#!/usr/bin/env python3
"""Spawn, wait N s, attach: report app state, scene activation, thread count, window visibility."""
import os, sys, time, json, threading

sys.stdout.reconfigure(encoding='utf-8')
import frida

BID = 'vn.gsm.md'


class Watchdog:
    def __init__(self, secs=70):
        self.deadline = time.time() + secs
        threading.Thread(target=self._loop, daemon=True).start()

    def _loop(self):
        while True:
            time.sleep(0.25)
            if time.time() > self.deadline:
                print('HARD TIMEOUT', flush=True)
                os._exit(3)


JS = r"""
const libobjc = Process.getModuleByName('libobjc.A.dylib');
const e = n => libobjc.getExportByName(n);
const objc_getClass = new NativeFunction(e('objc_getClass'), 'pointer', ['pointer']);
const sel_registerName = new NativeFunction(e('sel_registerName'), 'pointer', ['pointer']);
const objc_msgSend = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
const msgBool = new NativeFunction(e('objc_msgSend'), 'uchar', ['pointer', 'pointer']);
const msgUL = new NativeFunction(e('objc_msgSend'), 'ulong', ['pointer', 'pointer']);
const S = s => Memory.allocUtf8String(s);
const cls = n => objc_getClass(S(n));
const sel = s => sel_registerName(S(s));
const cn = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer']);

const app = objc_msgSend(cls('UIApplication'), sel('sharedApplication'));
const appState = Number(msgUL(app, sel('applicationState')));
const scenes = objc_msgSend(app, sel('connectedScenes'));
const n = Number(msgUL(scenes, sel('count')));
const anyF = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'ulong']);
const sc = anyF(scenes, sel('anyObject'), 0);
const act = Number(msgUL(sc, sel('activationState')));
const dl = objc_msgSend(sc, sel('delegate'));
const win = objc_msgSend(dl, sel('window'));
const rvc = objc_msgSend(win, sel('rootViewController'));
const vcView = objc_msgSend(rvc, sel('view'));
const frame = objc_msgSend(vcView, sel('frame'));
const hidden = Number(msgBool(win, sel('isHidden')));
send({type: 'state', appState: appState, sceneCount: n, sceneActivation: act,
      winHidden: hidden, rootVC: cn(rvc).readCString(),
      view: cn(vcView).readCString(), frame: cn(frame).readCString().slice(0, 120)});
const threads = Process.enumerateThreads();
send({type: 'threads', n: threads.length, states: threads.map(t => t.state)});
"""


def main():
    delay = float(sys.argv[1]) if len(sys.argv) > 1 else 10.0
    Watchdog(70)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    for p in dev.enumerate_processes():
        if p.name == 'Driver':
            print('kill stale', p.pid, flush=True)
            dev.kill(p.pid)
    time.sleep(1.5)
    pid = dev.spawn([BID])
    dev.resume(pid)
    t0 = time.time()
    time.sleep(max(0.5, delay - (time.time() - t0)))
    try:
        sess = dev.attach(pid)
        s = sess.create_script(JS)
        s.on('message', lambda m, d: print('[frida]', json.dumps(m)[:400], flush=True))
        s.load()
        time.sleep(1.5)
        sess.detach()
        print('app alive at t=%.0fs' % delay, flush=True)
    except Exception as ex:
        print('attach failed (app dead?):', str(ex)[:120], flush=True)


if __name__ == '__main__':
    main()
