#! /bin/sh
#
# update-flash.sh

download()
{
while [ ! -e $1 ];do
	echo ""
	echo "*" downloading $1 ...
	# ftpget $tftpsvr $1 $1
	tftp -g $tftpsvr -r $1
	sleep 1
done
}

### main

if [ -z $tftpsvr ];then
{
	tftpsvr=192.168.0.23
}
fi
######################################################
# main
echo "## backup old files "
mkdir -p /mtd8 /mtd6
mount /dev/mtdblock8 /mtd8
mount /dev/mtdblock6 /mtd6

cp -fr /mtd8/yealink/config /tmp
cp -fr /mtd8/yealink/data /tmp
cp -fr /mtd8/yealink/www/.htpasswd /tmp/data/htpasswd
cp -fr /mtd8/firmware /tmp/

cp -fr /mtd6/config /tmp
cp -fr /mtd6/data /tmp

umount /mtd6
umount /mtd8

echo "## reset mtd8 and mtd6 "
flash_eraseall -q /dev/mtd8
flash_eraseall -q /dev/mtd6

echo "## setup upgrade folder "
mkdir -p /rundata
mount /dev/mtdblock8 /mtd8
mount /dev/mtdblock6 /rundata

mkdir -p /mtd8/rundata
mkdir -p /mini-boot /phone /firmware /upgrade.finish /mtd8/mini-boot /mtd8/phone /mtd8/firmware /mtd8/upgrade.finish
mount /mtd8/mini-boot /mini-boot
mount /mtd8/phone /phone
mount /mtd8/firmware /firmware
mount /mtd8/upgrade.finish /upgrade.finish

echo "## recover old files "
cp -fr /tmp/firmware /
cp -fr /tmp/config /rundata/
cp -fr /tmp/data /rundata/

cd /tmp/
download mini-boot.tgz
tar -zxf mini-boot.tgz -C /tmp/
chmod +x /tmp/* -R

cp -fr /tmp/mini-boot /
cp -fr /tmp/rundata /
cp -fr /tmp/sbin /
ln -sf /tmp/lib/libm.so.6 /lib/libm.so.6
ln -sf /tmp/lib/libpthread.so.0 /lib/libpthread.so.0
ln -sf /tmp/lib/librt.so.1 /lib/librt.so.1
ln -sf /tmp/lib/libssl.so.0.9.7 /lib/libssl.so.0.9.7
ln -sf /tmp/lib/libcrypto.so.0.9.7 /lib/libcrypto.so.0.9.7


export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/mini-boot/lib:/tmp/lib

/tmp/drivers/loadmodules.sh
while [ ! -e /dev/fb/0 ]; do
	echo "wating /dev/fb/0"
	sleep 1
done

. /mini-boot/scripts/get-device-name.sh

case $deviceName in  
	VP2008T | VP2008TV30 )
	packetNameFile="VP2008.packetname"
	;;  
	VP2009T | VP2009V12 )
	packetNameFile="VP2009.packetname"
	;;
	VP2009D | VP2009DT )
	packetNameFile="VP2009D.packetname"
	;;  
	*)  
	echo undefined device name $deviceName  
	packetNameFile=""
	;;  
esac  
echo packet file = $packetNameFile

if [ "$packetNameFile" != "" ];then
{
	download $packetNameFile
	romFileName=`cat $packetNameFile`
	echo romFileName = $romFileName	
	
	/mini-boot/scripts/show-upgrade.sh &
	# /mini-boot/bin/idleBox.exx "installROMFile(ftp://anonymous:123456@$tftpsvr/$romFileName, 1)" &
        /mini-boot/bin/idleBox.exx "installROMFile(tftp://$tftpsvr/$romFileName, 1)" &
}
else
{
	echo can not find rom file for $deviceName : `/mini-boot/bin/idleBox.exx "devGetDeviceVersion()"`
	/mini-boot/bin/idleBox.exx "drawPixelFile(/mini-boot/resource/failed.fb0,0,0)"
}
fi
