#!/bin/sh
if [ "$1" == "start" -a -f /run/setup ]; then
	umount /etc/config >/dev/null 2>&1
	umount /boot >/dev/null 2>&1
	mount /dev/mmcblk0p1 /boot
	parted -s /dev/mmcblk2 mklabel msdos
	parted -s /dev/mmcblk2 mkpart primary 1049kB 269MB
	
	mkdosfs -n EMMC /dev/mmcblk2p1
	mount /dev/mmcblk2p1 /mnt
	for f in VERSION boot.scr dtb rootfs.cpio.gz zImage; do 
		cp /boot/$f /mnt
	done
        
	mkdir -p /mnt/config
        
        if [ -f /boot/config.ini ]; then
        	mkdir -p /etc/config
                /usr/bin/uci -q -f /etc/default/keenfalcon import
                
                (
                	cd /boot
                	
                	if [ -f config.ini ]; then
		       		cat config.ini | /usr/bin/dos2unix | /lib/keenfalcon/configure
		       		zip -u /mnt/config.zip config.ini 
			fi
					       		
        	        for unit in air ground; do 
                		if [ -f ${unit}.ini ]; then
	                	        if [ -f /run/${unit} ]; then
	        	                        cat ${unit}.ini | dos2unix | /lib/keenfalcon/configure
        	        	        fi
                		        zip -u /mnt/config.zip ${unit}.ini
				fi                	       
        	        done
                )

                mv /etc/config/keenfalcon /mnt/config
        fi
	
	umount /mnt

	dd if=/dev/zero of=/dev/mmcblk2 bs=1k count=1023 seek=1 status=noxfer >/dev/null 2>&1
	dd if=/boot/u-boot-sunxi-with-spl.bin of=/dev/mmcblk2 bs=1024 seek=8 status=noxfer >/dev/null 2>&1
	umount /boot
	
	touch /run/reboot	
	echo heartbeat >'/sys/class/leds/nanopi:red:pwr/trigger'
fi
