# -*- coding: utf-8 -*-
import subprocess
import time

import frida

ADB = r"C:\Users\Administrator\AppData\Local\Android\Sdk\platform-tools\adb.exe"
PKG = "my.com.tngdigital.ewallet"


def adb(*a):
    return subprocess.run([ADB, *a], capture_output=True, text=True)


def main():
    adb("shell", "am", "force-stop", PKG)
    adb("logcat", "-c")
    time.sleep(0.3)
    d = frida.get_usb_device(10)
    pid = d.spawn([PKG])
    s = d.attach(pid)
    sc = s.create_script('send("empty ok " + String(Process.id));')
    sc.on("message", lambda m, _d: print(m, flush=True))
    sc.load()
    print("resume", pid, flush=True)
    d.resume(pid)
    for i in range(10):
        time.sleep(1)
        p = adb("shell", "pidof", PKG).stdout.strip()
        print("t=%d %s" % (i + 1, p or "DEAD"), flush=True)
        if not p:
            break
    print("--- death lines ---", flush=True)
    for line in adb("logcat", "-d").stdout.splitlines():
        if "exited cleanly" in line or "has died" in line and "tngdigital" in line:
            print(line[:240], flush=True)
        if "TngRoot" in line and ("install" in line or "short-circuit" in line or "blocked" in line):
            print(line[:240], flush=True)


if __name__ == "__main__":
    main()
