#!/bin/bash
function help {
echo "Usage: ipapatcher <IPA File>"
}
if [ $1 = "-h" ]; then
help
exit 1
fi
if [ $1 = "--help" ]; then
help
exit 1
fi
if [ ! -f $1 ] && [ ! $1 = "-h" ] &&  [ ! $1 = "--help" ]; then
echo "[X] Could not find IPA with filename $1"
exit 1
fi
echo "[*] Unzipping (May take a while depending on size of the app, be patient!)"
if [ ! -d "/tmp/IPAPatcher" ]; then
mkdir /tmp/IPAPatcher
else
rm -r /tmp/IPAPatcher
mkdir /tmp/IPAPatcher
fi
if [ ! $? -eq 0 ]; then
    echo "[X] Could not create dir /tmp/IPAPatcher, please run as root."
fi
mkdir /var/mobile/Documents/Patched > /dev/null 2>&1
unzip -d /tmp/IPAPatcher/ "$1" > /dev/null 2>&1
echo "[*] Finished unzipping!"
dir=`find /tmp/IPAPatcher/Payload/ -name '*.app'`
dir2=${dir#*Payload/}
dir3="${dir2%%.*}"
binary="/tmp/IPAPatcher/Payload/$dir3.app/$dir3"
plist="$binary.plist"
patch="/var/mobile/Documents/Patched/$dir3.patched.ipa"
echo "[*] Signing binary with entitlements..."
ldid -e "$binary" > "$plist"
if [ ! $? -eq 0 ]; then
    echo "[X] Error extracting entitlements from binary."
fi
sed -i '5 i\<true\/>' "$plist"
sed -i '5 i\<key>platform-application<\/key>' "$plist"
if [ ! $? -eq 0 ]; then
    echo "[X] Error adding entitlements to $plist, please check $plist"
    exit 1
fi
jtool --sign --ent "$plist" --inplace "$binary" > /dev/null 2>&1
if [ ! $? -eq 0 ]; then
    echo "[X] Error, could not sign binary."
else
echo "[*] Finished signing!"
rm "$plist" > /dev/null 2>&1
fi
echo "[*] Zipping..."
rm -r /Payload > /dev/null 2>&1
mv /tmp/IPAPatcher/Payload /Payload
zip -r "$patch" "/Payload" > /dev/null 2>&1
echo "[*] Finished zipping!"
rm -r /tmp/IPAPatcher/
rm -r /Payload
echo "[*] Output: $patch"