#!/bin/sh

prefix="/mnt/update_tools"
export PATH=$PATH:${prefix}

if [[ ! -d /lib ]];then
	tar xf $prefix/lib.tar -C /
fi

cd $prefix

i=0
found=0
files="u-boot.bin uImage rootfs.img qte.img"

display_bmp second.bmp

for file in $files
do 
	cnode=/dev/mtd$i
#	bnode=/dev/mtdblock$i
	
	if  [[ -f /mnt/$file ]]; then
		echo "UPDATE $file"
		display_bmp $i.bmp
		let found++
	else
		let i+=1
		continue
	fi
	
	flash_eraseall $cnode
	
	if [[ $file == u-boot.bin || $file == uImage ]]
	then 
		nandwrite -ap $cnode /mnt/$file
	else
		nandwrite -ar $cnode /mnt/$file
	fi
	let i+=1
done

cnode=/dev/$(awk '/[Ss]tart.bmp/ {print $1} ' /proc/mtd |cut -b 1-4)

for file in Start.bmp start.bmp
do
	if [[ -f /mnt/$file ]];then
		echo "UPDATE $file"
		display_bmp startbmp.bmp
		flash_eraseall $cnode
		nandwrite -ap $cnode /mnt/$file	
		let found++
		break;
	else
		echo "/mnt/$file" not exist!
	fi
done

if [[ -f /mnt/uImage.org ]];then
	echo "restore original uImage"
	flash_eraseall /dev/mtd1
	nandwrite -ap /dev/mtd1 /mnt/uImage.org
	sync && rm /mnt/uImage.org && sync && sync
fi

if [[ $found -gt 0 ]];then
	display_bmp over.bmp
	echo "UPDATE $found files"
	power_off 122
else
	echo "no file need update!"
fi
