# -*- coding: utf-8 -*-
"""
observe_gate.py — spawn-gating quan sát bshield (log-only).
Chạy: python observe_gate.py <run-id> [ghi_chu]
Rồi trên iPhone mở app Driver bình thường. frida sẽ giữ app trước khi chạy,
gắn agent (hook P0-P4), rồi thả app chạy tiếp. App không bị DYLD_INSERT.
Ctrl+C để dừng.
"""
import frida, sys, os, time, json, datetime, socket

UDID = '2f04999241eb80cae2d8a6176504af07002b86bd'
BUNDLE = 'vn.gsm.md'
JS = r'E:\ios\dump_tool\observe_bshield_compiled.js'
OUTDIR = r'E:\ios\dump_tool\runs'

def main():
    args = sys.argv[1:]
    run_id = args[0] if args else 'run-gate'
    dur = 0
    note = []
    for a in args[1:]:
        if a.startswith('--dur='):
            dur = int(a.split('=', 1)[1])
        else:
            note.append(a)
    note = ' '.join(note)
    os.makedirs(OUTDIR, exist_ok=True)
    logfile = os.path.join(OUTDIR, '%s-%s.log' % (run_id, datetime.datetime.now().strftime('%H%M%S')))
    f = open(logfile, 'w', encoding='utf-8', buffering=1)

    def w(line):
        f.write(line + '\n')
        try: print(line[:300])
        except Exception: pass

    def on_message(msg, data):
        if msg.get('type') == 'send':
            p = msg['payload']
            if isinstance(p, dict):
                p['_log'] = logfile; p['_run'] = run_id; p['_note'] = note
            w(json.dumps(p, ensure_ascii=False))
        elif msg.get('type') == 'error':
            w(json.dumps({'ev': 'script_error', 'desc': msg.get('description')}, ensure_ascii=False))

    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')

    def on_spawn_added(spawn):
        w(json.dumps({'ev': 'spawn_added', 'pid': spawn.pid, 'identifier': spawn.identifier,
                      'at': datetime.datetime.now().isoformat()}))
        if spawn.identifier == BUNDLE:
            try:
                session = dev.attach(spawn.pid)
                session.on('detached', on_detached)
                script = session.create_script(open(JS, 'r', encoding='utf-8').read())
                script.on('message', on_message)
                script.load()
                w(json.dumps({'ev': 'agent_loaded_gated', 'pid': spawn.pid}))
            except Exception as e:
                w(json.dumps({'ev': 'gate_attach_error', 'err': str(e)[:300]}))
        dev.resume(spawn.pid)
        w(json.dumps({'ev': 'resumed', 'pid': spawn.pid}))

    def on_detached(reason, *a):
        w(json.dumps({'ev': 'DETACHED', 'reason': reason, 'at': datetime.datetime.now().isoformat()}))
        print('[!] detached: %s' % reason)

    dev.on('spawn-added', on_spawn_added)
    dev.enable_spawn_gating()
    w(json.dumps({'ev': 'gate_on', 'run': run_id, 'note': note,
                  'at': datetime.datetime.now().isoformat()}))
    print('[*] DANG CHO mo app %s tren iPhone (tap icon)... Ctrl+C de dung' % BUNDLE)
    try:
        t0 = time.time()
        while True:
            time.sleep(1)
            if dur and time.time() - t0 > dur:
                print('[*] het %ds — dung' % dur)
                break
    except KeyboardInterrupt:
        pass
    finally:
        try: dev.disable_spawn_gating()
        except Exception: pass
        # thả mọi spawn còn treo
        try:
            for s in dev.enumerate_pending_spawns():
                dev.resume(s.pid)
        except Exception: pass
        w(json.dumps({'ev': 'run_stop', 'at': datetime.datetime.now().isoformat()}))
        f.close()

if __name__ == '__main__':
    main()
