#!/bin/sh

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

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

#export QT_QPA_EGLFS_KMS_CONFIG=/etc/eglfs.json
#export QT_QPA_EVDEV_TOUCHSCREEN_PARAMETERS="rotate=180"

DBG="-debug"
#TOUCH=""
#if [ $(grep -c 'eGalax\|ft5x\|ssd25\|Touchscreen' /proc/bus/input/devices) ]; then 
#	TOUCH="-touch"
#fi

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

	rm -f /tmp/nesis.exit

	echo "Starting ${APP} on" `date` >> ${LOGFILE}
	# touch is rotated in nesis III 8.4
	# -plugin evdevtouch:/dev/input/event1
	/nesis/nesis ${DBG} -style fusion 1>> ${LOGFILE} 2>&1
	APP_EXIT_CODE=$?
	echo "${APP} has exited with return code: $APP_EXIT_CODE on" `date` >> ${LOGFILE}

	if [ $APP_EXIT_CODE -gt 4 ]; then
		if [ $(grep -c sda1 /proc/partitions) == 1 ]; then
			mount -o remount,rw /media/sda1
			cp /tmp/log.txt /media/sda1/NesisDebugLog-$(date +'%F%M%S').txt
			mount -o remount,ro /media/sda1
			DBG="-debug"
		fi
	fi

	hwclock -w
	if [ -e /tmp/nesis.exit ]; then
		# overide real app exit code
		APP_EXIT_CODE=$(cat /tmp/nesis.exit)
	fi

	if [ $APP_EXIT_CODE == 2 ]; then
		# we have to reboot
		sync
		mount -o remount,ro /rw
		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 /rw
#umount -a

poweroff
