# -*- 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")

needles = [
    b"CharacterCrypto",
    b"sdkutils",
    b"SoUtils",
    b"dfp is empty",
    b"register scene",
    b"deviceToken",
    b"getRiskToken",
    b"encrypt",
    b"decrypt",
    b"/uapi/v2/register",
]

with zipfile.ZipFile(str(APK)) as zf:
    data = b"".join(zf.read(n) for n in zf.namelist() if n.endswith(".dex"))
    for n in needles:
        print(n.decode(), data.count(n))

    print("\n--- CharacterCrypto classes ---")
    for m in re.finditer(rb"L[^;]{0,100}CharacterCrypto[^;]{0,40};", data):
        print(m.group().decode()[1:-1].replace("/", "."))

    print("\n--- SoUtils classes ---")
    for m in re.finditer(rb"L[^;]{0,80}SoUtils[^;]{0,20};", data):
        print(m.group().decode()[1:-1].replace("/", "."))

    print("\n--- native methods in shpssdkbank ---")
    for dex_name in zf.namelist():
        if not dex_name.endswith(".dex"):
            continue
        dex = zf.read(dex_name)
        if b"shpssdkbank" not in dex:
            continue
        tmp = Path(__file__).resolve().parent.parent / "tmp" / "tmp_shps.dex"
        tmp.write_bytes(dex)
        out = subprocess.check_output(
            [str(DEXDUMP), "-d", str(tmp)], universal_newlines=True, errors="replace"
        )
        cap = False
        cls = ""
        for line in out.splitlines():
            if "Class descriptor  : 'Lcom/shopee/shpssdkbank/" in line:
                cap = True
                cls = line.split("'")[1]
            elif cap and line.startswith("  Class descriptor") and "shpssdkbank" not in line:
                cap = False
            if cap and ("0x0101" in line or "NATIVE" in line):
                print(cls.replace("L", "").replace(";", "").replace("/", "."), line.strip())
