# -*- coding: utf-8 -*-
"""Quick reference: register crypto JNI targets for Frida."""
import re
import subprocess
import zipfile
from pathlib import Path

APK = Path(__file__).resolve().parent.parent / "apks" / "seabank_ph_base.apk"
DEXDUMP = Path(r"C:\Users\Administrator\AppData\Local\Android\Sdk\build-tools\37.0.0\dexdump.exe")
OUT = Path(__file__).resolve().parent / "frida" / "jni_targets.md"

TARGETS = [
    "Lcom/shopee/bke/lib/jni/utils/d;",          # NativeEncryptUtilsWrapper
    "Lcom/shopee/bke/lib/jni/utils/uvwuvwuv;",   # NativeEncryptUtils (sdkutils JNI)
    "Lcom/shopee/bke/lib/jni/utils/f;",          # SoUtils.loadSoLibrary
    "Lcom/shopee/shpssdkbank/uwuvuvvww/vvuuuuvvv;",
    "Lcom/shopee/shpssdkbank/wvvvuwwu;",
]

lines = [
    "# MariBank v3.22 register / crypto JNI targets",
    "",
    "## sdkutils (注册 body 加密)",
    "- `com.shopee.bke.lib.jni.utils.d` — NativeEncryptUtilsWrapper",
    "- `com.shopee.bke.lib.jni.utils.uvwuvwuv` — NativeEncryptUtils (native)",
    "- `com.shopee.bke.lib.jni.utils.f` — SoUtils → loads `libsdkutils.so`",
    "",
    "## shpssdk_bank (riskToken / DFP)",
    "- `vvuuuuvvv.wwvuwuwvu(Context)` — getRiskToken 真实入口",
    "- `wvvvuwwu` — native bridge (`vvuwuuvuu` → `wwvwvwuvv`)",
    "",
    "## dexdump natives",
    "",
]

with zipfile.ZipFile(str(APK)) as zf:
    dex = zf.read("classes8.dex")
    tmp = Path(__file__).resolve().parent / "tmp_frida_ref.dex"
    tmp.write_bytes(dex)
    out = subprocess.check_output(
        [str(DEXDUMP), "-d", str(tmp)], universal_newlines=True, errors="replace"
    )
    for target in TARGETS:
        lines.append("### " + target)
        cap = False
        for line in out.splitlines():
            if ("Class descriptor  : '" + target + "'") in line:
                cap = True
            elif cap and line.startswith("  Class descriptor") and target not in line:
                break
            if cap and ("NATIVE" in line or ("name          :" in line and "type          :" not in line)):
                safe = line.encode("ascii", "replace").decode()
                if "name          :" in safe:
                    lines.append("- " + safe.strip())
        lines.append("")

    dex11 = zf.read("classes11.dex")
    tmp.write_bytes(dex11)
    out11 = subprocess.check_output(
        [str(DEXDUMP), "-d", str(tmp)], universal_newlines=True, errors="replace"
    )
    for target in TARGETS[3:]:
        lines.append("### " + target)
        cap = False
        for line in out11.splitlines():
            if ("Class descriptor  : '" + target + "'") in line:
                cap = True
            elif cap and line.startswith("  Class descriptor") and target not in line:
                break
            if cap and "NATIVE" in line:
                lines.append("- " + line.encode("ascii", "replace").decode().strip())
        lines.append("")

OUT.write_text("\n".join(lines), encoding="utf-8")
print("written", OUT)
