#!/bin/sh
set -eu
HERE=$(cd "$(dirname "$0")" && pwd)
IPA=${1:?usage: storefix-ipa.sh GAME.ipa [OUT.ipa]}
OUT=${2:-${IPA%.ipa}-storefix.ipa}
[ -e "$OUT" ] && { echo "$OUT exists"; exit 1; }
OUT=$(cd "$(dirname "$OUT")" && pwd)/$(basename "$OUT")
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
unzip -q "$IPA" -d "$WORK"
APP=$(find "$WORK/Payload" -maxdepth 1 -name '*.app' | head -1)
[ -n "$APP" ] || { echo "no Payload/*.app in $IPA"; exit 1; }
EXE=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$APP/Info.plist")
mkdir -p "$APP/Frameworks"
cp "$HERE/storefix-fat.dylib" "$APP/Frameworks/storefix.dylib"
python3 -I "$HERE/inject_dylib.py" "$APP/$EXE" @executable_path/Frameworks/storefix.dylib
(cd "$WORK" && zip -qry -X "$OUT.tmp" Payload)
mv "$OUT.tmp" "$OUT"
echo "wrote $OUT (unsigned; sign it with your sideloading tool)"
