# -*- coding: utf-8 -*-
"""Build fixfrida.deb: place frida-agent.dylib where frida-server expects it."""
import os, io, tarfile, time

OUT = r"E:\ios\dump_tool\out"
DEB = os.path.join(OUT, "fixfrida.deb")

control = """Package: com.fix.frida4
Name: Fix Frida 4
Version: 5.0.0
Architecture: all
Maintainer: me
Description: install frida agent into jbroot and restart server
Author: me
"""

postinst = r"""#!/bin/bash
M1=/var/mobile/Media/fix
M2=/rootfs/var/mobile/Media/fix
mkdir -p "$M1" "$M2" 2>/dev/null
mark() { echo "$1" >> "$M1/steps.txt" 2>/dev/null; echo "$1" >> "$M2/steps.txt" 2>/dev/null; }
rm -f "$M1/steps.txt" "$M2/steps.txt"
mark "v6_start"
JB=""
for C in /var/jb /var/containers/Bundle/Application/.jbroot-* /private/var/containers/Bundle/Application/.jbroot-*; do
  if [ -x "$C/usr/sbin/frida-server" ]; then JB="$C"; break; fi
done
mark "jb=$JB"
[ -z "$JB" ] && mark "no_jb" && exit 0
A="$JB/usr/libexec/frida-agent.dylib"
mark "agent_dpkg_size=$(stat -c %s "$A" 2>/dev/null)"
if [ ! -s "$A" ]; then
  cp -f "$M1/frida-agent.dylib" "$A" 2>/dev/null
  mark "agent_after_cp=$(stat -c %s "$A" 2>/dev/null)"
fi
chmod 755 "$A" 2>/dev/null
mkdir -p "$JB/usr/lib/frida-1.0" 2>/dev/null
cp -f "$A" "$JB/usr/lib/frida-1.0/frida-agent.dylib" 2>/dev/null
mark "alt_size=$(stat -c %s "$JB/usr/lib/frida-1.0/frida-agent.dylib" 2>/dev/null)"
killall sysdiagd 2>/dev/null
sleep 1
( "$JB/usr/libexec/sysdiagd" -l 127.0.0.1:7777 >/dev/null 2>&1 & )
sleep 2
mark "respawned"
mark "v6_end"
exit 0
"""

ct = io.BytesIO()
with tarfile.open(fileobj=ct, mode='w:gz') as tf:
    d = tarfile.TarInfo('./')
    d.type = tarfile.DIRTYPE
    d.mode = 0o755
    tf.addfile(d)

    def add(name, content, mode):
        data = content.encode('utf-8')
        ti = tarfile.TarInfo(name)
        ti.size = len(data)
        ti.mode = mode
        ti.mtime = int(time.time())
        tf.addfile(ti, io.BytesIO(data))

    add('control', control, 0o644)
    add('postinst', postinst, 0o755)
control_tgz = ct.getvalue()

dt = io.BytesIO()
with tarfile.open(fileobj=dt, mode='w:gz') as tf:
    d = tarfile.TarInfo('./')
    d.type = tarfile.DIRTYPE
    d.mode = 0o755
    tf.addfile(d)
data_tgz = dt.getvalue()
# nhung agent that (24.8MB) de dpkg tu dat dung cho
agent_blob = open(os.path.join(OUT, "agent_data.tar.gz"), "rb").read()

with open(DEB, 'wb') as f:
    def add_member(name, blob):
        f.write(name.encode('ascii').ljust(16)[:16])
        f.write(str(int(time.time())).encode().ljust(12))
        f.write(b'0'.ljust(6))
        f.write(b'0'.ljust(6))
        f.write(b'100644'.ljust(8))
        f.write(str(len(blob)).encode().ljust(10))
        f.write(b'`\n')
        f.write(blob)
        if len(blob) % 2:
            f.write(b'\n')
    f.write(b'!<arch>\n')
    add_member('debian-binary', b'2.0\n')
    add_member('control.tar.gz', control_tgz)
    add_member('data.tar.gz', agent_blob)

print("built:", DEB, os.path.getsize(DEB), "bytes")
