#!/bin/sh

PATH=/usr/sbin:/usr/bin:/sbin:/bin
_FUNCTIONS=/etc/rc.d/functions
[ -f ${_FUNCTIONS} ] && . ${_FUNCTIONS}

NAME="jailbreak"
KEY_DIR="/etc/uks"
KEYFILES="${KEY_DIR}/pubprodkey01.pem ${KEY_DIR}/pubprodkey02.pem "
EMERGENCY="/mnt/us/emergency.sh"
OTAUP=/usr/sbin/otaup
UPDATE_FILE=
BLOCK_SIZE=64

get_otaup_functions() {
	echo "#!/bin/sh" > $1
	sed -n '/^extract_bundle/,/^}$/p' ${OTAUP} >> $1
	sed -n '/^verify_signature/,/^}$/p' ${OTAUP} >> $1
	sed -n '/^verify_bundle_files/,/^}$/p' ${OTAUP} >> $1
	chmod +x $1
	[ -f $1 ] && . $1
}

bind_keys() {
	# Don't mount twice...
    if ! grep "${KEY_DIR}/pubprodkey01.pem" /proc/mounts > /dev/null 2>&1 ; then
        msg "mounting custom key" I
        mount --bind ${KEY_DIR}/pubprodkey01.hack.pem ${KEY_DIR}/pubprodkey01.pem
    else
        msg "looks like the custom key is already mounted" W
    fi
}

unbind_keys() {
	if grep "${KEY_DIR}/pubprodkey01.pem" /proc/mounts > /dev/null 2>&1 ; then
	    msg "unmounting custom key" I
	    umount -l ${KEY_DIR}/pubprodkey01.pem
	fi
}

stop() {
	# In here, stop means start
	UPDATE_FILE=`find /mnt/us/ -maxdepth 1 -type f -print0 | grep -i "/mnt/us/update.*\.bin$" | head -1`

	if [ -z ${UPDATE_FILE} ]; then
		exit 0
	fi
	
	TMPDIR=/tmp/.update-check-tmp.$$
	mkdir ${TMPDIR}
	get_otaup_functions /tmp/otaup_functions
	extract_bundle ${UPDATE_FILE} ${TMPDIR} > /dev/null 2>&1
    verify_bundle_files ${TMPDIR} > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		msg "custom key requested" I
	    bind_keys
	else
		msg "official keys requested" I
		unbind_keys
	fi
	rm -rf ${TMPDIR}
	rm -f /tmp/otaup_functions
}

start() {
	# First things first, check for an emergency script
	if [ -f ${EMERGENCY} ] ; then
		# We got one, make it executable and use it
		[ -x ${EMERGENCY} ] || chmod +x ${EMERGENCY}
		# Run it...
		${EMERGENCY}
		# And GET OUT! NOW!
		exit 0
	fi

	unbind_keys
}

case "$1" in
  start)
	start
  ;;
  stop)
	stop
  ;;
  restart|force-reload)
	start
	stop
  ;;
  *)
	echo "Usage: /etc/init.d/$NAME {start|stop|restart|force-reload}" >&2
	exit 1
  ;;
esac

exit 0