# -*- coding: utf-8 -*-
"""Spawn TNG and strace for exit syscalls (needs root)."""
import subprocess
import time
import sys

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


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


def main():
    adb("shell", "am", "force-stop", PKG)
    time.sleep(0.5)
    adb("logcat", "-c")
    # start app
    adb(
        "shell",
        "monkey",
        "-p",
        PKG,
        "-c",
        "android.intent.category.LAUNCHER",
        "1",
    )
    time.sleep(0.4)
    out = adb("shell", "pidof", PKG)
    pid = out.stdout.strip().split()[0] if out.stdout.strip() else ""
    if not pid:
        print("no pid")
        return 1
    print("pid", pid)
    # strace briefly
    p = subprocess.Popen(
        [
            ADB,
            "shell",
            "su",
            "-c",
            f"timeout 8 strace -f -e trace=exit,exit_group,kill,tkill,tgkill,write -p {pid} 2>&1 | head -80",
        ],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
    )
    try:
        stdout, _ = p.communicate(timeout=15)
        print(stdout)
    except subprocess.TimeoutExpired:
        p.kill()
        print(p.stdout.read() if p.stdout else "timeout")
    print("alive?", adb("shell", "pidof", PKG).stdout.strip())
    return 0


if __name__ == "__main__":
    sys.exit(main())
