#!/bin/sh

script_path=`echo $0 | awk -F '/' '{for(i=2;i<NF;i++) printf"/"$i}'`
killall wpa_supplicant
killall udhcpc
killall hostapd
killall udhcpd
echo  $script_path >> test

SD_UPGRADE_FILE=sd_upgrade_all.bin
ETH0MAC_FILE=eth0mac.cfg
isupgraded=no
ETH0MAC=`sed -n "s/ethaddr0:\(.*\).*/\1\n/p" /proc/xm/xminfo`
ETH0MAC_DEFAULT="00:00:23:34:45:66"

MCUUPGRADE=`cat function.ini | ./busybox grep "mcuUpgrade:" | ./busybox grep -v grep | sed 's/mcuUpgrade://g' | sed 's/\r//g' | sed 's/\n//g' | sed "s/$(echo -e '\015')//g"`

if [ -f $script_path/$ETH0MAC_FILE ]; then
	ETH0MAC4FILE=`cat $script_path/$ETH0MAC_FILE | ./busybox grep "eth0mac:" | ./busybox grep -v grep | sed 's/eth0mac://g' | sed 's/\r//g' | sed 's/\n//g' | sed "s/$(echo -e '\015')//g"`
	if [ "$ETH0MAC" = "$ETH0MAC_DEFAULT" -o "$ETH0MAC" = "$ETH0MAC4FILE" ];then
		isupgraded=yes
	fi
fi

echo "ETH0MAC:$ETH0MAC ETH0MAC4FILE:$ETH0MAC4FILE "
if [ ! -f $script_path/$SD_UPGRADE_FILE ]; then
	echo "cann't found upgrade file"
	./simple_adec_bind_ao -r 8000 -t g711a -i audio/upgradefile_fail.pcm
	exit -1
fi

if [ "$isupgraded" = "no" ];then
	./simple_adec_bind_ao -r 8000 -t g711a -i audio/start_upgrade.pcm
	$script_path/upgrader file $script_path/$SD_UPGRADE_FILE
	if [ $? != 0 ]; then
		./simple_adec_bind_ao -r 8000 -t g711a -i audio/upgrade_fail.pcm
	else
		echo "eth0mac:$ETH0MAC" > $script_path/$ETH0MAC_FILE
		sync
		sleep 5
		./simple_adec_bind_ao -r 8000 -t g711a -i audio/upgrade_ok.pcm
		if [ "$MCUUPGRADE" = "no" ];then
			reboot
		fi
	fi
fi
