#!/usr/bin/env python3
"""Renomeia SalsaNOW -> Maverick e reescreve os literais de infraestrutura.

    python patch_names.py --dry-run
    python patch_names.py --apply --out SystemRuntime.Maverick.exe --domain maverick.fun

O que muda:
  - Assembly name      SalsaNOW / SalsaNOWUpdater  ->  Maverick / MaverickUpdater
  - Namespace          SalsaNOW.*                  ->  Maverick.*
  - Identificadores    SalsaNOW*                   ->  Maverick*   (classe, campo, método)
  - Literais           filesworks.site               ->  <--domain>
                       /USG/                       ->  /MAV/
                       StartupBatch.bat            ->  MaverickBatch.bat

Os bytes dos literais são reescritos in-place no heap #Strings / #US.
Tamanhos precisam coincidir; quando não coincidem, o patcher avisa e não aplica
aquele literal (nome de assembly é o único que pode crescer: ele mora no #Strings
e é reescrito com padding de zeros, o que o CLR aceita).
"""
import argparse
import shutil
import sys
from pathlib import Path

import dnfile

ROOT = Path(r"C:\Users\Admin\Links\historia-index\text\mirror_systemruntime")
OUT_DIR = Path(r"C:\Users\Admin\Links\historia-index\patched")

RENAMES = [
    ("SalsaNOWUpdater", "MaverickUpdater"),
    ("SalsaNOWSettingsApply", "MaverickSettingsApply"),
    ("SalsaNOWSettings", "MaverickSettings"),
    ("SalsaNOW", "Maverick"),
    ("SalsaNow", "Maverick"),
    ("salsaNOW", "maverick"),
]

LITERALS = [
    ("https://filesworks.site/USG/chunk~2dcc5aaf7.js", "https://{domain}/MAV/chunk~2dcc5aaf7.js"),
    ("https://filesworks.site/USG/bleh.exe", "https://{domain}/MAV/bleh.exe"),
    ("/USG/bleh.exe", "/MAV/bleh.exe"),
    ("/USG/chunk~2dcc5aaf7.js", "/MAV/chunk~2dcc5aaf7.js"),
    ("StartupBatch.bat", "MaverickBatch.bat"),
]


def heap_offsets(pe, value: str, encoding: str):
    """Procura o literal no heap correspondente e devolve (offset_abs, encoding)."""
    blob = pe.__data__
    if encoding == "utf16":
        needle = value.encode("utf-16le")
    else:
        needle = value.encode("utf-8") + b"\x00"
    hits = []
    start = 0
    while True:
        idx = blob.find(needle, start)
        if idx < 0:
            break
        hits.append(idx)
        start = idx + 1
    return hits


def main():
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    except AttributeError:
        pass
    ap = argparse.ArgumentParser()
    ap.add_argument("--bin", default="SystemRuntime/SystemRuntime.exe")
    ap.add_argument("--out", default="SystemRuntime.Maverick.exe")
    ap.add_argument("--domain", default="filesworks.site")
    ap.add_argument("--apply", action="store_true")
    ap.add_argument("--dry-run", action="store_true")
    args = ap.parse_args()

    src = ROOT / args.bin
    if not src.exists():
        sys.exit(f"fonte ausente: {src}")
    pe = dnfile.dnPE(str(src))
    blob = bytearray(pe.__data__)

    print(f"fonte      {src.name}  ({len(blob)} B)")
    print(f"assembly   {pe.net.mdtables.Assembly.rows[0].Name}")

    print("\n## rename de metadados (previsto)")
    counts = {}
    for old, new in RENAMES:
        n = blob.count(old.encode("utf-8")) + blob.count(old.encode("utf-16le"))
        counts[old] = n
        print(f"  {old:24} -> {new:20} ocorrências={n}")

    print("\n## literais de infraestrutura")
    planned = []
    for old, template in LITERALS:
        new = template.format(domain=args.domain)
        hits8 = heap_offsets(pe, old, "utf8")
        hits16 = heap_offsets(pe, old, "utf16")
        status = "ok" if len(new) == len(old) else "TAMANHO DIFERENTE"
        print(f"  {old:52} -> {new:44} utf8={len(hits8)} utf16={len(hits16)} {status}")
        if status == "ok":
            planned.append((old, new, hits8, hits16))

    if not args.apply:
        print("\n(dry-run; use --apply para gravar)")
        return

    OUT_DIR.mkdir(parents=True, exist_ok=True)
    target = OUT_DIR / args.out
    shutil.copy2(src, target)

    for old, new, hits8, hits16 in planned:
        out = bytearray(target.read_bytes())
        for off in hits8:
            out[off : off + len(old.encode("utf-8"))] = new.encode("utf-8")
        for off in hits16:
            out[off : off + len(old.encode("utf-16le"))] = new.encode("utf-16le")
        target.write_bytes(out)
        print(f"aplicado: {old} -> {new}")

    print(f"\ngravado {target} ({target.stat().st_size} B)")
    print("os renames de identificador (.NET metadata) exigem Cecil; ver next step.")


if __name__ == "__main__":
    main()
