
PrefixStr="UpgradeFlash"

LogFile="/dev/tee.log"


checkversion()
{
return 0;
}

prepare()
{
echo Prepare $(date) >> $LogFile;
echo -e "$PrefixStr Status=Preparing" | tee -a $LogFile
checkversion; ret=$?;
check_hardware;

if [ $ret -ne 0 ] ; then
echo -e "$PrefixStr Status=UpgradeFinished" | tee -a $LogFile
sleep 1; exit 0;
fi
}

s_hardware="";
s_platform="armba";
s_chipf="";
check_hardware()
{
return;
}

download()
{
echo Download $(date) >> $LogFile;
cd /tmp;
while [ true ] ; do 
echo -e "$PrefixStr Status=Downloading Progress=%1" | tee -a $LogFile
echo -e "ftpget -u test -p test $serverip \"$imagefile\";" | tee -a $LogFile
ftpget -u test -p test $serverip "$imagefile";ret=$?;
if [ $ret -eq 0 ] ; then 
result=$(md5sum $imagefile | cut -d ' ' -f 1);
if [ "$result" == "$md5value" ] ; then 
echo -e "$PrefixStr Status=Downloading Progress=%100" | tee -a $LogFile
break;
else
echo -e "$PrefixStr Status=DownloadingError2" | tee -a $LogFile
fi;
else
echo -e "$PrefixStr Status=DownloadingError3" | tee -a $LogFile
fi;
done
}

upgrade()
{
echo Upgrade $(date) >> $LogFile;
echo -e "$PrefixStr Status=Upgrading Progress=%1" | tee -a $LogFile
if [ -f /app/TestUpdate ] ; then
killall TestUpdate; /app/TestUpdate "$imagefile" prog.log > /dev/null 2>>$LogFile &
else
echo -e "$PrefixStr Status=UpgradError1" | tee -a $LogFile
fi
}

before_finish()
{
rm -rf "$imagefile"; sleep 3;
dumpfile="$hwaddr-$ipaddr"
cat /dev/mtd0 > "$dumpfile"; cat /dev/mtd1 >> "$dumpfile"; cat /dev/mtd2 >> "$dumpfile"; cat /dev/mtd3 >> "$dumpfile";
echo -e "ftpput -u test -p test $serverip $dumpfile;" >> $LogFile;
md5sum "$dumpfile" >> $LogFile;

echo -e "prog.log start============" >> $LogFile;
cat prog.log >> $LogFile;
echo -e "prog.log stop============" >> $LogFile;

echo -e "dmesg start=============" >> $LogFile;
dmesg -c >> $LogFile;
echo -e "dmesg stop=============" >> $LogFile;

ftpput -u test -p test $serverip log/$dumpfile.log tee.log;

}

checkprogress()
{
echo CheckProgress $(date) >> $LogFile;
while [ ture ] ; do
sleep 4; 
str=$(ps); echo "$str" | grep -q "TestUpdate"; local ret=$?;
progress=$(cat prog.log | cut -d ' ' -f 2); 
echo -e "$PrefixStr Status=Upgrading Progress=$progress" | tee -a $LogFile
if [ "$progress" == "%100" ] ; then 
before_finish;
echo -e "$PrefixStr Status=UpgradeFinished" | tee -a $LogFile
break; 
elif [ $ret -ne 0 ] ; then
upgrade;
fi; 
done;
}

confirm()
{
result=$(cat /dev/mtd0 | md5sum); 
if [ "$result" == "" ] ; then 
echo "Partition 0 PASS" | tee -a $LogFile;
else echo "Partition 0 FAILED" | tee -a $LogFile; fi
}

finish()
{
echo Finish2 $(date) >> $LogFile;
echo -e "$PrefixStr Status=Rebooting" | tee -a $LogFile;
while [ true ] ; do sleep 10; reboot; done;
}

main()
{
#resetip;

prepare;

download;

upgrade;

checkprogress;

finish;
}

main &
