# -*- coding: utf-8 -*-
"""Dump riskToken + requestDefense + register crypto call chain."""
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 = [
    ("classes11.dex", "Lcom/shopee/shpssdkbank/SHPSSDK;", "getRiskToken"),
    ("classes11.dex", "Lcom/shopee/shpssdkbank/SHPSSDK;", "requestDefense"),
    ("classes11.dex", "Lcom/shopee/shpssdkbank/uwuvuvvww/vvuuuuvvv;", "wwvuwuwvu"),
    ("classes11.dex", "Lcom/shopee/shpssdkbank/uwuvuvvww/vvuuuuvvv;", "wuvwuvwwu"),
    ("classes11.dex", "Lcom/shopee/shpssdkbank/wvvvuwwu;", "wwvwvwuvv"),
    ("classes11.dex", "Lcom/shopee/shpssdkbank/wvvvuwwu;", "vvuwuuvuu"),
]

def dump_method(out, cls, method):
    cls_short = cls.replace("L", "").replace(";", "").replace("/", ".")
    needle = cls_short + "." + method + ":"
    print("\n" + "=" * 72)
    print(cls_short, method)
    cap = False
    lines = []
    for line in out.splitlines():
        if needle in line:
            cap = True
        if cap:
            lines.append(line)
            if len(lines) > 1 and line.strip().startswith("name          :") and method not in line:
                break
    for line in lines[:80]:
        print(line.encode("ascii", "replace").decode())

with zipfile.ZipFile(str(APK)) as zf:
    for dex_name, cls, method in TARGETS:
        tmp = Path(__file__).resolve().parent.parent / "tmp" / "_tmp.dex"
        tmp.write_bytes(zf.read(dex_name))
        out = subprocess.check_output(
            [str(DEXDUMP), "-d", str(tmp)], universal_newlines=True, errors="replace"
        )
        dump_method(out, cls, method)

# classes8 CharacterCrypto / SoUtils
print("\n" + "=" * 72, "classes8 crypto classes")
with zipfile.ZipFile(str(APK)) as zf:
    tmp = Path(__file__).resolve().parent.parent / "tmp" / "_tmp8.dex"
    tmp.write_bytes(zf.read("classes8.dex"))
    out8 = subprocess.check_output(
        [str(DEXDUMP), "-d", str(tmp8)], universal_newlines=True, errors="replace"
    )
    cap = False
    for line in out8.splitlines():
        if "Class descriptor" in line and (
            "CharacterCrypto" in line or "SoUtils" in line or "sdkutils" in line.lower()
        ):
            print("\n---", line.strip())
            cap = True
            continue
        if cap:
            if line.startswith("  Class descriptor") and "CharacterCrypto" not in line:
                cap = False
                continue
            if "name          :" in line or "NATIVE" in line or "loadLibrary" in line:
                print(line.strip()[:180])
