#!/bin/sh

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

# do the defered init
deferedinit () {
	modprobe ehci_hcd
	modprobe twl4030-usb
	modprobe musb_hdrc
	modprobe sd_mod

	# tvp5151
	modprobe omap3-isp
	
	media-ctl -r -l '"tvp5150 3-005d":0->"OMAP3 ISP CCDC":0[1], "OMAP3 ISP CCDC":1->"OMAP3 ISP CCDC output":0[1]'
	media-ctl -v --set-format '"tvp5150 3-005d":0 [UYVY 720x576]'
	media-ctl -v --set-format '"OMAP3 ISP CCDC":0 [UYVY 720x576]'
	media-ctl -v --set-format '"OMAP3 ISP CCDC":1 [UYVY 720x576]'

	if [ -f /nesis/kmodules/easycap.ko ]; then
		modprobe videodev
		insmod /nesis/kmodules/easycap.ko
	fi
}

APP_EXIT_CODE=1
LOGFILE=/tmp/log.txt

export APP_RESTART=0

if [[ -f /nesis/nesis.bin || -f /nesis/nesis ]]; then
	APP=nesis
	SPLASH=Splash.ppm
else
	APP=zeus
	if [ $(cat /sys/class/graphics/fb0/rotate) == 1 ]; then
		SPLASH=ZeusSplashV.ppm
	else
		SPLASH=ZeusSplashH.ppm
	fi
fi

# APP_PIDS=$(pgrep "${APP}.bin")

# load gumu driver
gumu_maj=`grep "SpiCan$" /proc/devices | cut -b1,2,3`
rm -f /dev/gumu
mknod /dev/gumu c $gumu_maj 0
chmod 666 /dev/gumu

alsactl restore

# load usb storage device
sleep 6 && deferedinit &

# for proc in $APP_PIDS; do
# 	echo -n "Process = $proc"
# 	if [ $proc != $$ ]; then
# 		kill -TERM $proc
# 		echo " kill"
# 	else
# 		echo " our pid"
# 	fi
# done

if [ -e $LOGFILE ]; then
	LSIZE=$(stat -c "%s" ${LOGFILE})
	if [ $(($LSIZE > 512000)) == 1 ]; then
		echo "Size of ${LOGFILE} is $(stat -c "%s" ${LOGFILE}); rotating."
		rm -f ${LOGFILE}.bz2
		bzip2 ${LOGFILE}
	fi
fi

# try to mount mmc card with maps
if ! [ -d /media/mmc ]; then
	mkdir -p /media/mmc
fi

if ! mountpoint -q /media/mmc; then
	mount -o ro /dev/mmcblk0p2 /media/mmc
else
	echo "MMC already mounted?!"
fi

while [ $APP_EXIT_CODE != 0 ]; do
	let APP_RESTART++
	# check for upgraded nesis - old nesis should go to nesis.old
#	if [ -f /nesis/${APP} ]; then
#		echo "New ${APP} was installed!" | tee -a ${LOGFILE}
#		if [ -f /nesis/${APP}.bin ]; then
#			mv /nesis/${APP}.bin /nesis/${APP}.old
#		fi

	echo "Starting ${APP} on" `date` | tee -a ${LOGFILE}
	# only lunch with -display powervr if ready
	export TSLIB_TSDEVICE=/dev/input/event1
	export QT_QPA_EVDEV_TOUCHSCREEN_PARAMETERS="rotate=180" 
	/nesis/${APP} -plugin tslib -plugin evdevkeyboard:/dev/input/event2 -style fusion 1>> ${LOGFILE} 2>&1
	APP_EXIT_CODE=$?
	echo "${APP} has exited with return code: $APP_EXIT_CODE on" `date` | tee -a ${LOGFILE}

	# show bootsplash
# 	fbsplash -s /nesis/$SPLASH 
	# write hardware clock
	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 3
	fi
done

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

sleep 0.8
echo poweroff > /proc/gumu

