# -*- 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/SHPSSDK;",
    "Lcom/shopee/shpssdk/SHPSSDK;",
]
with zipfile.ZipFile(str(APK)) as zf:
    for dex_name in ["classes11.dex", "classes10.dex", "classes6.dex"]:
        tmp = Path(__file__).resolve().parent.parent / "tmp" / "tmp_scan.dex"
        tmp.write_bytes(zf.read(dex_name))
        out = subprocess.check_output(
            [str(DEXDUMP), "-d", str(tmp)], universal_newlines=True, errors="replace"
        )
        for target in targets:
            capture = False
            for line in out.splitlines():
                if f"Class descriptor  : '{target}'" in line:
                    capture = True
                    print("===", dex_name, target, "===")
                elif capture and line.startswith("  Class descriptor"):
                    break
                if capture and ("native" in line.lower() or "loadLibrary" in line
                                or "System" in line and "load" in line):
                    print(line.strip())
                if capture and "name          :" in line and "type          :" in line:
                    pass
                if capture and "access        : 0x0101" in line or (
                        capture and "NATIVE" in line):
                    print(line.strip())

# also grep dex binary for loadLibrary strings near shpssdk
with zipfile.ZipFile(str(APK)) as zf:
    data = zf.read("classes11.dex")
    for m in re.finditer(rb"libshpssdk[^\x00]{0,40}", data):
        print("str", m.group().decode("latin1"))
