#!/bin/sh

flash=/dev/flash0
upg=y
force=n
doenv=n

[ $# -gt 0 -a "$1" = force ] && force=y

host=`platform`
case $host in
	CS5100 | PM5315 | PM5330 | TM5230 | PCS410 )
		filen=/SpliceCom/loader/lx.ldr
		chkbut=y
		;;
	* )
		echo Unknown Host $host
		exit 1
		;;
esac

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

insmod flashenv >/dev/null 2>&1

# Setup trap to remove modules on exit
trap "rmmod flashenv >/dev/null 2>&1" 0 

if [ ! -r $filen ]; then
	echo can\'t open $filen
	exit 3
fi

echo Running upgrade for $host
echo '#####################################################################################'
echo Upgrade process will take some time, please be patient and do not power down the unit
echo '#####################################################################################'

if [ ! -w $flash ]; then
	echo can\'t open $flash
	exit 4
fi
if [ chkbut = "y" ]; then
	if [ `dd if=/dev/button bs=1 count=1 2>/dev/null` = "1" ]; then
		echo Loader upgrade aborted due to button push
		exit 5
	fi
fi

badfiletype=n

magic=`od -An      -N4 -td4 $filen`
ftype=`od -An -j4  -N4 -td4 $filen`
frevn=`od -An -j8  -N4 -td4 $filen`
fbldn=`od -An -j12 -N4 -td4 $filen`

if [ $ftype != 1414483778 ]; then
	echo file type is not a loader $ftype
	exit 6
fi

if [ $magic != 1414807885 ]; then
	echo -e bad file magic for new loader \"$magic\"
	exit 7
fi

echo file: contains loader rev $frevn build $fbldn

magic=`od -An      -N4 -td4 $flash`
prevn=`od -An -j8  -N4 -td4 $flash`
pbldn=`od -An -j12 -N4 -td4 $flash`

echo FLASH contains loader rev $prevn build $pbldn
doenv=y

if [ $frevn -lt $prevn ]; then
	echo FLASH contents are newer than file \(use force to overwrite\)
	upg=n
else
	if [ $frevn -eq $prevn ]; then
		if [ $fbldn -lt $pbldn ]; then
			echo FLASH contents are newer than file \(use force to overwrite\)
			upg=n
		else
			if [ $fbldn -eq $pbldn ]; then
				echo FLASH contents are the same as the file \(use force to overwrite\)
				upg=n
			fi
		fi
	fi
fi

if [ \( $upg = "y" \) -o \( $force = "y" \) ]; then
	echo Changing loader
	# Write 64k blocks up to the last block, then write sectors skipping
	# over the two config sectors.

	dd if=$filen of=$flash bs=64k count=7

	dd if=$filen of=$flash bs=4k count=7 \
		seek=112 skip=112 conv=notrunc

	dd if=$filen of=$flash bs=4k count=1 \
		seek=127 skip=127 conv=notrunc

	echo Done
	if [ -n "$1" -a "$1" = "start" ]; then
		sync
		poweroff
		sleep 10
	fi
fi

exit 8


