#!/bin/sh
PATH=$PATH:/usr/local/bin
. sig_catcher

# Sel logging variables, please refer netapp/include/sel.h for more info
# values under sel_component_t & sel_sev_t
SEL_PARAM="SP.notice"
SEL_LOGGER="sel_logger"
IPMI_SENSOR_TASK_UP="/tmp/sensorMonitorTaskUp"
loop_continue=1
count=0

usage()
{
cat << USAGE_HERE
Usage:
	run_cmd_when_ipmi_ready.sh <command> <timeout>

	<command>:
	  The command that will run after IPMI stack is ready.
	<timeout>
	  After timeout, if IPMI stack is not ready, run the <command>.

USAGE_HERE
   exit 0
}


# the first argument is command
cmd=${1}

# the second argument is timeout
timeout=${2}

if [ -z "$cmd" -o -z "timeout" ];then
	usage
fi

while [ \( $count -lt $timeout \) -a \( "$loop_continue" -gt 0 \) ]
do
	count=$((count+1))
	lan_msghndlr_no=$(lsof -nl | grep -c "MsgHndlr.*socket")
	if [ \( "$lan_msghndlr_no" -gt 0 \) -a \( -e "$IPMI_SENSOR_TASK_UP" \) ];then
		#IPMI sensor scan task and Msghndlr is up now.
		#Use ipmitool to check if "Get device ID command" is working.
		#If "Get device ID command" is not working, ipmitool shows some error messages.
		get_device_id=$(/usr/local/bin/ipmitool -A NONE -H 127.0.0.1 raw 6 1 2>/dev/null | cut -d ' ' -f 2)
		if [ "$get_device_id" = "02" ];then
			#IPMI Get device ID command is working
			loop_continue=0
		fi
	fi
	sleep 1
done

if [ "$loop_continue" -eq 1 ]; then
	#IPMI stack is not ready.
	$SEL_LOGGER $SEL_PARAM "IPMI not ready & run $cmd"
fi
#run the command
$cmd