#!/usr/bin/env python3
"""Launch build 43 and watch: verdict/notify/state hooks + periodic window-state polls."""
import os, sys, time, json, threading

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

BID = 'vn.gsm.md'

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 class_getInstanceMethod = new NativeFunction(e('class_getInstanceMethod'), 'pointer', ['pointer', 'pointer']);
const method_getImplementation = new NativeFunction(e('method_getImplementation'), 'pointer', ['pointer']);
const S = s => Memory.allocUtf8String(s);
const cls = n => objc_getClass(S(n));
const sel = s => sel_registerName(S(s));
const modOf = a => { const m = Process.findModuleByAddress(a); return m ? m.name + '+0x' + a.sub(m.base).toString(16) : a.toString(); };

const counts = {};

function hookImp(modName, off, label) {
    try {
        const m = Process.getModuleByName(modName);
        const addr = m.base.add(off);
        Interceptor.attach(addr, {
            onEnter(args) {
                counts[label] = (counts[label] || 0) + 1;
                if (counts[label] <= 4) {
                    const a = [];
                    for (let i = 0; i < 5; i++) a.push(args[i].toString());
                    send({type: 'hit', label: label, n: counts[label], args: a});
                }
            },
            onLeave(v) {
                if (counts[label] <= 4) send({type: 'ret', label: label, ret: v.toInt32()});
            }
        });
        send({type: 'hooked', label: label, addr: modOf(addr)});
    } catch (er) { send({type: 'hookerr', label: label, e: String(er)}); }
}

const bi = 'build-info';
hookImp(bi, 0xe0d0, 'verdict');
hookImp(bi, 0xe074, 'notify');
hookImp(bi, 0x4174, 'get');
hookImp(bi, 0x5730, 'addListener');
hookImp(bi, 0x298158, 'sd_willConnect');
hookImp(bi, 0x28feb8, 'df_launch');

// window wiring evidence
for (const [s2, l2] of [['setRootViewController:', 'setRootVC'], ['makeKeyAndVisible', 'makeKey']]) {
    const m = class_getInstanceMethod(cls('UIWindow'), sel(s2));
    if (!m.isNull()) {
        const imp = method_getImplementation(m);
        Interceptor.attach(imp, { onEnter(args) {
            counts[l2] = (counts[l2] || 0) + 1;
            if (counts[l2] <= 4) send({type: 'hit', label: l2, n: counts[l2], arg: args[2].toString()});
        } });
        send({type: 'hooked', label: l2, imp: modOf(imp)});
    }
}

setInterval(function () {
    const app = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer'])(
        cls('UIApplication'), sel('sharedApplication'));
    const dl = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer'])(app, sel('delegate'));
    const win = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer'])(dl, sel('window'));
    const msgBool = new NativeFunction(e('objc_msgSend'), 'uchar', ['pointer', 'pointer']);
    const rvc = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer'])(win, sel('rootViewController'));
    const cn = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer']);
    send({type: 'state', counts: counts,
          win: win.isNull() ? 'nil' : cn(win).readCString(),
          hidden: win.isNull() ? -1 : Number(msgBool(win, sel('isHidden'))),
          key: win.isNull() ? -1 : Number(msgBool(win, sel('isKeyWindow'))),
          root: rvc.isNull() ? 'nil' : cn(rvc).readCString()});
}, 3000);
"""


class Watchdog:
    def __init__(self, secs=90):
        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)


def main():
    Watchdog(90)
    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(2)
    pid = dev.spawn([BID])
    print('spawned', pid, flush=True)
    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()
    dev.resume(pid)
    time.sleep(18)
    print('watch done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
