#!/usr/bin/env python3
"""Attach to SpringBoard via the root frida-server and dismiss the presented system alert."""
import os, sys, time, json, threading

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


class Watchdog:
    def __init__(self, secs=60):
        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 msgUL = new NativeFunction(e('objc_msgSend'), 'ulong', ['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 cn = o => object_getClassName(o).readCString();
const idx = new NativeFunction(e('objc_msgSend'), 'pointer', ['pointer', 'pointer', 'ulong']);

const app = objc_msgSend(cls('UIApplication'), sel('sharedApplication'));
const windows = objc_msgSend(app, sel('windows'));
const n = Number(msgUL(windows, sel('count')));
send({type: 'windows', n: n});
let dismissed = 0;
for (let i = 0; i < n; i++) {
    const w = idx(windows, sel('objectAtIndex:'), i);
    const rvc = objc_msgSend(w, sel('rootViewController'));
    if (rvc.isNull()) continue;
    const presented = objc_msgSend(rvc, sel('presentedViewController'));
    if (!presented.isNull()) {
        send({type: 'presented', win: i, cls: cn(rvc), pcls: cn(presented)});
        // walk down the presented chain, then dismiss
        let top = presented;
        for (let k = 0; k < 4; k++) {
            const next = objc_msgSend(top, sel('presentedViewController'));
            if (next.isNull()) break;
            top = next;
        }
        send({type: 'top', cls: cn(top)});
        const msg2 = new NativeFunction(e('objc_msgSend'), 'void', ['pointer', 'pointer', 'pointer']);
        msg2(top, sel('dismissViewControllerAnimated:completion:'), ptr(0));
        dismissed++;
    }
}
send({type: 'done', dismissed: dismissed});
"""


def main():
    Watchdog(60)
    dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
    ps = {p.name: p.pid for p in dev.enumerate_processes()}
    pid = ps.get('SpringBoard')
    if not pid:
        print('SpringBoard not found')
        return
    print('attach SpringBoard', pid, flush=True)
    sess = dev.attach(pid)
    s = sess.create_script(JS)
    s.on('message', lambda m, d: print('[sb]', json.dumps(m)[:400], flush=True))
    s.load()
    time.sleep(3)
    sess.detach()


if __name__ == '__main__':
    main()
