#!/bin/bash

# pick up some helper functions
source /ciena/scripts/utils.sh

###############################################################################
# FUNCTION:   suckupKrn
#
# Process krn settings.
#
###############################################################################
suckupKrn()
{
    . /ciena/scripts/krn getenv

    ##########################################################
    #   Determine normal versus debug 'kernel' mode.
    #   In debug mode, timeouts are largely disabled.
    ##########################################################

    if [ "$KRN_MODE" = "debug" ]; then
	DEBUG=-D
    else
	DEBUG=
    fi
}

LOGFILE=/dev/console

. /etc/profile
suckupKrn

LEOS_PATH=/mnt/apps/bin/leos

##########################################################
#   Stop previous instance of DHCP-C if running &
#   Unconfigure the interface, gw etc.
##########################################################
/ciena/scripts/stopDhcpc.sh 

##########################################################
#   Kill any existing children of a prior LEOS server.
##########################################################
if [ -r /tmp/fifo/leos/LEOS_IPC_PID ] ; then
    kill -TERM -`cat /tmp/fifo/leos/LEOS_IPC_PID` 2>/dev/null
fi

##########################################################
# Check for Monitor (xgrade) script and run it if required.
# Stops various system services first.
##########################################################
if [ -x /tmp/xgrade/monitor ]; then 	
   echo "Shutting down all kernel modules!!!!"	
   /ciena/scripts/shutdown
   killall -STOP getty login inetd telnetd sshd 2>/dev/null
   echo "Running Monitor (xgrade) script now!!!!"
   (while :; do sleep 5; echo "Software installation in progress..."; done) &
   NOISE=$!
   /tmp/xgrade/monitor   
   kill $NOISE	# Should never actually get here, it resets first.
fi


##########################################################
# Clean up the /tmp/xgrade directory just to be safe
##########################################################
rm -rf /tmp/xgrade/*

if [ ! -f /tmp/console_enable ] ; then
    ##########################################################
    #   There is no console enabled, so glue stdout and
    #   stderr to CONSOLE_COLLECTOR.
    ##########################################################
    CONSOLE_COLLECTOR=/tmp/log/console_collector
    exec </dev/null &>$CONSOLE_COLLECTOR
else
    ##########################################################
    #   Determine disposition of serial port (console).
    #   If in normal mode, only stderr makes it out.
    ##########################################################
    if [ "$KRN_CONSOLE" = "normal" ]; then
        CONSOLE_MIRROR=/tmp/log/console_mirror
        exec </dev/null >$CONSOLE_MIRROR
    fi
fi

##########################################################
#   Find any earlier run history, for flash-based respawns
##########################################################
STATEFILE=/tmp/fifo/leos/LEOS_STATE
STARTFILE=/tmp/fifo/leos/LEOS_STARTING
RUNFILE=/tmp/fifo/leos/LEOS_RUNNING
if [ -r $STATEFILE ]; then
    STATE=`cat $STATEFILE`
else
    STATE=0
fi

if [ $STATE = '1' ]; then	# We died during config, try without?
    NOCONFIG=-n
else
    NOCONFIG=
fi

##########################################################
#   Finally start LEOS!!
##########################################################

# If leos is told to die, pass it on, and make for a fresh start next time.
trap 'kill -TERM $LEOS; wait $LEOS; rm -f $STARTFILE $RUNFILE $STATEFILE; exit 0' SIGTERM

if [ -f $LEOS_PATH ]; then
    chmod g=u /tmp/core* 2>/dev/null # Allow examination of any wreckage
    # leos core files are huge, and could even prevent downloading a
    # new leos.  Wait for the automatic compressor to do its thing.
    while [ -n "$(ls /tmp/core /tmp/core.* 2>/dev/null)" ] ; do
	echo "Waiting for core file to compress..."
	sleep 15
    done
   # Does no harm, but useful in case we ever run Bullseye;
   # but it only captures the coverage for server process.
   # For CLI process(es), it's a manual procedure.
   if [ -f /tmp/be_test.cov ] ; then
      export COVFILE=/tmp/be_test.cov
   fi
   touch /etc/nologin
   echo `date` Starting SAOS from $LEOS_PATH >> $LOGFILE
   rootfs_location=$(get_rootfs_location)
   if [ $rootfs_location = "flash" -a $KRN_RESPAWN = "enable" ]
   then			# Only get tricky with flash-based respawns.
       if [ -n $NOCONFIG ]
       then
          /bin/tar xzf /etc/etc.tar.gz -C /
          chmod o-w /etc
          /ciena/scripts/fixup_etc_issue
       fi
       rm -f $RUNFILE

       $LEOS_PATH $DEBUG $NOCONFIG -s &	# Run leos.
       LEOS=$!

       wait $LEOS	# Allows SIGTERM signal to propagate to leos via trap.
       ES=$?

       suckupKrn	# Check for respawn changes while leos was running.
       if [ $KRN_RESPAWN != "enable" ]; then
	   rm -f $STARTFILE $RUNFILE $STATEFILE
	   exit $ES
       fi

       if [ $ES -ne 0 ]	# Post-mortem time...
       then		# Died abnormally, or never even ran.
	   if [ ! -r $STARTFILE -a  ! -r $RUNFILE ]
	   then		# Died very early, before config.
	       reboot	# To (presumably) alternate flash bank.
	   elif [ -r $STARTFILE ]
	   then		# Died during config.
	       if [ $STATE = '1' ]
	       then	# Already tried with no config file?
		   reboot # To (presumably) alternate flash bank.
	       else	# Try next time with no config file.
		   echo -n 1 >$STATEFILE
	       fi
	   else		# Died after running 1+ minutes, back to normal.
	       echo -n 0 >$STATEFILE
	   fi
       else		# Ran successfully, back to normal.
	   echo -n 0 >$STATEFILE
       fi
   else			# Non-flash, or non-respawn.  Just run leos.
       rm -f $STATEFILE
       exec $LEOS_PATH $DEBUG -s
   fi
else
    echo `date` $LEOS_PATH: No such file >> $LOGFILE
    sleep 5
fi
