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

methods = [
    ("Lcom/shopee/shpssdkbank/SHPSSDK;", "getRiskToken"),
    ("Lcom/shopee/shpssdkbank/wvvvuwwu;", "vvuwuuvuu"),
    ("Lcom/shopee/shpssdkbank/wvvvuwwu;", "vuwuuwvw"),
    ("Lcom/shopee/shpssdkbank/wvvvuwwu;", "vuwuuuwv"),
]

with zipfile.ZipFile(str(APK)) as zf:
    tmp = Path(__file__).resolve().parent.parent / "tmp" / "tmp11.dex"
    tmp.write_bytes(zf.read("classes11.dex"))
    out = subprocess.check_output(
        [str(DEXDUMP), "-d", str(tmp)], universal_newlines=True, errors="replace"
    )

for cls, method in methods:
    needle = f"{cls.replace('L', '').replace(';', '').split('/')[-1]}.{method}:"
    print("\n" + "=" * 70, cls, method)
    cap = False
    for line in out.splitlines():
        if needle in line.replace("com.shopee.shpssdkbank.", ""):
            cap = True
        if cap:
            print(line.encode("ascii", "replace").decode())
            if line.strip().startswith("catches") or (cap and line.strip() == "locals        :"):
                pass
        if cap and line.strip() == "" and "positions" in line:
            break
        if cap and line.startswith("      name") and method not in line and cap:
            # next method
            if methods.index((cls, method)) < len(methods) - 1:
                break

# classes8 - sdkutils / crypto
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(tmp)], universal_newlines=True, errors="replace"
    )
    for tag in ["CharacterCrypto", "SoUtils", "SecurityMain", "sdkutils", "encrypt"]:
        print("\n--- search", tag, "in classes8 ---")
        for line in out8.splitlines():
            if tag.lower() in line.lower() and ("Class descriptor" in line or "name          :" in line):
                print(line.encode("ascii", "replace").decode()[:200])
