# -*- coding: utf-8 -*-
"""Scan TNG DEX for Aliyun TigerTally / abort / SI_USER suicide helpers."""
import re
import zipfile
from pathlib import Path

APK = Path(__file__).resolve().parents[1] / "apks" / "tng" / "base.apk"

KEYS = [
    b"TigerTally",
    b"aliyun",
    b"Aliyun",
    b"com/aliyun/TigerTally",
    b"UnhandledEvent detected",
    b"finishAllActivityAndKillApp",
    b"trackUnhandledEvent",
    b"SI_USER",
    b"raise",
    b"SIGABRT",
    b"pthread_kill",
    b"dispatchUncaughtException",
    b"AppProtect",
    b"promon",
    b"xwwqazamx",
]


def main():
    with zipfile.ZipFile(APK) as z:
        entries = [(n, z.read(n)) for n in z.namelist() if n.endswith(".dex")]

    print("=== key hits ===")
    for name, data in entries:
        for k in KEYS:
            c = data.count(k)
            if c:
                print(f"{name}: {k.decode('utf-8','ignore')} x{c}")

    print("\n=== TigerTally class descriptors ===")
    all_data = b"".join(d for _, d in entries)
    classes = sorted(set(re.findall(rb"Lcom/aliyun/TigerTally/[A-Za-z0-9_/$]*;", all_data)))
    for c in classes[:80]:
        print(c.decode())
    print("total", len(classes))

    print("\n=== nearby strings TigerTally ===")
    for m in re.finditer(rb"TigerTally[\x20-\x7e]{0,60}", all_data):
        print(m.group().decode("ascii", "ignore"))

    print("\n=== finishAll / Unhandled contexts ===")
    for pat in [
        b"finishAllActivityAndKillApp",
        b"UnhandledEvent detected",
        b"trackUnhandledEvent",
        b"dispatchUncaughtException",
    ]:
        idx = all_data.find(pat)
        if idx < 0:
            continue
        ctx = all_data[max(0, idx - 40) : idx + len(pat) + 80]
        printable = "".join(chr(b) if 32 <= b < 127 else "." for b in ctx)
        print(pat.decode(), "=>", printable)


if __name__ == "__main__":
    main()
