#!/usr/bin/env bash
# Reconstruit une image firmware de l'émulateur à partir de l'IPSW officiel iPod2,1.
#
#   ipod-build-fw [BUILD]      (défaut : 5H11a = iPhone OS 2.2.1)
#
# Étapes : téléchargement de l'IPSW (serveurs Apple) et des clés (api.ipsw.me), NOR (LLB, iBoot, DeviceTree, logos),
# déchiffrement du rootfs, adaptations pour l'émulateur (mkbase-rootfs), NAND. Résultat : ~/ipod-emu/images/BUILD/
set -euo pipefail

BUILD=${1:-5H11a}
E="${IPOD_EMU_HOME:-$HOME/ipod-emu}"
W="$E/fw-$BUILD"
OUT="$E/images/$BUILD"
BOOTROM="$E/images/5F138/bootrom"   # bootrom S5L8720 (release n72ap_v1 de qemu-ios)
case $BUILD in
    5F138) NAND_VERSION=1 ;;         # 2.1.1 : driver NAND au format 1
    *)     NAND_VERSION=2 ;;         # 2.2.x : iBoot 385.49 exige le format 2
esac

mkdir -p "$W/enc" "$W/dec" "$OUT" "$E/ipsw"

info=$(curl -fsS "https://api.ipsw.me/v4/ipsw/iPod2,1/$BUILD")
url=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["url"])' <<<"$info")
ipsw="$E/ipsw/$(basename "$url")"
[ -f "$ipsw" ] || { echo "Téléchargement de $url"; curl -fL -o "$ipsw" "$url"; }
curl -fsS "https://api.ipsw.me/v4/keys/ipsw/iPod2,1/$BUILD" > "$W/keys.json"
key() { python3 -c 'import json,sys; k=[k for k in json.load(open(sys.argv[1]))["keys"] if k["image"]==sys.argv[2]][0]; print(k["filename"], k["key"])' "$W/keys.json" "$1"; }

echo "== NOR"
unzip -qo "$ipsw" 'Firmware/all_flash/*' -d "$W/enc"
F=$(echo "$W"/enc/Firmware/all_flash/all_flash.n72ap.production)
nor="$E/qemu-ios-generate-nor"
rm -rf "$nor/data" && mkdir "$nor/data"
for pair in applelogo:applelogo batterylow0:batterylow0 batterylow1:batterylow1 dtree:DeviceTree \
            glyphcharging:glyphcharging glyphplugin:glyphplugin iboot:iBoot llb:LLB \
            needservice:needservice recoverymode:recoverymode; do
    cp "$F/${pair#*:}"*.img3 "$nor/data/${pair%%:*}.img3"
done
(cd "$nor" && ./generate_nor >/dev/null && mv nor.bin "$OUT/nor.bin")

echo "== rootfs"
read -r rootfs_dmg rootfs_key < <(key RootFS)
unzip -qo "$ipsw" "$rootfs_dmg" -d "$W/enc"
"$E/dmg2img/vfdecrypt" -i "$W/enc/$rootfs_dmg" -k "$rootfs_key" -o "$W/dec/rootfs.dmg" >/dev/null
part=$("$E/dmg2img/dmg2img" -l "$W/dec/rootfs.dmg" 2>&1 | sed -n 's/^partition \([0-9]*\): .*Apple_HFS.*/\1/p' | head -1)
"$E/dmg2img/dmg2img" -p "$part" "$W/dec/rootfs.dmg" -o "$W/dec/rootfs-$BUILD.img" >/dev/null 2>&1
"$E/bin/mkbase-rootfs" "$W/dec/rootfs-$BUILD.img" "$OUT/rootfs.img"

echo "== NAND"
"$E/gen-v1/mknand" "$OUT/rootfs.img" "$OUT/nand" "$NAND_VERSION"
echo "$NAND_VERSION" > "$OUT/nand-version"
echo ",legacy-nor=off,nand-write=on" > "$OUT/machine-opts"
ln -sf "$BOOTROM" "$OUT/bootrom"
echo "Image prête : $OUT  →  ipod-emu start -f -W -w $BUILD"
