#!/bin/sh

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


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

#modprobe omaplfb
#pvrsrvctl --start --no-module

APP_EXIT_CODE=1
LOGFILE=/tmp/log.txt

export APP_RESTART=0

APP=nesis

# load gumu driver
alsactl restore

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
    # test if we have two partions
    if ! [ -e /dev/mmcblk0p4 ]; then
        
        END=$(expr $(cat /sys/block/mmcblk0/size) / 2048 - 180)
        if [ $END -gt 2000 ]; then
            echo "Resizing partitions on mmc - end $END"
            
            parted -s /dev/mmcblk0 resizepart 2 ${END}
            parted -s /dev/mmcblk0 mkpart p linux-swap $(expr $END + 2) $(expr $END + 140) 
            parted -s /dev/mmcblk0 mkpart p linux-swap $(expr $END + 142) $(expr $END + 156)
            
            sleep 4
            
            reboot
        fi
    else
        if [ -e /nesis/MasterData.dat ]; then
            echo "Moving master data."
            dd if="/nesis/MasterData.dat" of="/dev/mmcblk0p4"
            mv /nesis/MasterData.dat /nesis/MasterData.old
            sync
        fi
        
        if [ -e /nesis/MasterLogger.dat ]; then
            echo "Moving master logger."
            dd if="/nesis/MasterLogger.dat" of="/dev/mmcblk0p3"
            mv /nesis/MasterLogger.dat /nesis/MasterLogger.old
            sync
        fi
    fi
    
	mount -o ro,noatime /dev/mmcblk0p2 /media/mmc
else
	echo "MMC already mounted?!"
fi

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

	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"
	if [ $(cat /proc/bus/input/devices | grep -c eGalax) == 1 ]; then
		/nesis/${APP} -touch -plugin tslib -plugin evdevkeyboard:/dev/input/event2 -style fusion 1>> ${LOGFILE} 2>&1
	else
		/nesis/${APP} -plugin evdevkeyboard:/dev/input/event1 -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 3
	fi
done

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

sleep 0.8
echo poweroff > /proc/gumu

