#!/bin/sh

if [ "$1" != "start" ]; then
	exit 0
fi

export UPDATE=/update
export UPDATE_SCRIPTS=/update/scripts
export UPDATE_DATA=/update/data

execute_script()
{
	echo -n "    Executing" `basename $1`": "
	( cd $UPDATE_DATA ; sh $1 )
	status=$?
	rm -f $1
	case $status in
	0)
		echo " Ok."
		;;
	100)
		echo " Rebooting."
		shutdown -r now
		sleep 3600
		;;
	*)
		echo " Failed: $status"
		;;
	esac
}

prefix()
{
	echo "."
	echo "Remote update started."
}

postfix()
{
	echo "Remote update finished."
	echo -n "Resuming local package initialization:"
}

idle=1
for script in ${UPDATE_SCRIPTS}/*.sh; do
	if [ -r ${script} ]; then
		if [ $idle -ne 0 ]; then
			prefix
			idle=0
		fi
		execute_script $script
	fi
done

find ${UPDATE_SCRIPTS} ${UPDATE_DATA} ! -type d -delete
chown -R root:operator ${UPDATE}
chmod -R 775 ${UPDATE}

if [ $idle -eq 0 ]; then
	postfix
fi
