#!/bin/sh

#
# known blade IDs:
# Name      ID    SWBD   SYS               LLI          QCN
# --------------------------------------------------------------------
# MM        112   1000   mm_fpga.Primary   N/A          N/A
# SFM       113   N/A    sfm_fpga.Primary  N/A          N/A
#
# LC48X10G  114   1004   lc_fpga.Primary   N/A        qcn.image
# LC18X10G  115     
# LC12X40G  127   1005   lc_fpga.Primary   lli.image  qcn.image
# LC72X1G   128   1006   lc_fpga.Primary   lli.?      qcn.image
# LC48X1G   131   1007   lc_fpga.Primary   ?          qcn.image
#
# LC6X100g  149   1009   lc_fpga.1009      lli.1009   qcn.1009
# LC27x40g  150   1010   lc_fpga.1009      lli.1010   qcn.1009
# LC48x10T  151   1011   lc_fpga.1009      N/A        qcn.1009
#---------------------------------------------

#
#	Mercury-2 FPGA Matrix
#---------------------------------------------------
# FPGA            6x100      27x40       48x10T
#---------------------------------------------------
# SYS FPGA        sys.1009   sys.1009    sys.1009
# QCN FPGA        qcn.1009   qcn.1009    qcn.1009
# LLI FPGA        lli.1009   lli.1010    N/A
#

# for simulation only, don't change!
SIM=0
SIM_BLADE=
SIM_SWBD=

#
module=
slot=-1
file=
NULL='/dev/null'

if [ $SIM = 1 ] ; then
	CMD='echo Upgrade FPGA with parameters : '
else
	CMD='/sbin/fpgaupgrade.hydra'
fi

COUNT=1
ID=0
lcslotno=0
lcslotip=""
bladeid=0
mmslotno=0
mmslotip=""
PATH=$PATH:"/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/factory:/fabos/xtool"
export PATH
status_active="Active, Cold Recovered"
LogFile="/var/log/fpgaUpgrade.current"
LastLogFile="/var/log/fpgaUpgrade.last"
returncode="/tmp/fpgaUpgrade.rc"
SysLogFile="/tmp/messages"
bstatus="ENABLED"
partition=
blade_total=0
blade_failed=0

ERR_PERM=1

#
# log_echo
#
# prints all the logs to console and append to the $LogFile
#

log_echo(){
	echo $* 
	echo $* >> $LogFile
}

if [[ -e $LogFile ]] ; then
	cp $LogFile $LastLogFile
	echo "" > $LogFile
fi

hsl_poll_disable()
{
	hsl ifm optic poll disable
}

hsl_poll_enable()
{
	hsl ifm optic poll enable
}

Print_help()
{
	log_echo "Usage:"
	log_echo $0" -m MM|SFM|LC|QCN|LLI [-s slot] -f filename"
	log_echo $0" -m ALL --- upgrade all SFM/LC/MM from RPM"
	exit $ERR_PERM
}

# swbd
#
# Retrieve the current system platform name, of the form "SWBDn", where n
# is cardinal number, assuming a sin/hinv input stream.
#
swbd() {
	/bin/sed -n -e 's/^.\+\(SWBD[[:digit:]]\{1,\}\).\+$/\1/gp'      
}

# bladeid
#
# Retrieve the current system blade fruid, 
#
getbladeid() {
	boardtype=$1
	boardslot=$2

	if [ $SIM = 1 ]; then
	bladeid=$SIM_BLADE
	else
	bladeid=`slotshow|grep $boardtype|awk '{print "slot"$1 " " $3}'|grep "slot"$boardslot|awk '{print $2}'`
	fi
#	echo "Board Typd:["$boardtype"], slot :["$boardslot"] FRU_id:"$bladeid
}

# bladeid
#
# Retrieve the current system blade fruid, 
#
getLCbladeid() {
	if [ $SIM = 1 ]; then
	bladeid=$SIM_BLADE
	else
	bladeid=`cat /proc/fabos/blade/*/info |grep bladeId|awk '{print $2}'`
	fi
}

# mm slot no
#
# Retrieve the current MM slot no 
#
getMMslotno() {
	mmslotno=`sin|grep "Slot No"|awk '{print $3}'`
}

function progress(){
while true
do
     echo -n "."
     sleep 3
done
}

function proc_start(){
        progress &
        back_prc=$!
}

function proc_end(){
        kill $back_prc &>/dev/null 2>&1
}


initialization() {

	if  [[ $SWBD = "SWBD1002" ]];then
		MMPOS=( 15 16)
		LCPOS=( 1 2 3 4 11 12 13 14 )
	elif [[ $SWBD = "SWBD1001" ]] ;then
		MMPOS=( 15 16)
		LCPOS=( 1 2 3 4 11 12 13 14 )
	else
		MMPOS=( 1 2)
		LCPOS=( 7 8 9 10 )
	fi
}


#
# findoutLCip
#
# Finds out and return the ip address of the intended LC 
#
#

findoutLCip() {

	if [ $SWBD = "SWBD1002" ] || [ $SWBD = "SWBD1001" ] || [ $SWBD = "SWBD1000" ] ; then

		eth2=`ifconfig eth2| grep inet | cut -f2 -d ":" | cut -d " " -f-1 |  cut -d "." -f-3`
		
		
		for f in `slotshow | grep LC |awk {'print $1'}`
		do
	                
			if [ $f == $lcslotno ];then
				let ID=LCPOS[COUNT-1]
				lcslotip=$eth2.$ID
			fi
				    
			let  COUNT=COUNT+1
		done
		let COUNT=1
	fi

}


#
# findLocalFileName
#
# Find out LC local Image file name
#
#
findLocalFileName() {

	family=$partition

	case $bladeid in
	'149' | '150' | '151')
		family="1009"
	;;
	'114' | '127' | '128' | '131')
		family="image"
	;;
	esac

	if [[ $module == "LLI" && $bladeid == '150' ]] ; then
		family="1010"
	fi

	if [[ $module == "QCN" ]] ; then
		tfile="/boot/qcn_fpga."$family".bit"
	elif [[ $module == "LLI" ]] ; then
		tfile="/boot/lli_fpga."$family".bit"
	elif [[ $module == "LC" ]] ; then
		tfile="/boot/lc_fpga."$family".bit"
	elif [[ $module == "MM" ]] ; then
		tfile="/boot/mm_fpga."$family".bit"
	else
		log_echo "Error: Unknow module:"$module
		exit $ERR_PERM
	fi
}

Process_args()
{
    if [ $1 == "-m" ] ; then
	module=$2
    fi

    if [[ $# == 6 && $3 == "-s" ]] ; then
	slot=$4
    fi

    if [[ $# == 4 && $3 == "-f" ]] ; then
	file=$4
    fi

    if [[ $# == 6 && $5 == "-f" ]] ; then
	file=$6
    fi

    if [[ $module != "MM" && $module != "LC" && $module != "SFM" && $module != "QCN" && $module != "LLI" && $module != "ALL" ]] ; then
	log_echo "Error: Wrong module "$module
	exit $ERR_PERM
    fi

    if [[ $module == "" ]] ; then
        log_echo "Must specify module with -m"
        Print_help
    fi

    if [[ $file == "" && $module != "ALL" ]] ; then
        log_echo "Module:["$module"] file:["$file"]"
        log_echo "Must specify file name with -f"
    	Print_help
    fi

    if [[ $module == "ALL" && $file != "" ]] ; then
        log_echo "Upgrade ALL Modules do not need specify image file. File ignored."
    fi

    if [[ $# != 4 && $# != 6 && $# != 2 ]] ; then
        log_echo "Wrong parameter number."
        Print_help
    fi

    log_echo "Platform:["$SWBD"] Module:["$module"]" " Slot:["$slot"]" "file:["$file"]"
}


#
# Create node for each device driver.
# mk_device <module name> {<device name> <minor-dev-num>}
#
mk_device()
{
	set $@
	node=$1
	shift 1
	major=`grep $node\$ /proc/devices | cut -d ' ' -f 1`
	if [ ! $major ]; then
		$ECHO "Error: No major device for node [$node]. Exiting"
		exit $ERR_PERM;
	fi
	while [ $# -gt 0 ]; do
		rm -f /dev/$1
		mknod --mode=666 /dev/$1 c $major $2
		shift 2
	done
	return 0
}

load_module() {
	case ${SWBD##SWBD} in
	'1000' | '1001' | '1002' | '1003')
		/sbin/insmod /fabos/modules/mm_spi-module.ko

		mm_rev=`cat /proc/fpga_spi |grep "HW revision"| awk {'print $3'}`
		;;
	'1004' | '1005' | '1006' | '1007' | '1008' | '1009' | '1010' | '1011')
		/sbin/insmod /fabos/modules/lc_spi-module.ko
		;;
	esac
}

unload_module() {
	case ${SWBD##SWBD} in
	'1000' | '1001' | '1002' | '1003')

		# Keep spi driver loaded for P2B boards
		if [[ $mm_rev != "P2B" ]] ; then
			/sbin/rmmod mm_spi-module.ko
		fi
		;;
	'1004' | '1005' | '1006' | '1007' | '1008' | '1009' | '1010' | '1011')
		/sbin/rmmod lc_spi-module.ko
		;;
	esac
}

Sanity_check()
{
	case ${SWBD##SWBD} in

	'1000' | '1001' | '1002' | '1003')
	if [[ $module != "MM" && $module != "SFM" && $module != "LC" && $module != "QCN" && $module != "LLI" && $module != "ALL" ]] ; then
		log_echo "Error: Upgrade MM/SFM must be running on MM."
		exit $ERR_PERM
	fi
	;;

	'1004' | '1006' | '1007' | '1008' | '1011')
	if [[ $module != "LC" && $module != "QCN" ]] ; then
		log_echo "Error: LC $SWBD can only upgrade LC/QCN. Not [$module]"
		exit $ERR_PERM
	fi
	;;
	'1005' | '1009' | '1010')
		if [[ $module != "LC" && $module != "QCN" && $module != "LLI" ]] ; then
			log_echo "Error: LC $SWBD can only upgrade LC/QCN/LLI. Not [$module]"
			exit $ERR_PERM
		fi
	;;
    esac

	if [[ $module == "SFM" && $slot == "-1" ]] ; then
		log_echo "Error: Upgrade SFM must specify slot number."
		exit $ERR_PERM
	fi

	if [[ $module == "SFM" && $slot == "all" ]] ; then
		if [[ `slotshow | grep SFM | grep $bstatus | awk '{print $2}' | tail -n1` != "SFM" ]];then
			log_echo "Error: No SFM is $bstatus."
			exit $ERR_PERM
		fi
    
	elif [[ $module == "SFM" && $slot != "all" ]] ; then
		if [[ `slotshow | grep $module | grep $bstatus | awk '{print $1}' | grep $slot` != $slot ]] ; then
			log_echo "Error: SFM on slot "$slot" is not $bstatus."
			exit $ERR_PERM
		fi	
	fi

	if [[ $module == "LC" || $module == "MM" ]] ; then
		if [[ $slot == "all" ]] ; then
			if [[ `slotshow | grep $module | grep $bstatus | awk '{print $2}' | tail -n1` != $module ]] ; then 
				log_echo "Error: No $module is $bstatus."
				exit $ERR_PERM
			fi
		elif [[ $slot != "-1" && $slot != "REMOTE" ]] ; then
			if [[ `slotshow | grep $module | grep $bstatus | awk '{print $1}' | grep $slot` != $slot ]] ; then
				log_echo "Error: $module on slot "$slot" is not $bstatus."
				exit $ERR_PERM
			fi	
	    fi
    fi

}


check_fabos()
{
	if [[ $module != "MM" ]] ; then
		return 0
	fi

	#
	# Upgrade P2B MM can not thru active MM
	# Must check FABOS off and running localy
	#
	if [[ $mm_rev == "P2B" && $slot != "-1" ]] ; then
		log_echo "Error: The MM board is $mm_rev. Only P2C and newer can upgrade with option [$slot]."
		log_echo "To upgrade $mm_rev MMs, FABOS must be checked off and upgrade MMs individually."
		exit 1
	fi


	if [[ $mm_rev == "P2B" ]] ; then
		/sbin/chkconfig fabos
		if [[ $? != 1 ]] ; then
			log_echo "---------------------------------------------------------"
			log_echo "Error: Some old MM boards(P2A, P2B) have to have FOS checked off"
			log_echo "for MM FPGA upgrade."
			log_echo "You need run command:"
			log_echo "/sbin/chkconfig fabos off"
			log_echo "and reboot, then run this command."
			log_echo "---------------------------------------------------------"
			log_echo "Quit upgrade."
			unload_module
			exit 1
		fi
		if [[ -e /proc/fabos ]] ; then
			log_echo "----------------------------------------------------------"
			log_echo "Error: FABOS is still running. Need check FABOS off for P2B boards"
			log_echo "Please reboot the system and then run this command."
			log_echo "----------------------------------------------------------"
			log_echo "Quit upgrade."
			unload_module
			exit 1
		fi

		log_echo "Pass FABOS checking. Programming for $mm_rev"
		return 0
	fi

	mm_status=`hashow|grep Local`
	if [[ $slot != "REMOTE" && $mm_status != *$status_active ]] ; then
		log_echo "Error: Upgrade $module must be runing on Active MM."
		unload_module
		exit $ERR_PERM
	fi
	log_echo "Pass FABOS checking. Programming for $mm_rev"
}


cmd_run(){
	let blade_total=blade_total+1
	$CMD $*;RET_VAL=$?;echo "Return Code:"$RET_VAL|tee -a $LogFile
	if [[ "$RET_VAL" -ne "0" ]] ; then
		log_echo "Upgrade FAILED code:[$RET_VAL] !"
		let blade_failed=blade_failed+1
	fi
}

execute_cmd_MM(){
	bladeid=112

	getMMslotno

	eth2=`ifconfig eth2| grep inet | cut -f2 -d ":" | cut -d " " -f-1 |  cut -d "." -f-3`

	#
	# upgrade all MMs
	#
	if [[ $slot == "all" ]] ; then
		for f in `slotshow | grep MM | grep "ENABLED" | awk {'print $1'}`
		do
			let mm_slot=MMPOS[$f-1]

			if [ $mm_slot == $mmslotno ];then

				if [[ $file == "LOCAL" ]] ; then
					findLocalFileName
				else
					tfile=$file
				fi
				log_echo "Upgrading Active $module bladeid $bladeid file:$tfile..."
				check_fabos
				cmd_run -m $module -b $bladeid -f $tfile
			else
				mmslotip=$eth2.$mm_slot

				if [[ $file == "LOCAL" ]] ; then
					findLocalFileName
				else
					rcp $file root@$mmslotip:~
					tfile=$file
				fi
				log_echo "Upgrading Standby $module bladeid $bladeid on slot $f/$mm_slot IP:[$mmslotip] file:$tfile..."

				proc_start
				rsh $mmslotip "tail -n0 -f $SysLogFile &/sbin/fpgaupgrade -m $module -s REMOTE -f $tfile;echo $?;killall tail" | tee -a $LogFile
				proc_end

				if [[ $file != "LOCAL" ]] ; then
 					rsh  $mmslotip "rm ~/$tfile"
				fi
			fi
		done
	#
	# upgrade MM, or calling from peer MM
	#
	elif [[ $slot == "-1" || $slot == "REMOTE" ]] ; then
		log_echo "Upgrading $module bladeid $bladeid file:$file..."
		check_fabos
		cmd_run -m $module -b $bladeid -f $file

	#
	# slot # is given
	#
	else
		let mm_slot=MMPOS[$slot-1]
		
		#
		# local MM
		#
		if [[ $mm_slot == $mmslotno ]] ; then
			if [[ $file == "LOCAL" ]] ; then
				findLocalFileName
			else
				tfile=$file
			fi
			log_echo "Upgrading $module bladeid $bladeid on slot $slot file:$tfile..."
			check_fabos
			cmd_run -m $module -b $bladeid -f $tfile
		#
		# peer MM
		#
		else
			mmslotip=$eth2.$mm_slot
			rcp  $file root@$mmslotip:~
			log_echo "Upgrading Standy $module on slot $slot bladeid $bladeid IP [$mmslotip] ..."

			proc_start
			rsh $mmslotip "tail -n0 -f $SysLogFile &/sbin/fpgaupgrade -m $module -s REMOTE -f $file;echo $?;killall tail" | tee -a $LogFile
			proc_end

			if [[ $file != "LOCAL" ]] ; then
			    rsh  $mmslotip "rm ~/$file"
			fi
		fi
	fi
}

execute_cmd_LC(){
    case ${SWBD##SWBD} in
    '1000' | '1001' | '1002' | '1003')
	log_echo "--------------------------------------------------------------"
	log_echo "  Upgrade [$module] FPGA for slot [$slot] process started."
	log_echo "  Image file : $file"
	log_echo "--------------------------------------------------------------"
	;;
	esac

	case ${SWBD##SWBD} in 
		'1000' | '1001' | '1002' | '1003')
		if [[ $slot == "all" ]] ; then
			
			for eachLC in `slotshow | grep LC | grep $bstatus |awk {'print $1'}` ; do
				lcslotno=$eachLC
				getbladeid "LC" $lcslotno
				findoutLCip

				if [[ $module == "LLI" && $bladeid != "127" ]] ; then
					log_echo "Blade $bladeid at slot $lcslotno does NOT support $module, skipped."
					continue
				fi

				if [[ $file == "LOCAL" ]] ; then
					findLocalFileName
				else
					rcp  $file root@$lcslotip:~
					tfile=$file
				fi
				log_echo "Upgrading $module/$bladeid/$lcslotno/$lcslotip [$tfile]"

				proc_start
				rsh $lcslotip "tail -n0 -f $SysLogFile &/sbin/fpgaupgrade -m $module -f $tfile;echo $?;killall tail" | tee -a $LogFile
				proc_end

				if [[ $file != "LOCAL" ]] ; then
 					rsh  $lcslotip "rm ~/$tfile"
				fi
			done

		else
			lcslotno=$slot
			getbladeid "LC" $slot
			findoutLCip
			log_echo "Upgrading $module/$bladeid/$lcslotno/$lcslotip [$file]"

			if [[ $file == "LOCAL" ]] ; then
				findLocalFileName
			else
				rcp  $file root@$lcslotip:~
				tfile=$file
			fi
			proc_start
			rsh  $lcslotip "/sbin/fpgaupgrade -m $module -f $tfile;echo $?" | tee -a $LogFile
			proc_end

			echo "Reture Code:"$RET_VAL
			if [[ $file != "LOCAL" ]] ; then
			    rsh  $lcslotip "rm ~/$file"
			fi
		fi
		;;

		'1004' | '1006' | '1007' | '1008' | '1011')
		    getLCbladeid
		    if [[ $file == "LOCAL" ]] ; then
			    findLocalFileName
		    else
			    tfile=$file
		    fi

		    if [[ $module == "LC" || $module == "QCN" ]] ; then
				log_echo "Start upgrading $module bladeid $bladeid file $tfile..."
				hsl_poll_disable
				cmd_run -m $module -b $bladeid -f $tfile
				hsl_poll_enable
		    else
				log_echo "Upgrading $module on $SWBD not allowed."
				RET_VAL=1
		    fi
		;;
		'1005' | '1009' | '1010')
		    getLCbladeid
		    if [[ $file == "LOCAL" ]] ; then
			    findLocalFileName
		    else
			    tfile=$file
		    fi
		    if [[ $module == "LC" || $module == "QCN" || $module == "LLI" ]] ; then
				log_echo "Start Upgrading $module bladeid $bladeid file $tfile..."
				hsl_poll_disable
				cmd_run -m $module -b $bladeid -f $tfile
				hsl_poll_enable
		    else
				log_echo "Upgrading $module on $SWBD not allowed."
				RET_VAL=1
		    fi
		;;
		esac
}


execute_cmd_SFM(){

	log_echo "--------------------------------------------------------------"
	log_echo "  Upgrade [$module] FPGA on slot [$slot] process started."
	log_echo " Image file $file"	
	log_echo "--------------------------------------------------------------"

	if [[ $slot == "all" ]] ; then
		for sfm_slot in ` slotshow | grep SFM | grep $bstatus | awk '{print $1}'`
		do
			getbladeid "SFM" $sfm_slot
			log_echo "Upgrading [SFM] bladeid "$bladeid" on slot ["$sfm_slot"] File:["$file"]"

			let slot=sfm_slot-1

			cmd_run -m $module -s $slot -b $bladeid -f $file
		done

	elif [[ $slot != "-1" ]] ; then
		getbladeid "SFM" $slot
		log_echo "Upgrading [SFM] bladeid "$bladeid" on slot ["$slot"] File:["$file"]"	

		let slot=slot-1

		cmd_run -m $module -s $slot -b $bladeid -f $file
	fi

}

execute_cmd()
{
	original_logs=`cat /proc/sys/kernel/printk | awk '{print $1}'`
	#Setting log level to enable debug logs
	dmesg -n 7

	#
	# Only Diaply banner on MMs
	#
    case ${SWBD##SWBD} in
    '1000' | '1001' | '1002' | '1003')
	log_echo "##########################################################################"
	log_echo "# Upgrade $module FPGA process started. This will take a few minutes.    #"
	log_echo "# Please do not switch off/cycle the switch while the process continues. #"	
	log_echo "##########################################################################"
	;;
    esac


	if [[ $module == "ALL" ]] ; then

		#######################################
		# Upgrade SFM Primary partition
		#######################################
		module="SFM"
		slot="all"
		file="/boot/sfm_fpga.Primary.bit"
		execute_cmd_SFM

		#######################################
		# Upgrade LC Primary partition
		#######################################
		module="LC"
		slot="all"
		file="LOCAL"
		partition="Primary"
		execute_cmd_LC

		#######################################
		# Upgrade LLI
		#######################################
		module="LLI"
		slot="all"
		file="LOCAL"
		execute_cmd_LC

		#######################################
		# Upgrade MM
		#######################################
		module="MM"
		slot="all"
		file="LOCAL"
		partition="Primary"
		execute_cmd_MM

#		module="QCN"
#		slot="all"
#		file="LOCAL"
#		execute_cmd_LC
#


	elif [[ $module == "SFM" && $slot != "" ]] ; then
		execute_cmd_SFM
	
	elif [[ $module == "LC" || $module == "QCN" || $module == "LLI" ]] ; then
		execute_cmd_LC
	
	elif [[ $module == "MM" ]] ; then
		execute_cmd_MM
	else
		
		$CMD -m $module -f $file
	
	fi

	#Setting log level back to original
	dmesg -n $original_logs
}

SWBD=`/sbin/sin | swbd 2> ${NULL}`

if [ $SIM = 1 ]; then
    case ${SWBD##SWBD} in
    '1004' | '1005' | '1006' | '1007' | '1008' | '1009' | '1010' | '1011')
	echo "Platform [$SWBD] but Simulate Platform :[$SIM_SWBD]"
	SWBD=$SIM_SWBD
	;;
    esac
fi

#
# process argumwnts
#

Process_args $@

#
# initialization part
#

initialization

#
# Sanity checking
#

Sanity_check

#
# load driver module
#

load_module
mk_device fpga_spi fpga_spi 0


# Run command there
execute_cmd

#
# unload driver module
#
unload_module

#
# Only Diaply banner on MMs
#
case ${SWBD##SWBD} in
'1000' | '1001' | '1002' | '1003')
log_echo "##########################################################################"
log_echo "# Upgrade FPGA process ended                                             #"
#log_echo "# Total $blade_total upgraded.   #"
#if [[ "$blade_failed" -ne "0" ]] ; then
#  log_echo "# Failed $blade_total ! Please check log and retry.   #"
#fi
log_echo "##########################################################################"
;;
esac

#echo "RETURN:"$RET_VAL

exit $RET_VAL

