#!/bin/bash
#
# modules Remove the kernel loadable modules if called with any argument 
#

RETVAL=0
RC=0

# See how we were called.
  
. /etc/rc.d/init.d/functions
. /etc/rc.d/init.d/init_functions
. /etc/profile.d/SetNNEnvVar.sh

sanityLog()
{
    /nn/bin/AddNnuDiagLog "$@"
    if [ $? -ne 0 ];then
        echo `date` $0 sanity script failed to log message using AddNnuDiagLog "$@" >> /var/log/StartupSequence.log
    fi
}

start() {
        stop
        return 0 
}

stop() {

	# LED Treatment - identify via LEDs that shutdown is in progress
	sanityLog -mShutdownSequence -lStartupSequence.log -wR -sI -v11503 "Graceful Shutdown in progress. Power LED = solid green; Status LED = flash yellow"

	# Check for the existence of the reset_request UBoot environment variable.
	# If it does not exist, create it with the value of mainos.
	/nn/bin/fw_printenv reset_request | grep "reset_request="
	if [ $? -ne 0 ]; then
	    /nn/bin/fw_setenv reset_request mainos
	fi

	# Do not interact with HWM FPGA for halt or HW Watchdog functionality if 
	# HWM FPGA version is not 1.31 or greater.
	hwmfpga_ver=`/nn/bin/psmtest -f | grep "HWM FPGA Minor Number" | /opt/bin/awk '{print $6}'`
	if [ $hwmfpga_ver -lt "36" ]; then
	    echo "`date` system_exit : early version of HWM FPGA detected ($hwmfpga_ver), no halt or HW Watchdog" >> /var/log/shutdown.log
	    return 0
	fi

	# Check whether system_exit was called as requested halt (runlevel 0) or reboot (runlevel 6).
	# If halt, call spi_hwm_shutdown_en to instruct HWM FPGA to halt system
	# In either case, notify the HW Watchdog of the time before action should be taken.
	case "$0" in
            *rc0.d/K00local)
	        echo "`date` system_exit : shutdown to halt (running spi_hwm_shutdown_en)" >> /var/log/shutdown.log
	        /nn/sbin/spi_hwm_shutdown_en
	        if [ $hwmfpga_ver -gt "36" ]; then
                   echo 150 > /proc/driver/sanity
                else
                   echo 4294967295 > /proc/driver/sanity 
		   touch /tmp/shutdown_to_sleep
                fi
                ;;
            *rc6.d/K00local)
                echo "`date` system_exit : shutdown to reboot" >> /var/log/shutdown.log
                echo 150 > /proc/driver/sanity
                ;;
	esac

        return 0 
}        

restart() {
        stop
}        

reload() {
        restart
}        

case "$1" in
  start)
          start
        ;;
  stop)
          stop
        ;;
  restart)
          restart
        ;;
  reload)
          reload
        ;;
  condrestart)
          [ -f /var/lock/subsys/$prog ] && restart || :
        ;;
  *)
        echo $"Usage: $0 {start|stop|reload|restart|condrestart}"
        exit 1
esac

exit $?
