# -*- coding: utf-8 -*-
import subprocess
import sys
import zipfile
import tempfile
import os

TARGET = "com/shopee/bke/lib/safemode/b;"
APK = sys.argv[1] if len(sys.argv) > 1 else "reverse/apks/seabank_ph_base.apk"
BT = None


def find_build_tools():
    base = os.environ.get("ANDROID_HOME") or os.path.expanduser(
        r"~\AppData\Local\Android\Sdk"
    )
    tools = os.path.join(base, "build-tools")
    versions = sorted(os.listdir(tools), reverse=True)
    return os.path.join(tools, versions[0], "dexdump.exe")


def main():
    dexdump = find_build_tools()
    with zipfile.ZipFile(APK) as zf:
        for name in zf.namelist():
            if not name.endswith(".dex"):
                continue
            data = zf.read(name)
            if TARGET.encode() not in data and b"Lcom/shopee/bke/lib/safemode/b;" not in data:
                continue
            print("FOUND in", name)
            tmp = tempfile.NamedTemporaryFile(suffix=".dex", delete=False)
            tmp.write(data)
            tmp.close()
            try:
                out = subprocess.check_output(
                    [dexdump, "-f", tmp.name], stderr=subprocess.STDOUT, text=True,
                    errors="ignore"
                )
                capture = False
                for line in out.splitlines():
                    if "Class descriptor  : 'Lcom/shopee/bke/lib/safemode/b;'" in line:
                        capture = True
                    elif capture and line.startswith("  Class descriptor"):
                        break
                    if capture:
                        if "name          :" in line or "type          :" in line or "Class descriptor" in line:
                            print(line)
            finally:
                os.unlink(tmp.name)


if __name__ == "__main__":
    main()
