#!/bin/bash

function finish() {
	f="${1}"

	# No control fd: bail out
	[[ -z "${f}" || -z "${CYDIA}" ]] && return
	cydia=(${CYDIA})

	# Cydia control fd version != 1: bail out
	[[ ${cydia[1]} -eq 1 ]] || return

	echo "finish:${f}" >&${cydia[0]}
}

# Clear Inbox folder
if [ -d "/var/mobile/Library/Application Support/Containers/jp.soh.reprovision.ios/Documents/Inbox" ]; then
	rm -rf "/var/mobile/Library/Application Support/Containers/jp.soh.reprovision.ios/Documents/Inbox"
fi

# Check if old daemon exists
{
	if [ -f "/usr/bin/reprovisiond" ]; then
		echo "Why are you install ReProvision from pirate repo although it is free?"
		echo "If you don't know the official repository, maybe you don't even know that there is a great service in this world called Google."
		echo "Uninstall ReProvision first, and then install ReProvision Reborn from official repo."
		echo "Good bye."
		exit 1
	fi
}

# Handle the daemon
echo "(Re)-loading daemon..."
chown root /Library/LaunchDaemons/jp.soh.reprovisiond.plist

# Unload for an upgrade. - Might spew an error, so hide that.
/bin/launchctl unload /Library/LaunchDaemons/jp.soh.reprovisiond.plist 2>/dev/null || /sbin/launchctl unload /Library/LaunchDaemons/jp.soh.reprovisiond.plist 2>/dev/null
/bin/launchctl load /Library/LaunchDaemons/jp.soh.reprovisiond.plist 2>/dev/null || /sbin/launchctl load /Library/LaunchDaemons/jp.soh.reprovisiond.plist

# # Reload application cache (is this still needed?)
echo "Reloading application cache"
uicache -p /Applications/ReProvision.app

# Classic easter egg
echo "Do, or do not. There is no try."

# Finally, request Cydia to restart SpringBoard after installation.
# This is ensure we catch cases where users need to log in after install.
finish restart
