#!/bin/sh

EXE=guiderII-arm
UNVS=universal-arm
PID=00E4

udhcpc -i eth0 &

rm -rf /opt/backup

sleep 2
for i in 1 2 3 4 5;
do
  if [ $i == 5 ]; then
	mount -t vfat -o,codepage=936,iocharset=utf8 /dev/sda /mnt
	if [ $? -ne 0 ]; then
		echo "mount /dev/sda to /mnt failed"
		continue
	else
	if [ -f /mnt/$PID ] || [ -f /mnt/$UNVS ]; then
		if [ -f /mnt/flashforge_init.sh ]; then
			 echo "found /mnt/flashforge_init.sh"
			 chmod a+x /mnt/flashforge_init.sh
			 /mnt/flashforge_init.sh
			 umount /mnt
			 break
		fi
		umount /mnt
	fi
	umount /mnt
	fi
  else
	if [ ! -e /dev/sda$i ]; then
	 echo "sda$i not exist"
	 continue
	fi
	mount -t vfat -o,codepage=936,iocharset=utf8 /dev/sda$i /mnt
	if [ $? -ne 0 ]; then
		echo "mount /dev/sda$i to /mnt failed"
		continue
	else
	if [ -f /mnt/$PID ] || [ -f /mnt/$UNVS ]; then
		if [ -f /mnt/flashforge_init.sh ]; then
			 echo "found /mnt/flashforge_init.sh"
			 chmod a+x /mnt/flashforge_init.sh
			 /mnt/flashforge_init.sh
			 umount /mnt
			 break
		fi
		umount /mnt
	fi
	umount /mnt
	fi
  fi	  
done

echo "Gpio WiFi Power On"
echo 195 >/sys/class/gpio/export
echo out >/sys/class/gpio/gpio195/direction
echo 0 > /sys/class/gpio/gpio195/value

echo 194 >/sys/class/gpio/export
echo out >/sys/class/gpio/gpio194/direction
echo 1 > /sys/class/gpio/gpio194/value

ifconfig wlan0 up
wpa_supplicant -d -Dwext -i wlan0 -c /etc/wpa_supplicant.conf -B
sleep 0.1

ifconfig wlan0 | grep wlan0 | grep HWaddr |tr -s ' '| cut -d ' ' -f5 > /opt/WiFiMAC
sync

killall wpa_supplicant
killall wpa_cli

Ethernet_MAC=`cat /opt/EthernetMAC | grep -E '[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}'`
echo "Ethernet_MAC="$Ethernet_MAC

if [ ! $Ethernet_MAC ]; then
	ifconfig eth0 hw ether "$Ethernet_MAC"
fi

if [ ! "`mount | grep "mmcblk0p3"`" ]; then
	echo "mmcblk0p3 not mounted and will fsck";
	fsck -y /dev/mmcblk0p3 && mount /dev/mmcblk0p3 /data;
fi

WORK_DIR=/opt

rm -rf /data/pics
mkdir /data/pics
rm -rf /data/update/*

export PATH=$WORK_DIR/bin:$PATH
export PATH=$WORK_DIR/flashforge:$PATH


if [ ! -d /data ]; then
  mkdir /data
fi

if [ ! -d /media ]; then
  mkdir /media
fi

mkdir /PROGRAM
/PROGRAM/ffstartup-arm -f /PROGRAM/ffstartup.cfg &
