#!/usr/bin/env python3
"""Launch build 46 via uiopen, attach within the 20 s launch-watchdog window, and
probe the live UI state: what does UIApplication.delegate / the scene / the window
look like, and is Flutter ever created?"""
import os, subprocess, 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 object_getClassName = new NativeFunction(e('object_getClassName'), 'pointer', ['pointer']);
const S = s => Memory.allocUtf8String(s);
const cls = n => objc_getClass(S(n));
const sel = s => sel_registerName(S(s));
const m0 = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer']);
const anyF = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'ulong']);
const drv = Process.getModuleByName('Driver');

function snap(tag) {
    try {
        const app = m0(cls('UIApplication'), sel('sharedApplication'));
        const dg = m0(app, sel('delegate'));
        const scenes = m0(app, sel('connectedScenes'));
        const sc = anyF(scenes, sel('anyObject'), 0);
        const sdg = sc.isNull() ? ptr(0) : m0(sc, sel('delegate'));
        let win = ptr(0), rvc = ptr(0), hidden = -1;
        if (!sdg.isNull()) {
            win = m0(sdg, sel('window'));
            if (!win.isNull()) {
                rvc = m0(win, sel('rootViewController'));
                hidden = win.add(0x20).readU8();
            }
        }
        const adWin = dg.isNull() ? ptr(0) : m0(dg, sel('window'));
        let adRvc = ptr(0);
        if (!adWin.isNull()) adRvc = m0(adWin, sel('rootViewController'));
        send({type: 'snap', tag: tag,
              appDel: dg.isNull() ? 'nil' : object_getClassName(dg).readCString(),
              sceneDel: sdg.isNull() ? 'nil' : object_getClassName(sdg).readCString(),
              win: win.isNull() ? 'nil' : object_getClassName(win).readCString(),
              hidden: hidden,
              rootVC: rvc.isNull() ? 'nil' : object_getClassName(rvc).readCString(),
              adWin: adWin.isNull() ? 'nil' : object_getClassName(adWin).readCString(),
              adRootVC: adRvc.isNull() ? 'nil' : object_getClassName(adRvc).readCString()});
    } catch (er) { send({type: 'snap_err', tag: tag, e: String(er)}); }
}

try { Interceptor.attach(drv.base.add(0x3271c), { onEnter() { send({type: 'REAL_SCENE_FN'}); } }); } catch (er) {}
const hooked = {};
const iv = setInterval(() => {
  for (const [cn, sn, label] of [['FlutterEngine', 'run', 'fe_run'], ['FlutterEngine', 'runWithEntrypoint:', 'fe_run1'],
      ['FlutterViewController', 'initWithEngine:nibName:bundle:', 'fvc_init'], ['FlutterViewController', 'viewDidLoad', 'fvc_vdl']]) {
    const k = cn + '|' + sn; if (hooked[k]) continue;
    const c = cls(cn); if (c.isNull()) continue;
    const m = class_getInstanceMethod(c, sel(sn)); if (m.isNull()) continue;
    hooked[k] = true;
    try { Interceptor.attach(method_getImplementation(m), { onEnter() { send({type: 'HIT', label: label}); } });
          send({type: 'hooked', label: label}); } catch (er) {}
  }
}, 400);
setTimeout(() => clearInterval(iv), 25000);

snap('attach');
setTimeout(() => snap('t3'), 3000);
setTimeout(() => snap('t6'), 6000);
setTimeout(() => snap('t10'), 10000);
"""


def main():
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    # launch
    subprocess.run([r'E:\ios\work319\fv17\Scripts\python.exe', r'E:\ios\work319\runsh.py',
                    r'E:\ios\work319\launch46b.sh', '/var/mobile/Media/l46d.txt', '180'],
                   capture_output=True, timeout=120)
    # attach fast
    pid = None
    t0 = time.time()
    while time.time() - t0 < 16:
        try:
            pid = dev.get_process('Driver').pid
            break
        except Exception:
            time.sleep(0.2)
    print('attached pid', pid, 'after %.1fs' % (time.time() - t0), flush=True)
    if not pid:
        print('app did not stay running', flush=True)
        return
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', lambda m, d: print('[frida]', json.dumps(m)[:600], flush=True))
    s.load()
    time.sleep(14)
    print('done', flush=True)
    try:
        sess.detach()
    except Exception:
        pass


if __name__ == '__main__':
    main()
