#!/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/mmcblk1p1 /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
       		cat /boot/config.ini | /usr/bin/dos2unix | /lib/keenfalcon/configure
                
                for unit in air ground; do 
                        if [ -f /run/${unit} -a -f /boot/${unit}.ini ]; then
                                cat /boot/${unit}.ini | dos2unix | /lib/keenfalcon/configure
                        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
