#!/bin/bash
set -e
cd "$(dirname "$0")"

function error { echo "Error: $1" >&2; exit 1; }

# Modify these to specify a custom install path
MODULE_PATH="$THEOS/mod/jailed/"
TEMPLATE_PATH="$THEOS/templates/ios/kabiroberai/"
SUBSTRATE_PATH="./Library/Frameworks/CydiaSubstrate.framework"
SUBSTRATE_VERSION="0.9.6301"
SUBSTRATE="lib/CydiaSubstrate_$SUBSTRATE_VERSION.framework"

[ -d "$THEOS" ] || error "\"$THEOS\" is not a directory. Aborting…"

# Install Substrate
if [[ ! -d module/$SUBSTRATE ]]; then
	echo "Downloading CydiaSubstrate.framework ($SUBSTRATE_VERSION)…"
	curl -#Lo substrate.deb "http://apt.saurik.com/debs/mobilesubstrate_${SUBSTRATE_VERSION}_iphoneos-arm.deb"
	ar -x substrate.deb data.tar.lzma
	tar --lzma --strip-components 3 -xf data.tar.lzma "$SUBSTRATE_PATH"
	rm -rf substrate.deb data.tar.lzma 
	# remove any older copies of Substrate before moving the new one into place
	rm -rf module/lib/CydiaSubstrate*.framework
	mv CydiaSubstrate.framework "module/$SUBSTRATE"
	echo "Successfully installed CydiaSubstrate.framework"
fi
plutil -convert binary1 "module/$SUBSTRATE/Info.plist" || true
rm -rf "module/$SUBSTRATE/Libraries" "module/$SUBSTRATE/Commands"

# Install module
ln -fs "$PWD/update" "module/bin/update"
mkdir -p "$MODULE_PATH"
rm -rf "$MODULE_PATH"/*
cp -a module/* "$MODULE_PATH"
mv "$MODULE_PATH/$SUBSTRATE" "$MODULE_PATH/lib/CydiaSubstrate.framework"
echo "*" > "$MODULE_PATH/.gitignore"
echo "Successfully installed module."

# Install template
"$THEOS/bin/nicify.pl" template 2> /dev/null || error "Failed to nicify template"
mkdir -p "$TEMPLATE_PATH"
rm -rf "$TEMPLATE_PATH"/*
mv *.nic.tar "$TEMPLATE_PATH/jailed.nic.tar"
echo "*" > "$TEMPLATE_PATH/.gitignore"
echo "Successfully installed template."
