#!/bin/sh

fl()
{
  res=$1
  shift
  echo $@
  exit $res
}

wifi_stop()
{
	echo "Stopping wscd..."
	route delete 239.255.255.250
	killall wscd
	sleep 1
	killall -9 wscd
	iwpriv ra0 set WscConfMode=0
	led wps off
	echo "done."

	killall rt2860apd
	sleep 1
	brctl delif br0 ra0
	brctl delif br0 ra1
	brctl delif br0 ra2
	brctl delif br0 ra3
	brctl delif br0 wds0
	brctl delif br0 wds1
	brctl delif br0 wds2
	brctl delif br0 wds0
	ifconfig ra0 down
	ifconfig ra1 down
	ifconfig ra2 down
	ifconfig ra3 down
	iwpriv apcli0 set ApCliEnable=0
	ifconfig apcli0 down
	ifconfig wds0 down
	ifconfig wds1 down
	ifconfig wds2 down
	ifconfig wds3 down
	rmmod rt2860v2_ap
}

VERSION=`grep ^VERSION /VERSION | ( read a b; echo $b )`
if [ "$VERSION" = "1.2.1" ]; then
    echo "This firmware update was not created for v${VERSION}"
    sleep 2
    reboot
fi

for i in igmpproxy xl2tpd pppd udhcpc dnsmasq telnetd httpd miniupnpd klogd syslogd; do
  echo -n "stopping $i ..."
  killall -9 $i >/dev/null 2>&1
  [ $? -eq 0 ] && echo OK || echo failed
done
killall -9 crond >/dev/null 2>&1
sleep 1
killall resident
sleep 1

wifi_stop

UPD=$1
LOCALDIR=`pwd`
cd $LOCALDIR
UPD=`basename $UPD`
tar -x ./img/list -f $UPD || fl 3 "cannot get list of images"

for i in `cat ./img/list`; do
  echo "process $i..."
  tar -x ./img/${i} -f $UPD || fl 4 "extracting $i"
#  mtd_write erase $i 
  mtd_write write ./img/${i} $i && echo OK || fl 5 FAILED
#  rm -f ./img/${i}
done
#rm -rf $UPD ./img ./runme

tar -x ./moduconfig -f $UPD
dd if=/dev/mtdblock2 of=/tmp/mtd2
./moduconfig /tmp/mtd2
mtd_write write /tmp/mtd2 Config

reboot
exit 0
