#!/bin/sh
PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin

get_trigger()
{
	for t in `cat /sys/class/leds/nanopi:${1}/trigger `; do
     		case $t in
                	'['*']')
                        	echo $t | echo $t | sed -e 's/\[//' -e 's/\]//'
                                ;;
                esac
	done
}

set_trigger()
{
	echo "${2}" > /sys/class/leds/nanopi:${1}/trigger
}

case $1 in
start)
	get_trigger green:status > /run/green.led
        get_trigger red:pwr > /run/red.led
        
	if [ ! -f /run/setup ]; then
		if [ -f /run/ready ]; then
                	rm -rf /run/reboot /run/reconfigure /tmp/config
                        
			set_trigger green:status none
                        
			mount -t vfat -o rw /dev/mmcblk0p1 /mnt
                        
        		if [ -f /mnt/firmware.tar ]; then
				tar -C /boot -xf /mnt/firmware.tar
				rm -f /boot/u-boot-sunxi-with-spl.bin
				touch /run/reboot
			fi

			unit=''                        
			for u in air ground; do
        	        	if [ -f /run/${u} ]; then
                                	unit=$u
                                fi
        	        done
        	        
        	        mkdir -p /tmp/config
                        
                        (
                        	cd /mnt
				for f in *.ini; do			                               
	                        	case $f in
        	                        "config.ini"|"${unit}.ini")
						touch /run/reconfigure
                        	        	;;
					esac     
	                        	zip -u /boot/config.zip ${f}
					cp $f /tmp/config
        	                done
                        )
			
                        if [ -f /boot/config.zip ]; then
                        	cp /boot/config.zip /mnt
                        fi
                       
                        if [ -f /run/reconfigure ]; then
				uci -q -f /etc/default/keenfalcon import
                                for f in config ${unit}; do
                                	if [ -f /tmp/config/${f}.ini ]; then
						cat /tmp/config/${f}.ini | dos2unix | /lib/keenfalcon/configure
                                	fi
                                done
                                rm -f /run/reconfigure
                                rm -rf /tmp/config
				touch /run/reboot
                        fi
                        
		        umount /mnt
                        
			set_trigger red:pwr heartbeat
		else
			mount /dev/mmcblk0p1 /mnt
			touch /run/storage
			touch /run/reboot
		fi
	fi
	;;

stop)
	if [ -f /run/reboot ]; then
		set_trigger green:status none
		set_trigger red:pwr none
		reboot
	else                
		set_trigger green:status `cat /run/green.led`
		set_trigger red:pwr default-on
	fi
	;;
esac
exit 0
