#!/bin/sh
host=`platform`
case $host in
	PCS )
		echo No downgrade available
		exit
		;;
	VCM )
		echo No downgrade available
		exit
		;;
	PHONE )
		chgnand=n
		;;
	TRUNK )
		chgnand=n
		;;
	CALLSERVER )
		nfile=adminmod.img
		chgnand=y
		;;
	REMOTECS )
		nfile=rmtcserv.img
		chgnand=y
		;;
	* )
		echo Unknown Host $host
		exit
		;;
esac
echo Running downgrade for $host
echo '#######################################################################################'
echo Downgrade process will take some time, please be patient and do not power down the unit
echo '#######################################################################################'

filen=amboot.rom
flash=/dev/flash0
rmmod flash
lsmod | grep -q "^flash"
if [ $? -ne 0 ]; then
	insmod ./flash.ko rwe=1
	if [ $? -ne 0 ]; then
		insmod ./flash.ko
		if [ $? -ne 0 ]; then
			echo failed to load flash driver
			exit
		fi
	fi
fi
if [ ! -r $filen ]; then
	echo can\'t open $filen
	exit
fi
if [ ! -w $flash ]; then
	echo can\'t open $flash
	exit
fi
if [ `cat /dev/button` -eq 1 ]; then
    echo Loader downgrade aborted due to button push
	exit
fi

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

if [ $magic -ne 1414807885 ]; then
	echo FLASH contains old style loader
else
	echo FLASH contains loader rev $prevn build $pbldn

	if [ $chgnand = "y" ]; then
		nflash=/dev/nflash0
		blksz=16896
		rmmod nflash
		lsmod | grep -q "^nflash"
		if [ $? -ne 0 ]; then
			insmod /lib/modules/`uname -r`/nflash.ko
			if [ $? -ne 0 ]; then
				echo failed to load NAND flash driver
				exit
			fi
		fi
		if [ ! -r $nfile ]; then
			echo can\'t open $nfile
			exit
		fi
		if [ ! -w $nflash ]; then
			echo can\'t open $nflash
			exit
		fi
		len=`ls -l $nfile | cut -b33-43`
		blks=`expr $len / $blksz`

		echo Downgrading NAND Flash \($blks blocks\)
		dd if=$nfile of=$nflash bs=$blksz 2>/dev/null
	else
		echo Scheduling NAND erasure
		cmos -w 78 upgr
	fi
fi

echo Downgrading loader
# Do it in 2 bits to preserve the MAC address sector
dd if=$filen of=$flash bs=1k count=128
dd if=$filen of=$flash bs=1k count=64 \
	seek=192 skip=192 conv=notrunc
echo Done
