#!/bin/sh

if [[ -f /var/reboot ]]; then
	rm /var/reboot
	sync
	reboot
	sleep 3
fi

APP_EXIT_CODE=1
LOGFILE=/tmp/log.txt
export APP_RESTART=0
APP=nesis

KBD=$(cat /proc/bus/input/devices | sed -n '/Gumu/{nnnn;p;}' | sed -e "s/.*event/\/dev\/input\/event/")
cd /nesis

# go to high speed & stay there - 864MHz
echo "performance" > /sys/bus/cpu/devices/cpu0/cpufreq/scaling_governor

TOUCH=$(grep -c 'eGalax\|ft5x_ts\|ssd25' /proc/bus/input/devices)

while [ $APP_EXIT_CODE != 0 ]; do
	let APP_RESTART++

	echo "Starting ${APP} on" `date` | tee -a ${LOGFILE}
	# touch is rotated in nesis III 8.4
	export QT_QPA_EVDEV_TOUCHSCREEN_PARAMETERS="rotate=180"
	if [ $TOUCH == 1 ]; then
		/nesis/nesis -touch -plugin evdevkeyboard:$KBD -style fusion 1>> ${LOGFILE} 2>&1
	else
		/nesis/nesis -plugin evdevkeyboard:$KBD -style fusion 1>> ${LOGFILE} 2>&1
	fi
	APP_EXIT_CODE=$?
	echo "${APP} has exited with return code: $APP_EXIT_CODE on" `date` | tee -a ${LOGFILE}

#	hwclock -w

	if [ $APP_EXIT_CODE == 2 ]; then
		# we have to reboot
		sync
		mount -o remount,ro /
		reboot
	fi

	if [ $APP_EXIT_CODE != 0 ]; then
		# do not respawn too fast
		sleep 2
	fi
done

# we have exited cleanly, make shutdown
sync
mount -o remount,ro /
umount -a

poweroff
#sleep 0.8
#echo poweroff > /proc/gumu

