#!/bin/sh
#
# Startup script to implement .
#
# chkconfig: 2345 60 91
# description: Updates BIOS 

. /etc/init.d/functions

E_FILE=/tmp/ethdump.$$
DEV=eth0
FLASHROM=/usr/local/sng/bin/flashrom
BIOS_TMP=/tmp/bios.$$
BIOS_CUR=/usr/local/sng/bios/BIOS.bin
PROD=sng-bios-update
rc=

logit()
{
	data="$1"
	logger "$PROD: $data"
	echo "$PROD: $data"
}


compare_bios_version()
{
	local rc

	logit "Checking bios version"
	eval "$FLASHROM -r $BIOS_TMP -p internal > /dev/null"	
	rc=$?
	if [ $rc -ne 0 ] || [ ! -e $BIOS_TMP ]; then
		logit "Error: Failed to read BIOS: rc=$rc file=$BIOS_TMP"
		return 2
	fi

	bios_tmp_ver=`strings $BIOS_TMP | grep "BIOS Date"`
	bios_cur_ver=`strings $BIOS_CUR | grep "BIOS Date"`

	rm -f $BIOS_TMP

	if [ "$bios_tmp_ver" = "$bios_cur_ver" ]; then
		logit "Already up to date: $bios_cur_ver"
		return 0
	fi

	logit "BIOS Version differ"
	logit "Orig: $bios_tmp_ver"
	logit "New : $bios_cur_ver"

	return 1	
}

update_bios()
{
	local rc

	logit "Updating BIOS"

	#Backup Etheren Mac Address
	ethtool -e $DEV | head -n 3 > $E_FILE
	val=`sed -e '1,2d' $E_FILE | cut -c 9- | tr -d "\n"`;
	echo "1000: $val" | xxd -r - $BIOS_CUR

	#Update BIOS
	eval "$FLASHROM -w $BIOS_CUR -p internal > /dev/ull"
	rc=$?

	rm -f $E_FILE
	
	return $rc 
}


start() 
{
	compare_bios_version
	rc=$?
	if [ $rc -eq 1 ]; then
		update_bios
		rc=$?
		if [ $rc -eq 0 ]; then
			compare_bios_version
			rc=$?
			if [ $rc -eq 0 ]; then
				logit "Bios Update Successfull"
				logit "Please Reboot"
			fi
		else
			logit "Error: Failed to update BIOS"
		fi
	elif [ $rc -gt 1 ]; then
		logit "Error: Failed to compare BIOS"
	fi

	return $rc
}


stop() {
	echo
}
  
if [ ! -e $FLASHROM ] || [ ! -e $BIOS_CUR ]; then
	exit 1
fi

case "$1" in
  start)
	start
	;;

  stop)
	stop
	;;

  restart)
	stop
	start
	;;
  check)
	compare_bios_version
	;;
  *)
	echo $"Usage: $0 {start|stop|restart|check}"
	exit 1
esac

exit 0

# vi: ts=4 syntax=sh
