#!/bin/sh

# ----------------------------- GLOBALS ---------------------------- #

# Proc entry to read WDT status
OCT_WDT_PROC=/proc/octeon/watchdog

# Seconds between WDT checks
CYCLE_PERIOD=1

# Bonding control script
BOND_CTRL=/opt/meru/bin/bonding

# Fastpath control script
FASTPATH_CTRL=/opt/meru/bin/fastpath

# -------------------------- SANITY CHECKS ------------------------- #

#
# Check oct-ctrl script
#
OCT_CTRL=/opt/meru/bin/oct/oct-ctrl

if [ ! -f $OCT_CTRL ]; then
	echo "$OCT_CTRL must exist to use $0"; exit 1
fi

#
# Check number of Octeon cards in the system
#
NUM_OCTS=`${OCT_CTRL} count`

if [ $NUM_OCTS -eq 0 ]; then
	echo "$0 cannot run without Octeon cards present"; exit 1
fi

#
# Check that bonding is enabled (Octeon cards are reboot behind the bonding shield)
# If bonding is installed, we can assume that the bonding script is valid
#
lsmod | grep bonding 2>&1 > /dev/null || {
	echo "$0 cannot run unless bonding has been installed"
 	exit 3;
}

# --------------------------- BEGIN LOOP --------------------------- #

while [ 0 -eq 0 ]; do
	
	#Init local WDT status variable
	OCT_NEEDS_REBOOT=0

	for (( OCT = 0; OCT < NUM_OCTS; OCT++ ))
	do
		#Get indexed proc entry
		MY_OCT_WDT_PROC=${OCT_WDT_PROC}${OCT}

		#Check that it exists; if so, check the status
		if [ -f $MY_OCT_WDT_PROC ]; then
			
			#Grab status and verify that it is 0
			OCT_WDT_STATUS=`cat ${MY_OCT_WDT_PROC}`
			if [ $OCT_WDT_STATUS -ne 0 ]; then
				OCT_NEEDS_REBOOT=1
			fi

		fi
	done

	#Reboot Octeon cards if necessary
	if [ $OCT_NEEDS_REBOOT -eq 1 ]; then
		echo "Rebooting Octeon cards"
		echo [`date`] Rebooting Octeon cards ... > /opt/meru/etc/oct_watchdog_reboot	
		sync

		#detach octeon cards
		$BOND_CTRL detach
		echo [`date`] Detach Octeon cards done. >> /opt/meru/etc/oct_watchdog_reboot	
		sync

		$OCT_CTRL reload;
		echo [`date`] Reload Octeon cards done. >> /opt/meru/etc/oct_watchdog_reboot	
		sync

		#re-attach them
		$BOND_CTRL attach
		echo [`date`] Attach Octeon cards done. >> /opt/meru/etc/oct_watchdog_reboot	
		sync

		#restore fastpath state to the cards
		$FASTPATH_CTRL restore
		echo [`date`] Restore fastpath state to the Octeon cards done. >> /opt/meru/etc/oct_watchdog_reboot	
		sync
	fi

	#sleep for the cycle period
	sleep $CYCLE_PERIOD

done

