#!/usr/bin/env python3
"""Hide the SpringBoard alert window (rootVC = SBAlertItemRootViewController)."""
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 msgBool = new NativeFunction(e('objc_msgSend'), 'uchar', ['pointer', 'pointer']);
const msgUL = new NativeFunction(e('objc_msgSend'), 'ulong', ['pointer', 'pointer']);
const msgVoidBool = new NativeFunction(e('objc_msgSend'), 'void', ['pointer', 'pointer', 'uchar']);
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')));
let hidden = 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 rc = cn(rvc);
    if (rc.indexOf('Alert') >= 0 || rc.indexOf('alert') >= 0) {
        send({type: 'hide', win: i, rootVC: rc, wasHidden: Number(msgBool(w, sel('isHidden')))});
        msgVoidBool(w, sel('setHidden:'), 1);
        hidden++;
    }
}
send({type: 'done', hidden: hidden});
"""


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
    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(2)
    sess.detach()


if __name__ == '__main__':
    main()
