# -*- coding: utf-8 -*-
"""Spawn MariBank, resume after script load, wait for Java."""
import frida
import sys
import time
from datetime import datetime
from pathlib import Path

PKG = "ph.seabank.seabank"
HERE = Path(__file__).resolve().parent
LOGS_DIR = HERE.parent / "logs" / "frida"
LOGS_DIR.mkdir(parents=True, exist_ok=True)
SCRIPT = HERE / "trace_maribank_register.js"
LOG = LOGS_DIR / ("trace_%s.log" % datetime.now().strftime("%Y%m%d_%H%M%S"))


def on_message(message, data):
    if message.get("type") == "send":
        line = message.get("payload")
    else:
        line = str(message)
    text = line if isinstance(line, str) else repr(line)
    print(text, flush=True)
    with open(LOG, "a", encoding="utf-8") as f:
        f.write(text + "\n")


def main():
    import subprocess
    adb = r"C:\Users\Administrator\AppData\Local\Android\Sdk\platform-tools\adb.exe"
    subprocess.run([adb, "shell", "am", "force-stop", PKG], capture_output=True)
    time.sleep(1)

    d = frida.get_usb_device(10)
    source = SCRIPT.read_text(encoding="utf-8")
    print("Spawning %s ..." % PKG)
    pid = d.spawn([PKG])
    session = d.attach(pid)
    script = session.create_script(source)
    script.on("message", on_message)
    script.load()
    time.sleep(2)
    d.resume(pid)
    print("Resumed pid=%s, log=%s" % (pid, LOG))
    print("等待 90s 让 Java Hook 就绪，然后 Sign up -> Next")
    try:
        for _ in range(120):
            time.sleep(1)
    except KeyboardInterrupt:
        pass
    session.detach()


if __name__ == "__main__":
    main()
