#!/bin/sh

# This initial section is nothing to do with the kernel. It is a convenient place to
# do any post-upgrade cleanup.
rm -f /etc/init.d/S32tc /etc/init.d/S35vpn

nand_dev=/dev/mtdchar0
nfile=/SpliceCom/kernel/cs5100-256M.kimg
upg=n
blksz=131072

# load the modules to allow poweroff
insmod fpga
insmod gpio
insmod relay

# the following ensures the upgrade check is done only on the first reboot after a patch
[ ! -r $nfile ] && exit 0
mv ${nfile} ${nfile}.done
nfile=${nfile}.done

insmod mtdchar >/dev/null || exit 1
insmod nand_ids >/dev/null || exit 1
insmod nand_ecc >/dev/null || exit 1
insmod nand >/dev/null || exit 1
insmod pcs_nand >/dev/null || exit 1

# Setup trap to remove modules on exit
trap "rmmod pcs_nand; rmmod nand; rmmod nand_ecc; rmmod nand_ids; rmmod mtdchar" 0 

inlen=`ls -l $nfile | awk '{print $5;exit}'`
[ -z "$inlen" -o $inlen -lt 500000 ] && exit 2

# nanddump will count bad blocks as part of the length, so may
# need to specify extra length. Start with 5 extra blocks and
# increment if it's not enough.

dlen=`expr $inlen + 5 \* $blksz`

while true; do
	nanddump -f /tmp/kernel.dat -l $dlen -b -o $nand_dev 2>/dev/null || exit 3
	len2=`ls -l /tmp/kernel.dat | awk '{print $5;exit}'`
	[ $len2 -ge $inlen ] && break
	dlen=`expr $dlen + 5 \* $blksz`
	[ $dlen -gt 3000000 ] && exit 4
done

# truncate the data back to the same size as the kernel file
dd if=/tmp/kernel.dat of=/tmp/kernel.dat2 bs=$inlen count=1 2>/dev/null || exit 5

# compare the NAND data against the kernel image file
cmp -s /tmp/kernel.dat2 $nfile || upg=y

if [ $upg = "n" ]; then
	echo kernel is up to date
	exit 0
fi

echo Upgrading NAND Flash

mtdwr $nand_dev $nfile || exit $?

# Need to set the u-boot environment variable for the kernel length or
# u-boot will get a file CRC error.
envdev=/dev/flash_env_single
insmod flashenv
hexlen=`bash -c "printf %x $inlen;echo"`
echo fsz0=$hexlen > $envdev
echo fsz1=0 > $envdev
rmmod flashenv

sync
poweroff
sleep 10
