#!/usr/bin/env python3
"""Run shell commands as root on the RootHide device via the root frida-server (port 7777)."""
import frida, sys, time, subprocess, asyncio
sys.stdout.reconfigure(encoding='utf-8')

JS = r"""
const libc = Process.getModuleByName('libsystem_c.dylib');
const system = new NativeFunction(libc.getExportByName('system'), 'int', ['pointer']);
const cmds = CMDLIST;
for (const c of cmds) {
    const rc = system(Memory.allocUtf8String(c));
    send({type: 'cmd', cmd: c, rc: rc});
}
send({type: 'done'});
"""


def run(cmds, outfile='/var/mobile/Media/frout.txt', target='logd', script_timeout=25):
    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(target)
    if pid is None:
        raise SystemExit('target %s not running' % target)
    session = dev.attach(pid)
    body = 'const CMDLIST = %s;\n' % (repr_cmds(cmds),) + JS
    script = session.create_script(body)
    msgs = []
    script.on('message', lambda m, d: (msgs.append(m), print('[frida]', m)))
    script.load()
    time.sleep(script_timeout)
    session.detach()
    return msgs


def repr_cmds(cmds):
    import json
    return json.dumps(cmds)


if __name__ == '__main__':
    cmds = sys.argv[1:]
    if not cmds:
        cmds = [
            'id > /var/mobile/Media/frout.txt 2>&1',
            'ls -la /var/containers/Bundle/Application/ >> /var/mobile/Media/frout.txt 2>&1',
            'ls -d /var/containers/Bundle/Application/.jbroot-* >> /var/mobile/Media/frout.txt 2>&1',
            'ls /var/containers/Bundle/Application/.jbroot-*/usr/bin/uicache >> /var/mobile/Media/frout.txt 2>&1',
        ]
    run(cmds)
