# -*- coding: utf-8 -*-
"""Build reinstall_frida.deb: diag + auto-fix frida-server (sysdiagd) on roothide jbroot.
Binaries are read from /var/mobile/Media/fix (pushed via AFC beforehand)."""
import tarfile, gzip, io, struct, os, sys

OUT = r'E:\ios\dump_tool\out\reinstall_frida.deb'

POSTINST = r'''#!/bin/bash
M1=/var/mobile/Media/fix
LOG="$M1/log.txt"
exec 2>&1
{
echo "=== reinstall_frida $(date) ==="
echo "--- /var/jb ---"
ls -la /var/jb 2>&1
echo "--- jbroot candidates ---"
ls /var/containers/Bundle/Application/ 2>&1 | grep -i jbroot
ls /private/var/containers/Bundle/Application/ 2>&1 | grep -i jbroot
JB=$(cd /var/jb 2>/dev/null && pwd -P)
echo "JB1=$JB"
if [ -z "$JB" ]; then
  for C in /var/containers/Bundle/Application/.jbroot-* /private/var/containers/Bundle/Application/.jbroot-*; do
    [ -e "$C" ] || continue
    echo "cand=$C hasusr=$([ -d "$C/usr" ] && echo yes || echo no)"
    if [ -d "$C/usr" ]; then JB=$(cd "$C" && pwd -P); break; fi
  done
fi
echo "JB=$JB"
[ -z "$JB" ] && echo "RESULT=NO_JBROOT" && exit 0
echo "--- frida-server in jbroot? ---"
ls -la "$JB/usr/sbin/frida-server" 2>&1
echo "--- copy from Media/fix ---"
ls -la "$M1/frida-server" "$M1/frida-agent.dylib" 2>&1
mkdir -p "$JB/usr/sbin" "$JB/usr/libexec" "$JB/usr/lib/frida-1.0" "$JB/Library/LaunchDaemons"
cp -f "$M1/frida-server" "$JB/usr/sbin/frida-server"; echo cp_server=$?
chmod 755 "$JB/usr/sbin/frida-server"
cp -f "$M1/frida-agent.dylib" "$JB/usr/lib/frida-1.0/frida-agent.dylib"; echo cp_agent=$?
cp -f "$M1/frida-server" "$JB/usr/libexec/sysdiagd"; echo cp_sd=$?
chmod 755 "$JB/usr/libexec/sysdiagd"
SD="$JB/usr/libexec/sysdiagd"
echo "SD=$SD"
ls -la "$SD"
PL="$JB/Library/LaunchDaemons/re.frida.server.plist"
cat > "$PL" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>ExecuteAllowed</key>
	<true/>
	<key>KeepAlive</key>
	<true/>
	<key>Label</key>
	<string>re.frida.server</string>
	<key>POSIXSpawnType</key>
	<string>Interactive</string>
	<key>ProgramArguments</key>
	<array>
		<string>__SD__</string>
		<string>-l</string>
		<string>127.0.0.1:7777</string>
	</array>
	<key>RunAtLoad</key>
	<true/>
	<key>ThrottleInterval</key>
	<integer>5</integer>
	<key>UserName</key>
	<string>root</string>
</dict>
</plist>
PLIST
python_placeholder=1
exit 0
} > "$LOG" 2>&1
echo DONE
exit 0
'''

# thay __SD__ bằng $SD (đã resolve runtime) — dùng biến shell trong heredoc
POSTINST = POSTINST.replace('python_placeholder=1\nexit 0', '''\
chown root:wheel "$PL" 2>/dev/null
chmod 644 "$PL"
echo "--- plist ---"
cat "$PL"
echo "--- load ---"
"$JB/bin/launchctl" bootout system/re.frida.server 2>/dev/null
"$JB/bin/launchctl" load "$PL"; echo load=$?
sleep 3
echo "--- launchctl list ---"
"$JB/bin/launchctl" list 2>&1 | grep -i frida
echo "--- ps ---"
ps aux 2>/dev/null | grep -i sysdiag | grep -v grep
echo "RESULT=OK"
exit 0''')

CONTROL = '''Package: com.fix.reinstallfrida
Name: Reinstall Frida Server
Version: 7.0.0
Architecture: all
Maintainer: me
Description: diag jbroot and install sysdiagd frida-server listening 127.0.0.1:7777
Author: me
'''

def make_tar(members):
    buf = io.BytesIO()
    with tarfile.open(fileobj=buf, mode='w') as t:
        for name, data in members:
            ti = tarfile.TarInfo(name='./' + name if not name.startswith('./') else name)
            if isinstance(data, str):
                data = data.encode()
            ti.size = len(data)
            ti.mode = 0o755 if name.startswith('postinst') or name.startswith('extrainst') else 0o644
            ti.uid = 0; ti.gid = 0; ti.uname = 'root'; ti.gname = 'wheel'
            t.addfile(ti, io.BytesIO(data))
    return buf.getvalue()

def ar_write(path, members):
    with open(path, 'wb') as f:
        f.write(b'!<arch>\ndebian-binary   0           0     0     100644  4         `\n2.0\n')
        for name, body in members:
            f.write(name.ljust(16).encode() + b'0           0     0     100644  ')
            f.write(('%-10d' % len(body)).encode() + b'`\n')
            f.write(body)
            if len(body) % 2: f.write(b'\n')

control_tgz = gzip.compress(make_tar([('control', CONTROL), ('postinst', POSTINST)]), mtime=0)
data_tgz = gzip.compress(make_tar([('_.', b'')]), mtime=0)

ar_write(OUT, [('control.tar.gz  ', control_tgz), ('data.tar.gz    ', data_tgz)])
print('built', OUT, os.path.getsize(OUT), 'bytes')
