#!/bin/sh
### BEGIN INIT INFO
# Provides:          autostart
# Short-Description: Runs additional scripts after boot finished
### END INIT INFO

CMDNAME="${0##*/}"
PATH="/bin:/usr/bin"

SPICE3_USER="spice3"
AUTOSTART_USER="$SPICE3_USER"
AUTOSTART_PATH="/home/$AUTOSTART_USER/autostart"
USERBIN_PATH="/home/$AUTOSTART_USER/bin"
LOG_PATH="/home/${SPICE3_USER}/log"

# sanity checks
(id -u "${AUTOSTART_USER}" > /dev/null 2>&1) || (log "User ${AUTOSTART_USER} does not exist!"; exit 1)

if [ ! -d $AUTOSTART_PATH ]; then
	mkdir $AUTOSTART_PATH
	mkdir $USERBIN_PATH
	chown "${AUTOSTART_USER}":"${AUTOSTART_USER}" $AUTOSTART_PATH
	chown "${AUTOSTART_USER}":"${AUTOSTART_USER}" $USERBIN_PATH
	
	[ -d $AUTOSTART_PATH ] || (log "Path ${AUTOSTART_PATH} does not exist!"; exit 1)
fi

chmod 777 $AUTOSTART_PATH


function log() {
        /usr/bin/logger --id=$$ --tag "${CMDNAME}" "$*"
}

startStop()
{
	local file has_errors=0 retval
	log "Running all ${1} scripts from directory \"${AUTOSTART_PATH}\"... "
	for file in $AUTOSTART_PATH/*.$1; do
		if [ -x "${file}" ]; then
			log "Executing \"${file}\""
			su "${AUTOSTART_USER}" -c "${file}"
			retval=$?
			if [ ${retval} -ne 0 ]; then
				log "Execution of \"${file}\" failed with non zero status ${retval}."
				has_errors=1
			fi
		fi
	done
	#log "autostart: Done"
	return ${has_errors}
}

# Timeout thread that aborts wait for spice3_app startup, if startup did not finish within 60 seconds
timeout()
{
	count="0"
	while : ; do
		sleep 2
		c=$(pkill -SIGCONT -c -P $$ tail)
		if [ "${c}" -eq "0" ]; then
			break
		fi
		if (( "$count" > 30 )); then
			log "Error: spice3_app did not finish starting within 60 seconds!"
			pkill -P $$ tail
			break
		fi
		count=$(( $count + 1 ))
	done
}

case "$1" in
start)
	# If we are within the boot process (uptime less than 180 seconds) then we wait until spice3_app finishes startup.
	# Timeout thread will abort this wait after 60 seconds if something goes wrong.
	uptime=$(cut -d "." -f1 /proc/uptime)
	if (( "$uptime" < 180 )); then
		log "Waiting up to 60 seconds for the boot process to finish before running the scripts!"
		timeout&
		# Wait for spice3_app to completely finish startup. Some scripts may rely on firmware running
		tail -n0 -f "${LOG_PATH}/spice3rtb.error.log" | while read logline
		do
			[[ "${logline}" == *"Listening for connections on :::49374"* ]] && pkill -P $$ tail
		done
		
	fi
	startStop start
	;;

stop)
	startStop stop
	;;

restart)
	startStop stop
	startStop start
	;;

*)
	echo "Usage: /etc/init.d/autostart {start|stop|restart}"
	exit 1
	;;
esac

exit 0
