# -*- 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")
needle = b"NativeEncrypt"

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)
        if needle not in dex:
            continue
        print("===", dex_name, "===")
        for m in re.finditer(rb"const-string[^/]*// string@[0-9a-f]+", dex):
            pass
        tmp = Path(__file__).resolve().parent.parent / "tmp" / "tmp_ne.dex"
        tmp.write_bytes(dex)
        out = subprocess.check_output(
            [str(DEXDUMP), "-d", str(tmp)], universal_newlines=True, errors="replace"
        )
        cap = False
        for line in out.splitlines():
            if "NativeEncrypt" in line:
                print(line.strip())
            if "Class descriptor" in line:
                current = line
            if "NativeEncrypt" in line:
                # print previous class context
                idx = out.splitlines().index(line)
                for prev in out.splitlines()[max(0, idx - 40) : idx + 5]:
                    if "Class descriptor" in prev or "name          :" in prev or "NATIVE" in prev:
                        print(prev.strip())
