JB=$(ls -d /var/containers/Bundle/Application/.jbroot-* 2>/dev/null | head -1)
APP="$JB/Applications/Driver.app"
M=/rootfs/private/var/mobile/Media
echo "APP=$APP"
for p in $(launchctl list 2>/dev/null | grep "UIKitApplication:vn.gsm.md" | awk '{print $1}'); do
  [ "$p" != "-" ] && kill -9 "$p" 2>/dev/null && echo "killed $p"
done
sleep 1
echo "--- wipe + untar FULL build 54 (original Apple + decrypted __TEXT + patches) ---"
rm -rf "$APP"
mkdir -p "$APP"
tar -xf "$M/gsm54.tar" -C "$(dirname "$APP")" 2>&1 | tail -2
chmod -R 755 "$APP"
echo "--- sign all Mach-O ---"
"$JB/usr/bin/ldid" -S "$APP/Driver" && echo drv_signed
"$JB/usr/bin/ldid" -S "$APP/Frameworks/build-info.framework/build-info" && echo bi_signed
n=0; f=0
for fw in $(find "$APP/Frameworks" -type f 2>/dev/null); do
  if head -c 4 "$fw" 2>/dev/null | od -An -tx1 2>/dev/null | grep -q "cf fa ed fe"; then
    if "$JB/usr/bin/ldid" -S "$fw" >/dev/null 2>&1; then n=$((n+1)); else f=$((f+1)); echo "FAIL $fw"; fi
  fi
done
echo "frameworks signed=$n failed=$f"
echo "--- register + launch ---"
"$JB/usr/bin/uicache" -p "$APP" 2>&1 | head -2
"$JB/usr/bin/uiopen" --bundleid vn.gsm.md 2>&1 | head -2
sleep 10
launchctl list 2>/dev/null | grep "UIKitApplication:vn.gsm.md" | head -2
echo "--- newest crashes ---"
ls -t /rootfs/private/var/mobile/Library/Logs/CrashReporter/ 2>/dev/null | grep -i "^Driver" | head -2
echo INST54_DONE
