# -*- coding: utf-8 -*-
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")

targets = [
    "Lcom/shopee/shpssdkbank/wvvvuwwu;",
    "Lcom/shopee/shpssdkbank/uwuvuvvww/wvvuuwvwu;",
    "Lcom/shopee/shpssdkbank/uwuvuvvww/uvwuuuuuw/vvvvuwwvu;",
    "Lcom/shopee/shpssdkbank/SHPSSDK;",
    "Lcom/shopee/shpssdkbank/ShpssInstall;",
]

with zipfile.ZipFile(str(APK)) as zf:
    for dex_name in zf.namelist():
        if not dex_name.endswith(".dex"):
            continue
        dex = zf.read(dex_name)
        hit = any(t.replace("L", "").replace(";", "") in dex.decode("latin1", errors="ignore") for t in targets)
        if not hit:
            continue
        tmp = Path(__file__).resolve().parent.parent / "tmp" / "tmp_native.dex"
        tmp.write_bytes(dex)
        out = subprocess.check_output(
            [str(DEXDUMP), "-d", str(tmp)], universal_newlines=True, errors="replace"
        )
        for target in targets:
            if target.replace("L", "").replace(";", "") not in dex.decode("latin1", errors="ignore"):
                continue
            print("\n" + "=" * 70)
            print(dex_name, target)
            cap = False
            for line in out.splitlines():
                if f"Class descriptor  : '{target}'" in line:
                    cap = True
                elif cap and line.startswith("  Class descriptor") and target not in line:
                    break
                if cap:
                    safe = line.encode("ascii", "replace").decode()
                    if any(k in safe for k in ["name", "type", "access", "NATIVE", "Method", "loadLibrary", "register"]):
                        print(safe)

# find sdkutils / crypto manager classes
with zipfile.ZipFile(str(APK)) as zf:
    data = b"".join(zf.read(n) for n in zf.namelist() if n.endswith(".dex"))
    print("\n--- sdkutils / crypto / dfp classes ---")
    for pat in [
        rb"Lcom/[^;]{0,80}sdkutils[^;]{0,20};",
        rb"Lcom/[^;]{0,80}[Cc]rypto[^;]{0,40};",
        rb"Lcom/[^;]{0,80}dfp[^;]{0,30};",
        rb"Lcom/[^;]{0,80}SecurityMain[^;]{0,20};",
    ]:
        found = set()
        for m in re.finditer(pat, data):
            s = m.group().decode()[1:-1].replace("/", ".")
            if s not in found:
                found.add(s)
                print(s)
