#
#    Copyright (c) 1996-2016 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    File name:   diagburnin.sh
#    Module name: diag/scripts
#
#    This file contains several useful functions used by the
#    diagnostics burnin support.  They are stuck here
#    to save some disk image space.  To optimize execution time
#    copy this file into each of the command scripts instead.
#
INTEGER=2			      # config modes
STRING=5
HEX=6
# definitions that must match src/include/em/em_if.h ledState_e
LED_DEFAULT=0
LED_SOLID_OFF=1
LED_SOLID_ON=2
LED_FAST_BLINK=3
LED_SLOW_BLINK=4
LED_VSLOW_BLINK=5
LED_DIAG_ACTIVE=6
LED_DIAG_FAIL=7
LED_DIAG_PASS=8
#
# Begin burnin script support
# Bill Lewis 7/24/2001
#
##################################
#PRIVATE FUNCTIONS
##################################
##################################
# This function import_burnin_variables() is intended for
# internal use only. 
#
# The function processes two lists in the create_param_list().
# The first list is the parameterized constants that are non editable
# (PARAMCONST). The second list is the parameterized variables
# that are editable.
#
# It ensures that each PARAMDEF and PARAMVAR 
# entry exists in the config database.
#
# It gets the variable name from field 2 of the file, and the 
# default value from field 3. If the item does not exist, then it is 
# created, and given the default value. Otherwise, the config 
# database value is left untouched.
# $1 = PARAMDEF/PARAMCONST to parse
# space seperated list
#  field 1 = "PARAMDEF" or "PARAMCONST"
#  field 2 = variable name
#  field 3 = default value
#  field 4 = mode: $INTEGER, $STRING
#  field 5 = minimum value
#  field 6 = maximum value
#  field 7 = description

##################################
import_burnin_variables()
{
  # default the required parameters incase they are missing
  export number_of_runs=1
  export log_length=600
  export debug_on=1
  export bplb_on=0
  export margin_on=0
  export refclk_on=0
  export frcslv_on=0
  export min_lb_mode=2
  export reset_every=0
  export sof=0
  export portlogdump_on=0
  export bisr_every=0
  export bist_every=0
  export vib=2
  export thermal=10
  if [ $QUAL_AVAILABLE = TRUE ]
  then
    init_qual_variables
  fi

  export label=`/bin/echo $MyName | /usr/bin/tr "a-z" "A-Z"`

  # get the parameters listed i the file
  _param_list=`get_param_list`
  export _num_params=`/bin/echo $_param_list | \
         /usr/bin/tr -s " " "_" | \
         /usr/bin/tr -s "@" " " | \
         /usr/bin/wc -w | \
	 /bin/sed "s/ //g"`
  config_list=`get_config_list`
  _num=1
  while [ $_num -le $_num_params ]
  do
    _param=`/bin/echo $_param_list | /usr/bin/cut -d"@" -f$_num`
    _var_name=`/bin/echo $_param | /usr/bin/cut -d" " -f2`
    _dflt_val=`/bin/echo $_param | /usr/bin/cut -d" " -f3`
    _mode_val=`/bin/echo $_param | /usr/bin/cut -d" " -f4`
    _cur_val="`get_config_entry $_var_name`"
    if [ -z "$_cur_val" ]
    then
      _cur_val=$_dflt_val
      setConfig diag.$MyName.$_var_name $_mode_val "$_dflt_val"
    fi
    burninMessage "$_var_name=\""$_cur_val\"
    export `eval /bin/echo $_var_name`="`eval /bin/echo $_cur_val`"
    _num=`/usr/bin/expr $_num + 1`
  done
  _param_list=`get_paramconst_list`
  export _num_params=`/bin/echo $_param_list | \
         /usr/bin/tr -s " " "_" | \
         /usr/bin/tr -s "@" " " | \
         /usr/bin/wc -w | \
	 /bin/sed "s/ //g"`
  config_list=`get_config_list`
  _num=1
  while [ $_num -le $_num_params ]
  do
    _param=`/bin/echo $_param_list | /usr/bin/cut -d"@" -f$_num`
    _var_name=`/bin/echo $_param | /usr/bin/cut -d" " -f2`
    _dflt_val=`/bin/echo $_param | /usr/bin/cut -d" " -f3`
    _mode_val=`/bin/echo $_param | /usr/bin/cut -d" " -f4`
    _cur_val="`get_config_entry $_var_name`"
    if [ -z "$_cur_val" ]
    then
      _cur_val=$_dflt_val
      setConfig diag.$MyName.$_var_name $_mode_val "$_dflt_val"
    fi
    burninMessage "$_var_name=\""$_cur_val\"
    export `eval /bin/echo $_var_name`="`eval /bin/echo $_cur_val`"
    _num=`/usr/bin/expr $_num + 1`
  done
}

##################################
# This function valide_integer() is an internal only function.
# It determines if an integer is between two values. It
# expects the first parameter to be the value in question. The
# second value to be the minimum acceptable value, and the
# third value to be the maximum acceptable value. The min and
# max values are considered valid.
# $1 = value to test
# $2 = minimum acceptable value
# $3 = maximum acceptable value
##################################
validate_integer()
{
  _pass=TRUE
  _x=`/usr/bin/expr $1 : "\([-]*[0-9]\+\)"`
  if [ "$_x" != "$1" ]
  then
    _pass=NOTNUMBER
  else
    if [ "$2" != "NA" ]
    then
      _x=`/usr/bin/expr $2 : "\([-]*[0-9]\+\)"`
      if [ "$_x" != "$2" ]
      then
        _pass=MINNOTNUMBER
      else
        if [ "$1" -lt "$2" ]
        then
          _pass=LESSTHANMIN
        fi
      fi
    fi
    if [ "$3" != "NA" ]
    then
      _x=`/usr/bin/expr $3 : "\([-]*[0-9]\+\)"`
      if [ "$_x" != "$3" ]
      then
        _pass=MAXNOTNUMBER
      else
        if [ "$1" -gt "$3" ]
        then
          _pass=GREATERTHANMAX
        fi
      fi
    fi
  fi
  /bin/echo $_pass
}

####################################
# get_tmp_stats gets environmental
# statistics(temperature in centigrade)
# of the unit
####################################
get_tmp_stats()
{
    if [ $MultiBlade = TRUE ]
    then
      _cmd=`commandPath tempshow`
      temp=`$_cmd | /usr/bin/tr -s  " 	" "  " | /bin/grep -w $Slot | /usr/bin/cut -d" " -f5 | /usr/bin/xargs`
    else
      _cmd=`commandPath tempshow`
      temp=`$_cmd | /usr/bin/tr -s "		" "  " | /bin/grep [0-9] | /usr/bin/cut -d" " -f4 | /usr/bin/xargs `
    fi
    /bin/echo "$temp"
}

####################################
# get_volt_stats gets environmental
# statistics(voltage) of the unit
####################################
get_volt_stats()
{
      _cmd=`commandPath diagsensordump`
      volts=`$_cmd -volt 20 "Slot $Slot" | /usr/bin/tr -s " 	" "  " | /usr/bin/cut -d"-" -f1`
      /bin/echo "$volts"
}

####################################
# get_stats gets the environmental
# statistics (temperature and voltage)
# of the unit
####################################
get_stats()
{
     temp=`get_tmp_stats`
     volts=`get_volt_stats`
     /bin/echo "v{$volts},t{$temp c}"
}

####################################
# PRIVATE STATUS AND SIGNAL HANDLING
#
# cleanup() function to process trapped signal received. 
#
# For the burnin operation, any active child process is killed
# with the TERM signal, status, and messages are output, then the
# normal exit function is called
####################################
doburnin_cleanup()
{
  #
  # get the current slot
  #
  _slot=$FABOS_SLOTNO

  if [ $burninStarted -ne 0 ]
  then
    #
    # set abort flag
    #
    State=ABORT
    burninMessage "Script has been ABORTED `/bin/date`" > /dev/null 2>&1
    saveBladeParams $_slot

    if [ $Child -ne 0 ]
    then
      /bin/kill -TERM $Child
      /bin/echo ""
      burninMessage "Exiting. Kill pid $Child"
    fi
    #
    # Save time data for ending summary
    #
    _current_time=`/bin/date \+\%s`
    _duration=`/usr/bin/expr $_current_time - $StartTime`
    _minute=`/usr/bin/expr $_duration / 60`
    _hour=`/usr/bin/expr $_minute / 60`
    _sec=`/usr/bin/expr $_duration % 60`
    _minute=`/usr/bin/expr $_minute % 60`

    #
    # Set exit status now that we are done
    #
    if [ $CumulativeStatus -eq 0 ]
    then
      _cum_state=PASSED
    else
      _cum_state=FAILED
    fi

    #
    # Output a ending summary
    #
    _message="$State stat $_cum_state $TotalCmdNumber cmds in $RunNumber runs Therm $TotalThermal Vib $TotalVib in $_hour hr $_minute min $_sec sec ($_hour:$_minute:$_sec)"
    burninMessage "$_message"
    # Remove double spaces in the message for the forceError command
    _message=`/bin/echo "$_message" | /usr/bin/tr -s " " " "`
    _cmd=`commandPath exec_diag`
    if [ $MultiBlade = TRUE ]
    then
      $_cmd forceError --slot $_slot -severity 4 -message '"'" $Slot $MyName: $_message"'"'
    else
      $_cmd forceError --slot $_slot -severity 4 -message '"'" $MyName: $_message"'"'
    fi
    burninMessage "$_message"
    if [ "$label" != "-" ]
    then
      burninMessage "Label $label"
    fi

    #
    # Always restore LED control back to EM. the blade will either FAULT
    # and turn on the ATTN lite based on the SLOT_FAULT from diagd, or
    # the attn lite will be off as the blade transitions to SLOT_ON state.
    # These two LED conditions match the definition burnin final status for
    # all 4.x products.
    #
    _cmd=`commandPath exec_diag`
    eval $_cmd bogus_test_to_set_led --slot $_slot --setled $LED_DEFAULT > /dev/null 2>/dev/null &
    burninMessage "Burnin script exiting PID $_pid with status $CumulativeStatus"

  fi

  #
  # update the blade state as COMPLETE_ABORT
  #
  saveBladeParams $_slot STATE COMPLETE_ABORT
  /bin/sync

  exit $CumulativeStatus
}

####################################
# check_command_status() function monitors the exit status of the
# executed command. It waits for exec_diag return and process the
# return status. Both the RunStatus and CumulativeStatus are updated 
# based on failing results.
#
#  check_command_status $command_name $finish_time $ALL(TRUE/FALSE)
#
# Messages are generated to output the result of the command.
####################################
check_command_status()
{
  # wait for current child to finish and get return status
  #
  export Child=$!
  echo "PV Child PID $Child `/bin/date`" >>$LogFile
  wait $Child >>$LogFile 2>>$LogFile
  _testresult=$?
  echo "PV After wait testresult $_testresult `/bin/date`" >>$LogFile
  if [ $_testresult -eq 127 ]
  then
    burninMessage "TESTRESULT IS 127 SO TRY AGAIN"
    wait $Child >>$LogFile 2>>$LogFile
    _testresult=$?
    if [ $_testresult -eq 127 ]
    then
      burninMessage "TESTRESULT IS STILL 127 AFTER SECOND TRY"
      wait >>$LogFile 2>>$LogFile
      _testresult=$?
      burninMessage "FINAL TESTRESULT IS $_testresult"
    fi
  fi
  export Child=0
  if [ $_testresult -eq 139 -o $_testresult -eq 237 ]
  then
    burninMessage "Command #$CmdNumber Run $DIAG_PKG_PASS Known issue ($_testresult) $_new_var"
    _testresult=16
  fi
  #
  # diagshow will only fail if a port has faulted.
  #
  _cmd=`commandPath exec_diag`
  $_cmd diagshow --slot $Slot -silent 1 -use_bports 1 >> $LogFile
  _showresult=$?
  echo "PV diagshow result  $_showresult `/bin/date`" >> $LogFile
  if [ $_showresult -eq 127 -o $_showresult -eq 139 -o $_showresult -eq 237 ]
  then
    burninMessage "Command #$CmdNumber Run $DIAG_PKG_PASS Known issue ($_showresult) diagshow"
    _showresult=0
  fi

  if [ $_showresult -ne 0 ]
  then
    bladeID=`getBladeID $Slot`
    if [ "$bladeID" !=  "STRIKER" ]
    then
      burninMessage "Ignore diagshow result ($_showresult) for  Platform $bladeID test result $_testresult"
      _showresult=0
    fi
  fi
  #  construct PASSED or FAILED msg from return value of command
  #  .  return value = 0 for PASSED
  #  .  return value != 0 for FAILED
  #
  # For all test status updating following table:
  #              Normal test    "ALL" test
  #------------------------------------------------------------------
  #  Test P/F result		test return		"COMPLETE"
  #  Script cum status	test+show		show
  #  Blade LED		prev_cum+test+show	prev+show
  #
  # NOTE: that prev is handled in
  #  initialize_burnin_variables(). This reads the cumulative
  #  status from the non-volitile memory, and sets status and
  #  LED state based on that value. Therefore it does not need
  #  to be considered here.
  #
  # NOTE: Return values of 237 or 139 indicate that there was a problem
  # with Linux actually executing the command. Since these commands never
  # were executed (diagshow or the actual command), their staus is ignored. 
  #
  if [ "$3" = "TRUE" -a $MultiBlade = TRUE ]
  then
    if [ $_showresult -ne 0 ]
    then
      CumulativeStatus=`/usr/bin/expr $CumulativeStatus + 1`
      RunStatus=1
      # --setled only takes effect if the command fails.
      # net result is turn on the LED since test
      # will always fail
      _cmd=`commandPath exec_diag`
      eval $_cmd bogus_test_to_set_led --slot $Slot --setled $LED_DIAG_FAIL > /dev/null 2>/dev/null
      burninMessage "Found error in $1 during run $RunNumber showresult $_showresult"
    fi
  else
    if [ $_testresult -eq 0 ]
    then
      _stat=PASSED
    else
      skipped_abort=`/usr/bin/expr $_testresult % 32`
      skipped_abort=`/usr/bin/expr $skipped_abort / 16`
      skipped_abort=`/usr/bin/expr $skipped_abort \* 16`
      case "$_testresult" in
      "$skipped_abort")
        _stat=SKIPPED;;
      *)
        _stat=FAILED;;
      esac
    fi
    if [ $_showresult -ne 0 -o "$_stat" = "FAILED" ]
    then
      CumulativeStatus=`/usr/bin/expr $CumulativeStatus + 1`
      RunStatus=1
      # --setled only takes effect if the command fails.
      # net result is turn on the LED since test
      # will always fail
      _cmd=`commandPath exec_diag`
      eval $_cmd bogus_test_to_set_led --slot $Slot --setled $LED_DIAG_FAIL > /dev/null 2>/dev/null
      burninMessage "Found error in $1 during run $RunNumber showresult $_showresult testresult $_testresult"
      if [ "$portlogdump_on" = 1 ]
      then
	portlogdump >> $LogFile
      fi
    fi
  fi
  burninMessage "Command #$CmdNumber Run $DIAG_PKG_PASS $_stat $1 `/bin/date` `get_stats`"
  _current_time=`/bin/date \+\%s`
  _duration=`/usr/bin/expr $_current_time - $2`
  _minute=`/usr/bin/expr $_duration / 60`
  _hour=`/usr/bin/expr $_minute / 60`
  _sec=`/usr/bin/expr $_duration % 60`
  _minute=`/usr/bin/expr $_minute % 60`
  burninMessage "Command #$CmdNumber Run $DIAG_PKG_PASS Duration: $1 took $_hour hr $_minute min $_sec sec ($_hour:$_minute:$_sec)"
  if [ "$sof" = 1 -a $RunStatus = 1 ]
  then
    cleanupOnExit
  fi
}

##################################
# NAME
#    initialize_burnin_variables - Initializes the variables used
#                                  to control the burnin process
#
# SYNOPSIS
#    initialize_burnin_variables
#
# DESCRIPTION
#    This function initialize_burnin_variables() is used by scripts
#    that need values from non-volitile memory. For burnin, these
#    are RunNumber, and State of the overall burnin, and the
#    CumulativeStatus of the run. These are gathered from the serial 
#    EEPROM on each blade.
#
#    The number of runs to execute are contained in the PARAMDEF stored in 
#    config database.
#
# OPERANDS
#    NONE
#
##################################
initialize_burnin_variables()
{
  # Set for the diag to use in logging
  export DIAG_PKG_PASS=$RunNumber
  export State=ACTIVE
  # Make sure LED's match test status after power cycle
  # exec_diag grabs all "--" arguments and executes them
  if [ $CumulativeStatus -ne 0 ]
  then
    # Failed already
    _cmd=`commandPath exec_diag`
    eval $_cmd bogus_test_to_set_led --slot $Slot --setled $LED_DIAG_FAIL > /dev/null 2>/dev/null &
    burninMessage "Stored status indicates cumulative fail."
  else
    # Passing so far
    _cmd=`commandPath exec_diag`
    eval $_cmd bogus_test_to_set_led --slot $Slot --setled $LED_DIAG_ACTIVE > /dev/null 2>/dev/null &
  fi
  # format up the start time for the logging messages
  _tmp=`/bin/cat /proc/dcomm`
  _sec=`/usr/bin/expr "$_tmp" : ".*time: \+\([0-9]\+\)"`
  _msec=`/usr/bin/expr "$_tmp" : ".*time: \+[0-9]\+:\([0-9]\+\)"`
  if { [ -z $_sec ] || [ -z $_msec ] ; }
  then
    _sec=0
    _msec=0
  fi
  export DIAG_PKG_BEG="$_sec:$_msec"

  # get the parameters for the script
  export NumberOfRuns=`getConfig diag.$MyName.number_of_runs $INTEGER $number_of_runs`
  export MinLbMode=`getConfig diag.$MyName.min_lb_mode $INTEGER $min_lb_mode`
  LogLength=`getConfig diag.$MyName.log_length $INTEGER $log_length`
  case $MinLbMode in
    1 ) MinLbMode2=7;;
    2 ) MinLbMode2=8;;
    5 ) MinLbMode2=9;;
  esac

  export LogLength=`/usr/bin/expr $LogLength \* 1000`

  if [ "$NumberOfRuns" = 1 ]
  then
    ConfigSetCheck diag.$MyName.number_of_runs $INTEGER
    if [ $? != 0 ]
    then
      setConfig diag.$MyName.number_of_runs $INTEGER 1
    fi
  fi
  Vib=`getConfig diag.$MyName.vib $INTEGER $vib`
  if [ "$Vib" = 0 ]
  then
    ConfigSetCheck diag.$MyName.vib $INTEGER
    if [ $? != 0 ]
    then
      setConfig diag.$MyName.vib $INTEGER 0
    fi
  fi
  Thermal=`getConfig diag.$MyName.thermal $INTEGER $thermal`
  if [ "$Thermal" = 0 ]
  then
    ConfigSetCheck diag.$MyName.thermal $INTEGER
    if [ $? != 0 ]
    then
      setConfig diag.$MyName.thermal $INTEGER 0      
    fi
  fi
}

##################################
# NAME
#    get_filename - Get the name of the current script
#
# SYNOPSIS
#    get_filename
#
# DESCRIPTION
#    This command reads the shell arguments and extract the name 
#    of the command referenced by the user. The preceding 
#    directories are stripped as are the trailing extentions.
#
#    The burnin log files are created at the same time. They are:
#    LogFile, and UserFile
#
# OPERANDS
#    NONE
#
##################################
get_filename()
{
  # Initialize incase of trap
  export StartTime=`/bin/date \+\%s`
  export Child=0
  RunNumber=0
  TotalCmdNumber=0
  TotalThermal=0
  TotalVib=0
  CmdNumber=0

  # setup some default values
  export CumulativeStatus=0
  export Slot=$_def_slot
  export DIAG_POST=1
  export DIAG_USR_FAILLIM=16

  _cmd=`commandPath setdbg`
  $_cmd DIAG 1

  # get the main three: home, switch, and slot
  if [ ! -z "$FABOS_SLOTNO" ]
  then
    export Slot=$FABOS_SLOTNO
  else
    export FABOS_SLOTNO=$_def_slot
    export Slot=$FABOS_SLOTNO
  fi
  saveBladeParams $Slot PID $$

  if [ -z "$FABOSHOME" ]
  then
    export FABOSHOME=/fabos
  fi

  export FABOS_SWITCHNO=`getSwitchFromSlot $Slot`

  export MultiBlade=`isMultiBlade`
  if [ $MultiBlade = TRUE ]
  then
    slot_message=" $Slot"
  else
    slot_message=""
  fi
  # Adjust bisr to bist for bloom 1 vs bloom 2 products
  case `getSWBD` in
  SWBD10 | SWBD12 | SWBD22) bisr_message="bisr";;
  * ) bisr_message="bist";;
  esac

  saveBladeParams $Slot PID $$
  # setup the file names to use
  MyName=`getConfig diag.mode.burnin.$Slot.name $STRING "verify"`
  # Convert old script name to process step name
  MyName=`/bin/echo $MyName | /bin/sed -e "s/switch//g" -e "s/\.sh//g" -e "s/\.//g"`
  _log_path=`burninLogPath $MyName`
  export LogCmd=`commandPath logdata`
  export LogFile=$_log_path/$MyName.$Slot.log
  # truncate once to repair lost files from last power cycle.
  _cmd=`commandPath trunclog`
  $_cmd -f $LogFile -l 0 2>/dev/null
   burninMessage "Sending logs to $LogFile"
  # walk to path to ensure path is available
  export UserFile="$MyName.$Slot.usr"
}

##################################
# NAME
#    get_command_list - Get the output of the create_command_list
#		        function to stdout
#
# SYNOPSIS
#    get_command_list
#
# DESCRIPTION
#    This command executes the create_command_list function and places
#    a "@" seperator after every line that is a command. Any line that
#    is not a command is eliminated from the output by the "isCommand"
#    filter.
#
#    No need to filter for comment lines or empty lines. The function 
#    isACommand will do that for us.
#
# OPERANDS
#    NONE
#
##################################
get_command_list()
{
  create_command_list | while read _line
  do
    if [ `isACommand "$_line"` = "command" ]
    then
      /bin/echo $_line@
    fi
  done
}

##################################
# NAME
#    get_non_diag_errors - Searches the burninerr log for errors from
#			 surces other than the diagnostics that occured
#			 during the current burnin run.
#
# SYNOPSIS
#    get_non_diag_errors
#
# DESCRIPTION
#    This function get_non_diag_errors() assumes that the entries
#    in the burninerrshow output are in cronological order.
#    It also assumes that a burnin cycle is active, and that it must
#    have a start message before this function has been called.
#
#    The entire burnin error log is sampled to determine if there are
#    any entries other than diagnostics. If some are detected, then the
#    last burnin start message is located, and its line number in the
#    output is saved. If a start mesage is not found, then it is
#    assumed that the errors are valid, and a message is output, and
#    fail status returned.
#
#    Once the position of the last start message is located, then the
#    position of each non diagnostic error is compared to that of the start.
#    If the error appears after the start, then the error is considered
#    within this run, and error messages and status are sent.
#
# RESULT
#    The result of the testing is found by the existance of the file
#    /var/log/non_diag_stat_$Slot. If the file exists, then an error was
#    found. If it does not exist, then no error was found.
#
#    It is the callers responsibility to remove the file after testing
#    for the result. This function will remove it prior to the evaluation
#    to ensure the accuracy of the testing.
#
# OPERANDS
#    $1 after_inc - inicates the function was called after the
#	RunNumber was incremented at the end of the run.
#
##################################
get_non_diag_errors()
{
  if [ "$1" == "after_inc" ]
  then
    _run=`/usr/bin/expr $RunNumber - 1`
  fi
  _cmd=`commandPath burninerrshow`
  /bin/rm -f  /tmp/non_diag_stat_$Slot
  $_cmd $Slot | cat -b | tr -s " 	" "  " > /tmp/$$.tmp
  if [ -f /tmp/$$.tmp -a "`/bin/grep '^ [0-9]* [0-9][0-9][0-9][0-9]\/[0-9][0-9]\/[0-9][0-9]\-[0-9][0-9]\:[0-9][0-9]' /tmp/$$.tmp | grep -v '\[DIAG-'`" != "" ]
  then
    _last_start=`/bin/cat /tmp/$$.tmp | \
        /usr/bin/tr -s "\000 " " " | \
        /bin/grep -n "Starting run" | \
        /usr/bin/tail -n1 | \
        /usr/bin/cut -d":" -f1`
    if [ "$_last_start" != "" ]
    then
      /bin/grep '^ [0-9]* [0-9][0-9][0-9][0-9]\/[0-9][0-9]\/[0-9][0-9]\-[0-9][0-9]\:[0-9][0-9]' /tmp/$$.tmp |\
      /bin/grep -v '\[DIAG-' |\
      /bin/grep -v WARN |\
      /bin/grep -v INFO |\
      /usr/bin/cut -d" " -f2 | \
      while read error_line
      do
        if [ ! -z "$error_line" ]
        then
          if [ "$error_line" -gt $_last_start ]
          then
            touch /tmp/non_diag_stat_$Slot
            burninMessage "NON_DIAG errors detected during run $_run"
            break;
          fi
        fi
      done
    else
      touch /tmp/non_diag_stat_$Slot
      /burninMessage "NON-DIAG errors detected during run $_run, but no Start message"
    fi
  fi
  /bin/rm -f  /tmp/$$.tmp
}

##################################
# NAME
#    get_any_errors - Searches the burninerr log for any errors during
#		      the current burnin run.
#
# SYNOPSIS
#    get_any_errors
#
# DESCRIPTION
#    This function get_any_errors() assumes that the entries
#    in the burninerrshow output are in cronological order.
#    It also assumes that a burnin cycle is active, and that it must
#    have a start message before this function has been called.
#
#    The entire burnin error log is sampled to determine if there are
#    any error entries at all. If some are detected, then the
#    last burnin start message is located, and its line number in the
#    output is saved. If a start mesage is not found, then it is
#    assumed that the errors are valid, and a message is output, and
#    fail status returned.
#
#    Once the position of the last start message is located, then the
#    position of each error is compared to that of the start. If
#    the error appears after the start, then the error is considered
#    within this run, and error messages and status are sent.
#
# RESULT
#    The result of the testing is found by the existance of the file
#    /var/log/error_stat_$Slot. If the file exists, then an error was
#    found. If it does not exist, then no error was found.
#
#    It is the callers responsibility to remove the file after testing
#    for the result. This function will remove it prior to the evaluation
#    to ensure the accuracy of the testing.
#
# OPERANDS
#    NONE
#
##################################
get_any_errors()
{
  _cmd=`commandPath burninerrshow`
  /bin/rm -f  /tmp/error_stat_$Slot
  $_cmd $Slot > /tmp/$$.tmp
  if [ -f /tmp/$$.tmp -a "`/bin/grep -e '\[DIAG-' /tmp/$$.tmp | /bin/grep -v WARN` | grep -v 'Sts#'" != "" ]
  then
    _last_start=`/bin/cat /tmp/$$.tmp | \
        /usr/bin/tr -s "\000 " " " | \
        /bin/grep -n "Starting" | \
        /usr/bin/tail -n1 | \
        /usr/bin/cut -d":" -f1`
    if [ "$_last_start" != "" ]
    then
      /bin/cat /tmp/$$.tmp | \
      /usr/bin/tr -s "\000 " " " | \
      /bin/grep -n "\[DIAG-" | \
      /bin/grep -v "Sts#" |\
      /bin/grep -v WARN |\
      /bin/grep -v INFO |\
      /usr/bin/cut -d":" -f1 | \
      while read error_line
      do
        if [ ! -z "$error_line" ]
        then
          if [ $error_line -gt $_last_start ]
          then
            touch /tmp/error_stat_$Slot
            burninMessage "Errors detected during run $_run"
            break;
          fi
        fi
      done
    else
      touch /tmp/error_stat_$Slot
      burninMessage "Errors detected during run $_run, but no Start message"
    fi
  fi
  /bin/rm -f  /tmp/$$.tmp
}

##################################
# NAME
#    truncate_log - Truncate log to prevent file system overflow
#
# SYNOPSIS
#    truncate_log
#
# DESCRIPTION
#    This function truncate_log() determine if the log file is greater
#    than $LogLength characters in size, and truncate  it to 3/4 the
#    number of lines after putting all errors in the file at the
#    top of the file.
#
#    NOTE: that if the LogLength is too small and/or the number of
#    errors is great, that the resulting file can be larger than LogLength.
#
# check log file length, trim the log file if necessary
# Trim log file if greater than LogLength (300000 default) characters
# 300000 X 8 blades = 2.4 meg * 2 = 4.8 Meg (*2 max growth per test)
# tmp logs 3/4 4.8 meg = 3.6 Meg + 4.8 Meg = 7.4 Meg of log files
# 8 Meg is about all the space we have to operate in.
#
# NOTE: the trimming functionality was redesigned as a progam, and is not longer
# contained in the script.
#
# OPERANDS
#    NONE
#
##################################
truncate_log()
{
  if [ $LogLength -gt 0 ]
  then
    _cmd=`commandPath trunclog`
    $_cmd -f $LogFile -l $LogLength
  fi
}

##################################
#PUBLIC FUNCTIONS
##################################
##################################
# This function burninMessage() is intended for
# internal use only. It formats the output messages during burnin to
# be blade product sensative.
#
# It gets the message to output as the input parameters, and prepends
# slot information if appropriate.
# $* = message to output
##################################
burninMessage()
{
  /bin/echo "$slot_message $MyName: $*"
  $LogCmd $LogFile "$slot_message $MyName: $*"
}
##################################
# NAME
#    sharedResourceTimeout - Output TRUE if the CP128 cards have completed POST2
#
# SYNOPSIS
#    sharedResourceTimeout
#
# DESCRIPTION
#    This monitors the backplane loopback and CP128 board POST status to
#    indicate when is is OK to run backplane tests. This routine will wait
#    until the CP128 blades (if any) are in the proper state to perform
#    shares activity with the PORT blades.
# OPERANDS
#     $1 = bplb_mode
##################################
sharedResourceTimeout()
{
  p1timeout=900
  p2timeout=600
  current_time=`/bin/date \+\%s`
  end_time=`/usr/bin/expr $current_time + $p1timeout`
  bplb_mode="$1"
  if [ $bplb_mode = 1 ]
  then
    /bin/echo "SKIP"
  else
    _cmd=`commandPath slotshow`
    _cp=`$_cmd | /usr/bin/tr -s " " " " | \
      /bin/grep "CP BLADE" | /usr/bin/cut -d" " -f3-`

    # ensure the Id is CP128
    _cp128=`/bin/echo $_cp | /bin/grep 5`
    if [ "$_cp128" = "" ]
    then
      /bin/echo "CONTINUE"
    else
      done=FALSE
      current_state=`$_cmd | /usr/bin/tr -s " " " " | \
    /bin/grep "CP BLADE" | /usr/bin/cut -d" " -f5-`
      while [ $current_time -lt $end_time -a "$done" = "FALSE" ]
      do
        # We have cp128s, check state of the two blades.
	# if either one is in a ENABLED state then we can proceed
	_state=`$_cmd | /usr/bin/tr -s " " " " | \
		/bin/grep "CP BLADE" | /usr/bin/cut -d" " -f5-`
	p1_state="`/bin/echo $_state | /bin/grep -e POST1`"
	if [ "`/bin/echo $p1_state`" != "" ]
	then
	  # At least one CP128 in POST1
	  current_time=`/bin/date \+\%s`
	  if [ "$current_state" != "$_state" ]
	  then
	    # At least one started POST1
	    current_state="$_state"
	    end_time=`/usr/bin/expr $current_time + $p1timeout`
	  fi
	else
	  # At least one in POST2, none in POST1
	  p2_state="`/bin/echo $_state | /bin/grep -e POST2`"
	  if [ "`/bin/echo $p2_state`" != "" ]
	  then
	    current_time=`/bin/date \+\%s`
	    if [ "$current_state" != "$_state" ]
	    then
	      current_state="$_state"
	      end_time=`/usr/bin/expr $current_time + $p2timeout`
	    else
	      if [ $current_time -ge $end_time ]
	      then
	    	/bin/echo "TIMEOUT"
	      fi
	    fi
	  else
	    # we are able to test now
	    end_time=`/usr/bin/expr $current_time - $p2timeout`
	    /bin/echo "CONTINUE"
 	    done="TRUE"
	  fi
  	fi
      done
    fi
  fi
}
##################################
# NAME
#    checkBurninState - Determines if burnin can continue
#
# SYNOPSIS
#    checkBurninState
#
# DESCRIPTION
#    This function checkBurninState() handles getting the script
#    variables initialized.
#
#    The script determines if it is OK to start a burnin run. 
#    If the burnin State is COMPLETE, then it is not safe to start 
#    burnin. This differentiates a real start from a power cycle of 
#    the same burnin run.
#
# OPERANDS
#    NONE
##################################
checkBurninState()
{
  export RunNumber=`getBladeParam $Slot RUN_NUMBER`
  export _stored_state=`getBladeParam $Slot STATE`
  export CumulativeStatus=`getBladeParam $Slot CUM_STATUS`
  export RunStatus=`getBladeParam $Slot RUN_STATUS`
  export RunTime=`getBladeParam $Slot RUN_TIME`
  export TotalCmdNumber=`getBladeParam $Slot TOTAL_CMD_NUMBER`
  export CmdNumber=`getBladeParam $Slot CMD_NUMBER`
  export TotalThermal=`getBladeParam $Slot TEMP_CYCLE`
  export TotalVib=`getBladeParam $Slot VIB_CYCLE`

    #
    # Begin processing the PARAMETERS
    #
    import_burnin_variables
    #
    # Begin processing the COMMAND file content
    #
    export CommandList=`get_command_list`
    export NumberOfCommands=`/bin/echo $CommandList | \
         /usr/bin/tr -s " " "_" | \
         /usr/bin/tr -s "@" " " | \
         /usr/bin/wc -w | \
	 /bin/sed "s/ //g"`

    # Save the fact that we went live
    export State=ACTIVE

    #
    # Get the cp slot, and post to CP log
    #
    _cmd=`commandPath getCPSlot`
    _cp_slot=`$_cmd | /usr/bin/cut -d" " -f3`
    _cmd=`commandPath exec_diag`

    burnin_level=`getConfig diag.mode.burnin.level $INTEGER 0`
    num_switches=`getNumSwitches`
    switch=0
    initial_switch=$FABOS_SWITCHNO
    while [ $switch -lt $num_switches ]
    do
      if [ "$burnin_level" != "0" ]
      then
        export FABOS_SWITCHNO=$switch
        case `getSWBD` in
        "SWBD148" | "SWBD171" )
        burninMessage "Hardcoding the first slot value"
        export _first_slot=0;;
        * )
        export _first_slot=`$_cmd diagshow | \
          /bin/grep Slot | \
          /usr/bin/cut -d " " -f2 | \
          /usr/bin/xargs /bin/echo | \
          /usr/bin/cut -d " " -f1` ;;
        esac        
        break
      fi
      switch=`/usr/bin/expr $switch + 1`
    done
    export FABOS_SWITCHNO=`getSwitchFromSlot $Slot`

    _date=`/bin/date`
    _serial=`chassisshow | /bin/grep -w -A4 "Slot: $Slot" | /bin/grep Serial | /usr/bin/cut -f2`
    if [ $MultiBlade = TRUE ]
    then
      if [ "$_first_slot" = "$Slot" ]
      then
        _message=" $Slot CP $_cp_slot Starting $MyName run $RunNumber $_date"
        # Remove double spaces in the message for the forceError command
        _message=`/bin/echo "$_message" | /usr/bin/tr -s " " " "`
        _cmd=`commandPath exec_diag`
        $_cmd forceError --slot $_cp_slot -severity 4 -message '"'"$_message"'"'
      fi
    fi

    # get the run and command numbers
    initialize_burnin_variables
    if [ "$_stored_state" = "INITIALIZED" ]
    then
      burninMessage "Run diagClearError"
      _cmd=`commandPath exec_diag`
      $_cmd diagClearError $Slot

      export StartTime=`/bin/date \+\%s`
    else
      export StartTime=`getBladeParam $Slot START_TIME`
      # Check burninerrlog to see if there were any fails since we
      # have started. There could be fails on the test that was
      # interupted during a power cycle. We want to tag a blade as
      # fail even if the test was interupted.
      get_any_errors
      if [ -f /tmp/error_stat_$Slot ]
      then
        rm -f /tmp/error_stat_$Slot
        CumulativeStatus=`/usr/bin/expr $CumulativeStatus + 1`
      fi
      if [ "`/sbin/bootenv | /bin/grep BadRootDev`" != "" ]
      then
        $LogCmd $LogFile "Found BadRootDev in bootenv"
      fi    
    fi

    #
    # Get the user port list. This MUST be after the
    # diagClearError on the first run.
    #
    _cmd=`commandPath exec_diag`
    export UserPorts=`getUserPortList $Slot -split`

    # If we have not executed a command yet, then post
    # start message
    if [ $RunNumber -eq 1 -a $CmdNumber -eq 1 ]
    then
      export CmdNumber=`/usr/bin/expr $NumberOfCommands + 1`
      _message="Starting run  $_date $_serial"
      # Remove double spaces in the message for the forceError command
      _message=`/bin/echo "$_message" | /usr/bin/tr -s " " " "`
      _cmd=`commandPath exec_diag`
      if [ $MultiBlade = TRUE ]
      then
        $_cmd forceError --slot $Slot -severity 4 -message '"'" $Slot $MyName: $_message"'"'
      else
        $_cmd forceError --slot $Slot -severity 4 -message '"'" $MyName: $_message"'"'
      fi
      burninMessage "Starting run `/bin/date` on Serial number $_serial"
      if [ "$label" != "-" ]
      then
        burninMessage "Label $label"
      fi
    fi
    # ensure log mode is correct for both the CP and blade
    _cmd=`commandPath burninLogMode`
    if [ $MultiBlade = TRUE ]
    then
      $_cmd -slot $_cp_slot -mode FIRST_IN
    fi
    $_cmd -slot $Slot -mode FIRST_IN
    saveBladeParams $Slot
    do_force_slave $frcslv_on
}

##################################
# NAME
#    initializePerRunVariables - initializes the variables
#                                active per burnin run
#
# SYNOPSIS
#    initializePerRunVariables
#
# DESCRIPTION
#    Initializes the variables used to control the per run loop
#    activity, bump run counter, initialize the command counter,
#    and run status to pass.
#
# OPERANDS
#    NONE
##################################
initializePerRunVariables()
{
  if [ $CmdNumber -gt $NumberOfCommands ]
  then
    export RunStatus=0
    export CmdNumber=1
    export RunTime=`/bin/date \+\%s`
    saveBladeParams $Slot
  fi

  do_all_tests
  
  do_bplb_mode $bplb_on

  burninMessage "Begin run $RunNumber of $NumberOfRuns at command $CmdNumber `/bin/date` `get_stats`"
}

##################################
# NAME
#    isACommand - Sorts the command lines from a command entry
#
# SYNOPSIS
#    isACommand
#
# DESCRIPTION
#    This function isACommand() determines if the line in the 
#    $CommandList is an executable, or a comment or other entry. 
#    It assumes that blank lines and lines that start with "#" are 
#    comments or non-executible entries. All other lines are 
#    considered a command.
#
# OPERANDS
#    NONE
##################################
isACommand()
{
  if [ "$*" -a -z "`/bin/echo $* | /bin/grep '#'`" ]
  then
    /bin/echo command
  else
    /bin/echo "other"
  fi
}

##################################
# NAME
#    runBurninCommand - executes the commands from a $CommandList variable
#
# SYNOPSIS
#    runBurninCommand enable command argument ...
#
# DESCRIPTION
# This function runBurninCommand() processes the argument string as a command,
# it updates the command number, and updates the status.
#
# OPERANDS
#  $1 enable  - If the command is to be run
#  $2 command - The command name to run
#  $*         - The command name to run with all its arguments
#
##################################
runBurninCommand()
{
  isSolo=`/fabos/cliexec/config get flow.ioanalytics 2`
  _skip=0

  # get the command from the list, and get the relavent parts
  _command=`/bin/echo $CommandList | /usr/bin/cut -d"@" -f$CmdNumber`
  _command_name=`/bin/echo $_command | /usr/bin/cut -d" " -f2`
  _command_args=`/bin/echo $_command | /usr/bin/cut -d" " -f3-`
   _ports=`/bin/echo $_command_args | /bin/grep -w "UserPorts"`
  _ALL=FALSE
  if { [ "$_command_name" = "spinsilk" ] \
      || [ "$_command_name" = "backport" ] \
      || [ "$_command_name" = "spinSilk" ] \
      || [ "$_command_name" = "backPort" ] ; }
  then
    if [ "$_ports" = "" ]
    then
        _ALL=TRUE
    fi
  fi
  _cmd_time=`/bin/date \+\%s`
  _var=`eval /bin/echo $_command_name $_command_args`
  _new_var=`eval /bin/echo $_var`
  _enable=`/bin/echo $_command | /usr/bin/cut -d" " -f1`
  _enable=`eval /bin/echo $_enable`
  _val_enable=`eval /bin/echo $_enable`

  for retry in 1 2 3 4 5 ;
  do 
    bladeID=`getBladeID $Slot`
    if { [ "$bladeID" != "UNKNOWN" ] ; }
    then
        break
    fi
    burninMessage "getBladeID Slot $Slot Blade $bladeID retry $retry"
  done

  if { [ "$bladeID" = "GRAPHITE" ] || [ "$bladeID" = "CARBON" ] || [ "$bladeID" = "REDBIRD" ] || [ "$bladeID" = "ELARA" ] || [ "$bladeID" = "EUROPA" ] || [ "$bladeID" = "NESO" ] || [ "$bladeID" = "GALATEA" ] || [ "$bladeID" = "CHARON" ] || [ "$bladeID" = "THALASSA" ] || [ "$bladeID" = "STINGER" ] \
        || [ "$bladeID" = "PHAROS" ] || [ "$bladeID" = "PHAROS_LITE" ] || [ "$bladeID" = "GALATEA8G" ] || [ "$bladeID" = "THALASSA8G" ] || [ "$bladeID" = "WINDU" ] ||  [ "$bladeID" = "TOMTOO" ] || [ "$bladeID" = "ODIN" ] || [ "$bladeID" = "BULOVA2" ] || [ "$bladeID" = "SUPERHAWK3" ] || [ "$bladeID" = "KESTREL3" ] || [ "$bladeID" = "FALCON3" ] || [ "$bladeID" = "SKYBOLT" ]  || [ "$bladeID" = "SHENLONG" ] || [ "$bladeID" = "TIANLONG" ] ; }
  then
  	_exec_diag=`commandPath exec_diag2`
  else
  	_exec_diag=`commandPath exec_diag`
  fi

  if [ "$_command_name" = "turboramtest" ]   
  then
    bladeID=`getBladeID $Slot`
    if { [ "$bladeID" = "MARATHON" ] || [ "$bladeID" = "SPRINT" ] ; }
    then
	revNum=`getHWversion $Slot`
	if { [ "$revNum" = "01" ] || [ "$revNum" = "02" ] ; }
	then
    	   _val_enable=0
    	fi    
    fi      
  fi
 
#Block fcippathtest for Solo
  if [ "$isSolo" = "1" ]
  then
    if [ "$_command_name" = "fcippathtest" ]
    then
      _val_enable=0
      _skip=1
    fi
  fi
 
  if [ "$_val_enable" = "0" ]
  then
    if [ "$portlogdump_on" = 1 ]
    then
      portlogclear
    fi
    if [ "$_skip" = "0" ]
    then 
      burninMessage "Command #$CmdNumber Run $DIAG_PKG_PASS - Skip $_new_var `/bin/date` `get_stats`"
    fi
  else
    shift
    burninMessage "Command #$CmdNumber Run $DIAG_PKG_PASS - Run $_new_var `/bin/date` `get_stats`"
    $_exec_diag $_new_var 2>&1 >> $LogFile &
    check_command_status $_command_name $_cmd_time $_ALL
  fi

  # Increment the number of completed commands
  # command index is already CmdNumber + 1
  CmdNumber=`/usr/bin/expr $CmdNumber + 1`
  TotalCmdNumber=`/usr/bin/expr $TotalCmdNumber + 1`
  if [ $CmdNumber -gt $NumberOfCommands ]
  then
    RunNumber=`/usr/bin/expr $RunNumber + 1`
    # Set for the diag to use in logging
    export DIAG_PKG_PASS=$RunNumber
  fi
  truncate_log

  # Flush the data to flash
  /bin/sync

  saveBladeParams $Slot
}

##################################
# NAME
#    burninStatusUpdate - Updates the global variables per burnin run
#
# SYNOPSIS
#    burninStatusUpdate
#
# DESCRIPTION
#    This function burninStateUpdate()handles the status updating 
#    for a burnin script it modifies the CumulativeStatus based
#    on the RunStatus stored in the serial EEPROM of the blade.
#
#    Closing messages are output if this was the last run of burnin, 
#    and the results for this run are stored in the serial EEPROM
#
# OPERANDS
#    NONE
##################################
burninStatusUpdate()
{
  runnum=`getBladeParam $Slot RUN_NUMBER`
  runnum=`/usr/bin/expr $runnum - 1`
  RunStatus=`getBladeParam $Slot RUN_STATUS`
  TotalCmdNumber=`getBladeParam $Slot TOTAL_CMD_NUMBER`
  _current_time=`/bin/date \+\%s`
  _duration=`/usr/bin/expr $_current_time - $RunTime`
  _minute=`/usr/bin/expr $_duration / 60`
  _hour=`/usr/bin/expr $_minute / 60`
  _sec=`/usr/bin/expr $_duration % 60`
  _minute=`/usr/bin/expr $_minute % 60`

  TotalThermal=`/usr/bin/expr $TotalThermal + $Thermal`
  TotalVib=`/usr/bin/expr $TotalVib + $Vib`

  # get existance of any driver errors
  _driver_stat=0
  get_non_diag_errors before_inc
  if [ -f /tmp/non_diag_stat_$Slot ]
  then
    rm -f /tmp/non_diag_stat_$Slot
    _driver_stat=1
  fi
  if [ $RunStatus -eq 0 -a $_driver_stat -eq 0 ]
  then
    _message=PASSED
  else
    _message=FAILED
    CumulativeStatus=`/usr/bin/expr $CumulativeStatus + 1`
    eval $_cmd bogus_test_to_set_led --slot $Slot --setled $LED_DIAG_FAIL > /dev/null 2>/dev/null
    burninMessage "Found error during run $runnum RunStatus $RunStatus driver_stat $_driver_stat"
  fi
  burninMessage "END RUN $runnum of $NumberOfRuns $_message `/bin/date` Thermal $TotalThermal Vib $TotalVib took $_hour hr $_minute min $_sec sec ($_hour:$_minute:$_sec)"
  #
  # done after message so previous message will be correct
  #
  /bin/sync
}

##################################
# NAME
#    cleanupOnExit - Cleans all temporary files at termination of script
#
# SYNOPSIS
#    cleanupOnExit
#
# DESCRIPTION
#    Removes any working files created by the script, and calls cleanup
#    routine in the main script (my_local_cleanup())
# 
# OPERANDS
#    NONE
##################################
cleanupOnExit()
{
  #
  # Save time data for ending summary
  #
  _run_number=`/usr/bin/expr $RunNumber - 1`
  export DIAG_PKG_PASS=$_run_number
  _current_time=`/bin/date \+\%s`
  _duration=`/usr/bin/expr $_current_time - $StartTime`
  _minute=`/usr/bin/expr $_duration / 60`
  _hour=`/usr/bin/expr $_minute / 60`
  _sec=`/usr/bin/expr $_duration % 60`
  _minute=`/usr/bin/expr $_minute % 60`

  saveBladeParams $Slot

  #
  # When all are done, determine status from out testing only if
  # we are still passing. No need to get status if we are already failing
  #
  if [ $CumulativeStatus -eq 0 ]
  then
    #
    # When all are done, determine final status
    # Get status before we start to wait for the other blades to complete
    #
    if [ "$NumberOfCommands" != 0 ]
    then
      _cmd=`commandPath exec_diag`
      $_cmd diagshow --slot $Slot -silent 1 -use_bports 1  >> $LogFile
      _showresult=$?
      if [ $_showresult = 237 -o $_showresult = 139 ]
      then
        burninMessage "Known issue diagshow after run complete when cleaning up. showresult $_showresult"
        _showresult=0
      fi
    else
      _showresult=0
    fi

    # get existance of any driver errors
    _driver_stat=0
    get_non_diag_errors after_inc
    if [ -f /tmp/non_diag_stat_$Slot ]
    then
      rm -f /tmp/non_diag_stat_$Slot
      _driver_stat=1
    fi
    _showresult=`/usr/bin/expr $_showresult + $_driver_stat`
    # If we have failed (ever), lite the light and
    # adjust status
    if [ $_showresult -ne 0 ]
    then
      CumulativeStatus=`/usr/bin/expr $CumulativeStatus + 1`
      # --setled only takes effect if the command fails.
      # net result is turn on the LED since test
      # will always fail
      _cmd=`commandPath exec_diag`
      eval $_cmd bogus_test_to_set_led --slot $Slot --setled $LED_DIAG_FAIL > /dev/null 2>/dev/null
      burninMessage "Found error after run complete when cleaning up. showresult $_showresult"
    fi

    #
    # wait for all active burnins to complete to set final status
    #
    #
    # When all are done, determine final status if we are still passing.
    # No need to get status if we are already failing
    #
    if [ $CumulativeStatus -eq 0 ]
    then
      _some_active=TRUE
      while [ $_some_active = TRUE ]
      do
        _some_active=FALSE
        for _slot in `getAvailSlots -chassisnofault`
        do
          _state=`getBladeParam $_slot STATE`
          _pid=`getBladeParam $_slot PID`
	  if [ "$_pid" != invalid ]
	  then
            if [ "`/bin/ps -p $_pid | /bin/grep -w $_pid`" != "" ]
            then
              if [ "$_state" = ACTIVE ]
              then
#debug	        /bin/echo Slot $Slot waiting for activity to end found slot $_slot in state $_state on PID $_pid
                _some_active=TRUE
              fi
            fi
          fi
        done
        if [ "$_some_active" = "TRUE" ]
        then
          /bin/sleep 10
        else
          #
          # When all are done, determine final status
          # Get status one last time before exiting to
          # allow any ALL test to complete
          #
	  if [ "$NumberOfCommands" != 0 ]
	  then
            _cmd=`commandPath exec_diag`
            $_cmd diagshow --slot $Slot -silent 1 -use_bports 1 >> $LogFile
            _showresult=$?
            if [ $_showresult = 237 -o $_showresult = 139 ]
            then
              burninMessage "Known issue diagshow after all blades complete their run when cleaning up. showresult $_showresult"
              _showresult=0
	    fi
	  else
	    _showresult=0
          fi

          # get existance of any driver errors
          _driver_stat=0
          get_non_diag_errors after_inc
          if [ -f /tmp/non_diag_stat_$Slot ]
          then
            rm -f /tmp/non_diag_stat_$Slot
            _driver_stat=1
          fi
          _showresult=`/usr/bin/expr $_showresult + $_driver_stat`
          # If we have failed (ever), lite the light and
          # adjust status
          if [ $_showresult -ne 0 ]
          then
            CumulativeStatus=`/usr/bin/expr $CumulativeStatus + 1`
            # --setled only takes effect if the command fails.
            # net result is turn on the LED since test
            # will always fail
            _cmd=`commandPath exec_diag`
            eval $_cmd bogus_test_to_set_led --slot $Slot --setled $LED_DIAG_FAIL > /dev/null 2>/dev/null
            burninMessage "Found error after all blades complete their run when cleaning up. showresult $_showresult"
          fi
        fi
      done
    fi
  fi

  #
  # Save final data to blade storage
  saveBladeParams $Slot
  #
  # Set exit status now that we are done
  #
  if [ $CumulativeStatus -eq 0 ]
  then
    _cum_state=PASSED
  else
    _cum_state=FAILED
  fi

  #
  # Output a ending summary
  #
  _message="$State stat $_cum_state $TotalCmdNumber cmds in $_run_number runs Therm $TotalThermal Vib $TotalVib in $_hour hr $_minute min $_sec sec ($_hour:$_minute:$_sec)"
  # Remove double spaces in the message for the forceError command
  _message=`/bin/echo "$_message" | /usr/bin/tr -s " " " "`
  _cmd=`commandPath exec_diag`
  if [ $MultiBlade = TRUE ]
  then
    $_cmd forceError --slot $Slot -severity 4 -message '"'" $Slot $MyName: $_message"'"'
  else
    $_cmd forceError --slot $Slot -severity 4 -message '"'" $MyName: $_message"'"'
  fi
  burninMessage "$_message"
  if [ "$label" != "-" ]
  then
    burninMessage "Label $label"
  fi
  /bin/sync

  #
  # Indicate to others that we have completed logging activity
  #
  State=COMPLETE_$State
  if [ "$debug_on" -eq 1 ]
  then
    export debug_on=0
  fi
  saveBladeParams $Slot

  #
  # Turn off the burnin mode if we are last process running
  #
  _some_active=TRUE
  while [ $_some_active = TRUE ]
  do
    _some_active=FALSE
    for _slot in `getAvailSlots -chassisnofault`
    do
      _state=`getBladeParam $_slot STATE`
      _pid=`getBladeParam $_slot PID`
      if [ "$_pid" != invalid ]
      then
   	if [ "`/bin/ps -p $_pid | /bin/grep -w $_pid`" != "" ]
      	then
          if [ "`/bin/echo $_state | /bin/grep -e COMPLETE -e INITIALIZED`" = "" ]
          then
#debug	    /bin/echo Slot $Slot waiting for logging to end found slot $_slot in state $_state on PID $_pid
            _some_active=TRUE
          fi
        fi
      fi
    done
    if [ "$_some_active" = "TRUE" ]
    then
      /bin/sleep 1
    else
        burninSetLevel 0 > /dev/null
	burninMessage "Disabled burnin mode."
    fi
  done

  #
  # Restore LED control back to EM
  #
  _cmd=`commandPath exec_diag`
  if [ $MultiBlade = FALSE ]
  then
    _cmd=`commandPath switchbeacon`
#    $_cmd 1
    
  else
    case `getSWBD` in
    SWBD62)
      if [ $Slot != 6 -a $Slot != 7 ]
      then
        export FABOS_SWITCHNO=`getSwitchFromSlot $Slot`
#        _cmd=`commandPath bladebeacon`
#        $_cmd $Slot 1
      fi
      ;;

    SWBD77)
      if [ $Slot != 4 -a $Slot != 5 ]
      then
        export FABOS_SWITCHNO=`getSwitchFromSlot $Slot`
#        _cmd=`commandPath bladebeacon`
#        $_cmd $Slot 1
      fi
      ;;

    *)
      if [ $Slot != 5 -a $Slot != 6 ]
      then
        export FABOS_SWITCHNO=`getSwitchFromSlot $Slot`
#        _cmd=`commandPath bladebeacon`
#        $_cmd $Slot 1
      fi
      ;;
    esac
  fi
  #
  # Always restore LED control back to EM. the blade will either FAULT
  # and turn on the ATTN lite based on the SLOT_FAULT from diagd, or
  # the attn lite will be off as the blade transitions to SLOT_ON state.
  # These two LED conditions match the definition burnin final status for
  # all 4.x products.
  #
  _cmd=`commandPath exec_diag`
  eval $_cmd bogus_test_to_set_led --slot $Slot --setled $LED_DEFAULT > /dev/null 2>/dev/null &
  burninMessage "Burnin script exiting PID $_pid with status $CumulativeStatus"
  exit $CumulativeStatus
}

do_reference_clock()
{
  _cmd=`commandPath referenceclock`
  # Adjust reference clock to toggle every other run
  if [ $1 -eq 1 ]
  then
    if [ `/usr/bin/expr $RunNumber % 2` -eq 1 ]
    then
      burninMessage "BEFORE_RUN: Disabling the Reference System Clock"
      $_cmd OFF | /usr/bin/tee -a $LogFile
      /bin/sleep 1
    else
      burninMessage "BEFORE_RUN: Enabling the Reference System Clock"
      $_cmd ON | /usr/bin/tee -a $LogFile
      /bin/sleep 1
    fi
  fi
  src=`$_cmd | /usr/bin/tee -a $LogFile | /usr/bin/cut -d " " -f4`
  if [ ON = $src ]
  then
    ref_state=1
  else
    ref_state=0
  fi
  _cmd=`commandPath getPLLStatus`
  $_cmd -slot $Slot | /usr/bin/tee -a $LogFile
  export DIAG_PKG_STR="$ref_state$volt_state"
}

do_voltage_margin()
{
  # Adjust margining to cycle every three runs
  case $1 in
  "0" )
    volt_state=?
    burninMessage "BEFORE_RUN: Not setting margin";;

  "1" )
    _cmd=`commandPath voltagemargin`
    _index=`/usr/bin/expr $RunNumber % 3`
    case $_index in
    "0" ) $_cmd -margin HIGH    | /usr/bin/tee -a $LogFile
	  volt_state=H
	  burninMessage "BEFORE_RUN: Setting margin HIGH";;

    "1" ) $_cmd -margin NOMINAL | /usr/bin/tee -a $LogFile
	  volt_state=N
	  burninMessage "BEFORE_RUN: Setting margin NOMINAL";;

    "2" ) $_cmd -margin LOW     | /usr/bin/tee -a $LogFile
	  volt_state=L
	  burninMessage "BEFORE_RUN: Setting margin LOW";;

    * )	  volt_state=?
	  burninMessage "BEFORE_RUN: Setting margin UNKNOWN $_index";;
    esac;;

  "2" )
    _cmd=`commandPath voltagemargin`
    $_cmd -margin HIGH | /usr/bin/tee -a $LogFile
    volt_state=H
    burninMessage "BEFORE_RUN: Setting margin HIGH";;

  "3" )
    _cmd=`commandPath voltagemargin`
    $_cmd -margin LOW | /usr/bin/tee -a $LogFile
    volt_state=L
    burninMessage "BEFORE_RUN: Setting margin LOW";;

  "4" )
    _cmd=`commandPath voltagemargin`
    $_cmd -margin NOMINAL | /usr/bin/tee -a $LogFile
    volt_state=N
    burninMessage "BEFORE_RUN: Setting margin NOMINAL";;
  esac
  export DIAG_PKG_STR="$ref_state$volt_state"
}

apply_min_lb_mode()
{
  if [ $1 -gt 5 ]
  then
    if [ $1 -lt $MinLbMode2 ]
    then
      shift
      /bin/echo $MinLbMode2
    else
      /bin/echo $1
    fi
  else
    if [ $1 -lt $MinLbMode ]
    then
      shift
      /bin/echo $MinLbMode
    else
      /bin/echo $1
    fi
  fi
}

do_force_slave()
{
  if [ $frcslv_on -eq 1 ]
  then
    frcslv_timeout=50
    while [ $frcslv_timeout -gt 0 ]
    do
      _cmd=`commandPath hashow`
      slave=`$_cmd | /bin/grep Remote | /bin/grep Standby`
      if [ "$slave" = "" ]
      then
        if [ $frcslv_timeout -eq 1 ]
        then
          burninMessage "BEFORE_RUN: No Standby CP found, Not Toggling CP on next reboot"
          break
        fi
        /bin/sleep 1
      else
        _cmd=`commandPath forceSlave`
        $_cmd enable | /usr/bin/tee -a $LogFile
        burninMessage "BEFORE_RUN: Toggling CP on next reboot"
        break;
      fi
      frcslv_timeout=`/usr/bin/expr $frcslv_timeout - 1`
    done
  fi
}

#######################
# $1 all test value
# $2 not all test name
#######################
check_all_tests()
{
  if [ $MultiBlade = TRUE ]
  then
    # Adjust for the system level tests to run when there is a slot match
    _my_slots=`getAvailSlots -switchnofault`
    _num_slots=`/bin/echo "$_my_slots" | \
	/usr/bin/wc -w | \
	/bin/sed "s/ //g"`
    _my_run=`/usr/bin/expr $RunNumber - 1`
    _my_run=`/usr/bin/expr $_my_run % $_num_slots`
    # get modulo number_of_slots of the slot
    _my_position=0
    for pos in $_my_slots
    do
      if [ "$Slot" = "$pos" ]
      then
        break
      fi
      _my_position=`/usr/bin/expr $_my_position + 1`
    done
    if [ $_my_run -eq $_my_position ]
    then
      /bin/echo $1
    else
      /bin/echo $2
    fi
  else
    /bin/echo $1
  fi
}

do_all_tests()
{
  _param_list=`get_param_list`
  export _num_params=`/bin/echo $_param_list | \
         /usr/bin/tr -s " " "_" | \
         /usr/bin/tr -s "@" " " | \
         /usr/bin/wc -w | \
	 /bin/sed "s/ //g"`
  config_list=`get_config_list`
  _num=1
  while [ $_num -le $_num_params ]
  do
    _param=`/bin/echo $_param_list | /usr/bin/cut -d"@" -f$_num`
    _flag=`/bin/echo $_param | /usr/bin/cut -d" " -f1`
    _var_name=`/bin/echo $_param | /usr/bin/cut -d" " -f2`
    if [ "`/bin/echo $_flag | /bin/grep A`" != "" ]
    then
      # get database value
      _dflt_val=`/bin/echo $_param | /usr/bin/cut -d" " -f3`
      _mode_val=`/bin/echo $_param | /usr/bin/cut -d" " -f4`
      _cfg_val="`get_config_entry $_var_name`"
      if [ -z "$_cfg_val" ]
      then
        _cfg_val=$_dflt_val
        setConfig diag.$MyName.$_var_name $_mode_val "$_dflt_val"
      fi
      export `eval /bin/echo $_var_name`="`eval /bin/echo $_cfg_val`"

      # get alternative value if not all test
      val=`get_flag_val A "$_flag"`
      new_val=`check_all_tests $_cfg_val $val`
      export `eval /bin/echo $_var_name`=$new_val
      burninMessage "BEFORE_RUN: Setting $_var_name system level test to $new_val"
      /bin/rm -f /tmp/$$.val
    fi
    _num=`/usr/bin/expr $_num + 1`
  done
}
process_bplb_list()
{
  _param_list=`get_param_list`
  export _num_params=`/bin/echo $_param_list | \
         /usr/bin/tr -s " " "_" | \
         /usr/bin/tr -s "@" " " | \
         /usr/bin/wc -w | \
	 /bin/sed "s/ //g"`
  _num=1
  while [ $_num -le $_num_params ]
  do
    _param=`/bin/echo $_param_list | /usr/bin/cut -d"@" -f$_num`
    _flag=`/bin/echo $_param | /usr/bin/cut -d" " -f1`
    _var_name=`/bin/echo $_param | /usr/bin/cut -d" " -f2`
    if [ "`/bin/echo $_flag | /bin/grep B`" != "" ]
    then
      # get alternative vbalue if not all test
      val=`get_flag_val B "$_flag"`
      eval /bin/echo $`/bin/echo $_var_name` > /tmp/$$.val
      cur_val=`/bin/cat /tmp/$$.val`
      export `eval /bin/echo $_var_name`=$val
      burninMessage "BEFORE_RUN: backplane loopback mode active adjusting $_var_name to $val."
      /bin/rm -f /tmp/$$.val
    fi
    _num=`/usr/bin/expr $_num + 1`
  done
  _param_list=`get_paramconst_list`
  export _num_params=`/bin/echo $_param_list | \
         /usr/bin/tr -s " " "_" | \
         /usr/bin/tr -s "@" " " | \
         /usr/bin/wc -w | \
	 /bin/sed "s/ //g"`
  _num=1
  while [ $_num -le $_num_params ]
  do
    _param=`/bin/echo $_param_list | /usr/bin/cut -d"@" -f$_num`
    _flag=`/bin/echo $_param | /usr/bin/cut -d" " -f1`
    _var_name=`/bin/echo $_param | /usr/bin/cut -d" " -f2`
    if [ "`/bin/echo $_flag | /bin/grep B`" != "" ]
    then
      # get alternative vbalue if not all test
      val=`get_flag_val B "$_flag"`
      eval /bin/echo $`/bin/echo $_var_name` > /tmp/$$.val
      cur_val=`/bin/cat /tmp/$$.val`
      export `eval /bin/echo $_var_name`=$val
      burninMessage "BEFORE_RUN: backplane loopback mode active adjusting $_var_name to $val."
      /bin/rm -f /tmp/$$.val
    fi
    _num=`/usr/bin/expr $_num + 1`
  done
}
do_bplb_mode()
{
  # Ensure that the config database and teh PARAMDEF match, 
  # then adjust parameters if the mode is on.
  #
  bplb_mode=`getConfig diag.mode.bplb $INTEGER 0`
  if [ "$bplb_mode" = "$1" ]
  then
    if [ "$bplb_mode" != "0" ]
    then
      process_bplb_list 
    fi
  else
    burninMessage "BEFORE_RUN: backplane loopback mode mismatch script is $bplb_on and configuration is $bplb_mode."
    export State=FAILED
    cleanupOnExit
    exit 1
  fi
}

get_flag_val()
{ 
  for pair in `/bin/echo "$2" | /bin/sed "s/,/ /g"`
  do
    if [ "`/bin/echo $pair | /bin/grep $1`" != "" ]
    then
      /bin/echo $pair | /usr/bin/cut -d":" -f2
      break
    fi
  done
}

do_bisr_adjust()
{
  _param_list=`get_param_list`
  export _num_params=`/bin/echo $_param_list | \
         /usr/bin/tr -s " " "_" | \
         /usr/bin/tr -s "@" " " | \
         /usr/bin/wc -w | \
	 /bin/sed "s/ //g"`
  config_list=`get_config_list`
  _num=1
  while [ $_num -le $_num_params ]
  do
    _param=`/bin/echo $_param_list | /usr/bin/cut -d"@" -f$_num`
    _flag=`/bin/echo $_param | /usr/bin/cut -d" " -f1`
    _var_name=`/bin/echo $_param | /usr/bin/cut -d" " -f2`
    if [ "`/bin/echo $_flag | /bin/grep Z`" != "" ]
    then
      val=`get_flag_val Z "$_flag"`
      # save current value of named parameter
      eval /bin/echo $`/bin/echo $_var_name` > /tmp/$$.val
      # get current value in local variable
      cur_val=`/bin/cat /tmp/$$.val`
      # set named variable to new value
      export `eval /bin/echo $_var_name`=$val
      # save new value of named variable
      eval /bin/echo $`/bin/echo $_var_name` > /tmp/$$.val
      burninMessage "BEFORE_RUN: Adjusting the $bisr_message $_var_name from $cur_val to `/bin/cat /tmp/$$.val`"
      /bin/rm -f /tmp/$$.val
    fi
    _num=`/usr/bin/expr $_num + 1`
  done
}

do_lb_mode()
{
  _param_list=`get_paramconst_list`
  export _num_params=`/bin/echo $_param_list | \
         /usr/bin/tr -s " " "_" | \
         /usr/bin/tr -s "@" " " | \
         /usr/bin/wc -w | \
	 /bin/sed "s/ //g"`
  config_list=`get_config_list`
  _num=1
  while [ $_num -le $_num_params ]
  do
    _param=`/bin/echo $_param_list | /usr/bin/cut -d"@" -f$_num`
    _flag=`/bin/echo $_param | /usr/bin/cut -d" " -f1`
    _var_name=`/bin/echo $_param | /usr/bin/cut -d" " -f2`
    if [ "`/bin/echo $_flag | /bin/grep M`" != "" ]
    then
      val=`/bin/echo $_flag | \
        /bin/sed -e "s/^.*\(M:[[:print:]]\+\).*[,	]/\1/g" |\
        /usr/bin/cut -d":" -f2`
      eval /bin/echo $`/bin/echo $_var_name` > /tmp/$$.val
      cur_val=`/bin/cat /tmp/$$.val`
      export `eval /bin/echo $_var_name`="`apply_min_lb_mode $cur_val`"
      eval /bin/echo $`/bin/echo $_var_name` > /tmp/$$.val
      if [ $cur_val != `/bin/cat /tmp/$$.val` ]
      then
        burninMessage "BEFORE_RUN: Limiting lb_mode $_var_name from $cur_val to `/bin/cat /tmp/$$.val`"
      fi
      /bin/rm -f /tmp/$$.val
    fi
    _num=`/usr/bin/expr $_num + 1`
  done
}

##################################
# Example functions to demonstrate ability to modify things 
# at two critical places in the activity:
#
# 1. beginning of a run
# 2. end of a run
#
# At both places, environment variable can be used
# (read or write) in the context of the function.
#
# Since the PARAMDEF's are saved to the environment, they are
# also available to the functions. These functions can call
# the xtool scripts, or other commands and functions in the script.
##################################
check_command_results()
{
  _testresult=$?
  if [ $_testresult -eq 139 -o $_testresult -eq 237 ]
  then
    burninMessage "Command #$CmdNumber Run $DIAG_PKG_PASS Known issue ($_testresult) every_test_$bisr_message"
    _testresult=16
  fi
  if [ $_testresult -eq 0 ]
  then
    _stat=PASSED
  else
    skipped_abort=`/usr/bin/expr $_testresult % 32`
    skipped_abort=`/usr/bin/expr $skipped_abort / 16`
    skipped_abort=`/usr/bin/expr $skipped_abort \* 16`
    case "$_testresult" in
    "$skipped_abort")
      _stat=SKIPPED;;
    *)
      _stat=FAILED;;
    esac
  fi
  if [ "$_stat" = "FAILED" ]
    then
      CumulativeStatus=`/usr/bin/expr $CumulativeStatus + 1`
      RunStatus=1
      # --setled only takes effect if the command fails.
      # net result is turn on the LED since test
      # will always fail
      _cmd=`commandPath exec_diag`
      eval $_cmd bogus_test_to_set_led --slot $Slot --setled $LED_DIAG_FAIL > /dev/null 2>/dev/null
      burninMessage "Found error in every test $bisr_message during run $RunNumber testresult $_testresult"
    fi
  burninMessage "Command #$CmdNumber Run $DIAG_PKG_PASS $_stat every_test_$bisr_message `/bin/date` `get_stats`"
  _current_time=`/bin/date \+\%s`
  _duration=`/usr/bin/expr $_current_time - $1`
  _minute=`/usr/bin/expr $_duration / 60`
  _hour=`/usr/bin/expr $_minute / 60`
  _sec=`/usr/bin/expr $_duration % 60`
  _minute=`/usr/bin/expr $_minute % 60`
  burninMessage "Command #$CmdNumber Run $DIAG_PKG_PASS Duration: every_test_$bisr_message took $_hour hr $_minute min $_sec sec ($_hour:$_minute:$_sec)"
}

isBISRBlade()
{
  slot=$1
  chassisshow > /tmp/chassisshow.$slot
  /bin/grep -n "SW BLADE  Slot:" /tmp/chassisshow.$slot > /tmp/lines.$slot
  if [ -s /tmp/lines.$slot ]
  then
    start_pos=`/bin/cat /tmp/lines.$slot | /usr/bin/cut -d" " -f2- | /bin/grep -n -w $slot | /usr/bin/cut -d":" -f1`
    if [ -n "$start_pos" ]
    then
      start_line=`/usr/bin/tail -n +$start_pos /tmp/lines.$slot | /usr/bin/head -1 | /usr/bin/cut -d":" -f1`
      /usr/bin/tail -n +$start_line /tmp/chassisshow.$slot | /usr/bin/head -12 > /tmp/segment.$slot
      if [ "`/bin/grep ID /tmp/segment.$slot | /usr/bin/tr -s '	   ' '  ' | /usr/bin/cut -d' ' -f2 | /bin/grep -i BISR`" = "" ]
      then
        /bin/echo FALSE
      else
        /bin/echo TRUE
      fi
    else
      /bin/echo FALSE
    fi
  else
    /bin/echo FALSE
  fi
  /bin/rm -f /tmp/chassisshow.$slot /tmp/segment.$slot /tmp/lines.$slot
}

BEFORE_RUN()
{
  # Setup for portlogdumps
  if [ "$portlogdump_on" = 1 ]
  then
    portlogtypeenable 23
    _cmd=`commandPath setdbg`
    $_cmd BLOOM 4
    $_cmd INTR 4
    $_cmd SPEED 4
  fi

  if [ $QUAL_AVAILABLE = TRUE ]
  then
    perform_qual
  fi

  # This code makes the script get the diag semaphore before doing voltage margining
  # It calls the new test method diagsemaget which will grab the diag semaphore and hold
  # it for 10 seconds. Once we have the semaphore, we will do the voltage margin command.
  # We know we have the semaphore by polling the diagstatus command. When it returns that
  # diagsemaget is running, we know we have the semaphore and it is safe to run voltagemargin
  # We give diagsemaget up to 42 minutes to get the semaphore. If it can not get it in
  # that timeout, we move on anyway.
  if [ "$margin_on" -ne 0 ]
  then
     _cmd=`commandPath exec_diag`
     burninMessage "BEFORE_RUN: Taking Diag semaphore before setting voltage margin"
     (`$_cmd diagsemaget -timeout 10 --slot $Slot` > /dev/null 2>&1) &
     cur_diag=`$_cmd diagstatus $Slot | sed '1,3d' | sed '2d' | tr -d '"' | cut -d' ' -f3`
     trytotal=0
     while [  "$cur_diag" != "diagsemaget" ]
     do
        cur_diag=`$_cmd diagstatus $Slot | sed '1,3d' | sed '2d' | tr -d '"' | cut -d' ' -f3`
    	trytotal=`/usr/bin/expr $trytotal + 1`
    	if [ "$trytotal" -gt 700 ]
    	then
	   burninMessage "BEFORE_RUN: Timeout waiting for diagsemaget to start"
	   break
    	fi
    	sleep 5
     done
  fi

  bladeType=`getBladeID $Slot`

  if { [ "$bladeType" != MARATHON ] && [ "$bladeType" != SPRINT ] &&
	   [ "$bladeType" != IRONMAN ] && [ "$bladeType" != VIKING ] &&
	   [ "$bladeType" != SCIMITAR ] && [ "$bladeType" != SABRE ]; }
  then
  	do_voltage_margin $margin_on
  	do_reference_clock $refclk_on
  fi
  
#  moved to checkBurninState to avoid power cycles during BEFORE_RUN
#  do_force_slave $frcslv_on

  do_lb_mode

  # Handle the BISR values
  if [ `isBISRBlade $Slot` = TRUE ]
  then
    do_bisr_adjust
  fi

}

AFTER_RUN()
{
  burninMessage "AFTER_RUN: run status: $RunStatus run `/usr/bin/expr $RunNumber - 1` cumulative $CumulativeStatus"
}

check_slots_runs_status()
{

# When any slot completes its RUN, it will wait for
# other slots to complete the same RUN. This will avoid BE Link issue in core blades
# when systemverification triggered with more than one RUN

  multiBlade=`isMultiBlade`
  if [ $multiBlade = TRUE ]
  then
       if [ "$NumberOfRuns" -gt 1 -a "$RunNumber" -le "$NumberOfRuns" ]
      then
        my_slots="`getAvailSlots -chassis`"
        for f in $my_slots
        do
          run_com=`getBladeParam $f RUN_NUMBER`
          run_com=`/usr/bin/expr $run_com - 1`
          r1=`/usr/bin/expr $RunNumber - 1`
          while [ $r1 != $run_com -a $f != $Slot ]
          do
            /bin/echo "Slot $f yet to complete RUN $r1, Slot $Slot waiting!!"
            sleep 10
            run_com=`getBladeParam $f RUN_NUMBER`
            run_com=`/usr/bin/expr $run_com - 1`
          done
        done
      fi
   fi
}

get_test_list()
{
  # get my name
  export debug_on=0

  get_filename

  # find which field contains our defaults
  name_found=0
  # Adjusted starting offset to compensate for the stripped
  # "N SCRIPTNAME" in name_list
  DefaultField=3
  ModeField=$DefaultField
  for word in $name_list
  do
    if [ "$word" = $MyName ]
    then
      name_found=1
    else
      if [ $name_found = 0 ]
      then
        DefaultField=`/usr/bin/expr $DefaultField + 1`
      fi
      ModeField=`/usr/bin/expr $ModeField + 1`
    fi
  done
  ModeField=`/usr/bin/expr $ModeField + 1`
  MinField=`/usr/bin/expr $ModeField + 1`
  MaxField=`/usr/bin/expr $MinField + 1`
  CommentField=`/usr/bin/expr $MaxField + 1`
  export DefaultOffset MinField MaxField CommentField
  ScriptName=$MyName
}

do_burnin_main_loop()
{
  #
  # get sys info for multi blade
  #
  multiBlade=`isMultiBlade`
  if [ $multiBlade = TRUE ]
  then
     export syntax="$0 -slot [slot]"
  else
     export syntax="$0"
  fi


  ##################################
  # Check if it is OK to begin the run ess
  ##################################
  checkBurninState $*

  ##################################
  # Set the burninStarted in-order to cleanup if Ctrl+C is pressed
  ##################################
  burninStarted=1

  ##################################
  #Limit number of runs to 1 for skybolt, 
  #since it needs to be rebooted after PLB lb_mode 8 and FCIPPATHTEST
  ##################################
  if [ `getSWBD` == SWBD148 ]
  then
     if [ $NumberOfRuns -ne 1 ]
     then
        /bin/echo "Brocade 7840 supports only one run for systemverification"
        /bin/echo "Setting number of run to 1"
        NumberOfRuns=1
     fi
  fi

  ##################################
  # MAIN PROCCESS LOOP for the commands
  ##################################
  if [ $NumberOfRuns -eq 0 ]
  then
    while [ 1 ]
    do

      ###################################
      # initialize run and indicate which pass we are beginning
      ###################################
      initializePerRunVariables

      BEFORE_RUN

      if [ $reset_every -eq 1 ]
      then
	_cmd_time=`/bin/date \+\%s`
	_cmd=`commandPath exec_diag`
    	burninMessage "Perform diagClearError `/bin/date` `get_stats`"
        $_cmd diagClearError $Slot >> $LogFile
      fi

      ###################################
      # Begin processing the command file
      ###################################

      while [ "$CmdNumber" -le "$NumberOfCommands" ]
      do

        runBurninCommand
	case `getSWBD` in
	SWBD10 | SWBD12 | SWBD22)
          if [ "$bisr_every" = 1 ]
          then
	    _cmd_time=`/bin/date \+\%s`
	    exec_diag stestcmbisr -passcnt $bisr_npass -maxbadrows $bisr_bad_row -redundant $bisr_red_row -skipconschk $bisr_no_consist  --gettemp 1 >> $LogFile
	    check_command_results $_cmd_time
          fi
	  ;;
	*)
          if [ "$bist_every" = 1 ]
          then
	    _cmd_time=`/bin/date \+\%s`
	    exec_diag stestcmbist -passcnt $bist_npass --gettemp 1 >> $LogFile
	    check_command_results $_cmd_time
          fi
	  ;;
	esac

        if [ $reset_every -eq 1 ]
        then
	  _cmd_time=`/bin/date \+\%s`
	  _cmd=`commandPath exec_diag`
    	  burninMessage "Perform diagClearError `/bin/date` `get_stats`"
          $_cmd diagClearError $Slot >> $LogFile
        fi

      done  
      ###################################
      # Update the status at the end of the pass
      ###################################
      burninStatusUpdate

      AFTER_RUN

      check_slots_runs_status
    done
  else
    while [ "$RunNumber" -le "$NumberOfRuns" ]
    do
      ###################################
      # initialize run and indicate which pass we are beginning
      ###################################
      initializePerRunVariables

      BEFORE_RUN

      if [ $reset_every -eq 1 ]
      then
	_cmd_time=`/bin/date \+\%s`
	_cmd=`commandPath exec_diag`
    	burninMessage "Perform diagClearError `/bin/date` `get_stats`"
        $_cmd diagClearError $Slot >> $LogFile
      fi

      ###################################
      # Begin processing the command file
      ###################################  

      if [ "$NumberOfCommands" = 0 ]
      then
        RunNumber=`/usr/bin/expr $RunNumber + 1`

        # Set for the diag to use in logging
        export DIAG_PKG_PASS=$RunNumber

	truncate_log

        # Flush the data to flash
        /bin/sync

	export CumulativeStatus=0
	export RunStatus=0
        saveBladeParams $Slot
      else
        while [ "$CmdNumber" -le "$NumberOfCommands" ]
        do
          runBurninCommand
  	  case `getSWBD` in
	  SWBD10 | SWBD12 | SWBD22)
            if [ "$bisr_every" = 1 ]
            then
              _cmd_time=`/bin/date \+\%s`
	      exec_diag stestcmbisr -passcnt $bisr_npass -maxbadrows $bisr_bad_row -redundant $bisr_red_row -skipconschk $bisr_no_consist  --gettemp 1 >> $LogFile
	      check_command_results $_cmd_time
            fi
	    ;;
	  *)
            if [ "$bist_every" = 1 ]
            then
	      _cmd_time=`/bin/date \+\%s`
	      exec_diag stestcmbist -passcnt $bist_npass --gettemp 1 >> $LogFile
	      check_command_results $_cmd_time
            fi
	    ;;
	  esac

          if [ $reset_every -eq 1 ]
          then
	    _cmd_time=`/bin/date \+\%s`
	    _cmd=`commandPath exec_diag`
    	    burninMessage "Perform diagClearError `/bin/date` `get_stats`"
            $_cmd diagClearError $Slot >> $LogFile
          fi

        done  
      fi

      ###################################
      # Update the status at the end of the pass
      ###################################
      burninStatusUpdate

      AFTER_RUN

      check_slots_runs_status

    done
  fi

  State=TESTED

  cleanupOnExit
}
##################################
# Main body of script
##################################
# Load common functions
# Should be first to ensure the library 
# functions are available for use
##################################
home="/fabos/share"
util="diagcommon.sh"
ok=0
for f in "./$util" "$FABOSHOME/share/$util" "$home/$util"
do
  if [ -r $f ]
  then
    . $f
    ok=1
    break;
  fi
done
if [ $ok -ne 1 ]
then
  err "Could not locate $util"
  exit 3
fi

# Clear the burninStarted just to avoid extra cleanup if Ctrl+C is pressed
export burninStarted=0

# get setup for quick exit
trap "" 2
trap doburnin_cleanup INT TERM

# load qualification file if available
if [ -f /fabos/share/`getSWBD`_doqual ]
then
  . /fabos/share/`getSWBD`_doqual
  QUAL_AVAILABLE=TRUE
  export QUAL_AVAILABLE
else
  QUAL_AVAILABLE=FALSE
fi

FileName=common_test_list
util=$FileName
ok=0
for f in "./$util" "$FABOSHOME/share/$util" "$home/$util"
do
  if [ -r $f ]
  then
    . $f
    name_list=`/bin/cat $f | /usr/bin/tr -s "	 " "  " | /bin/grep "N SCRIPTNAME" | /usr/bin/cut -d " " -f3-`
    ok=1
    break;
  fi
done
if [ $ok -ne 1 ]
then
  err "Could not locate $util"
  exit 3
fi
if [ "$name_list" = "" ]
then
  err "Could not locate script name list"
  exit 3
fi

case "$1" in
"-slot"  ) 
  if [ "`isValidSlot $2 -chassis`" = TRUE ]
  then
    export FABOS_SLOTNO=$2
  else
    # Workaround for intermittent issue with isValidSlot
    sleep 1
    if [ "`isValidSlot $2 -chassis`" = TRUE ]
    then
       	/bin/echo "Slot valid check GOOD on SECOND try"
       	export FABOS_SLOTNO=$2
    else
       	/bin/echo "`/fabos/link_bin/slotshow -d575`"
       	list=`getAvailSlots -chassis`
       	search=`/bin/echo $list | /bin/grep -w $2`
       	/bin/echo "Invalid slot $2, list $list, search $search"
       	/bin/echo "`/bin/basename $0` <-slot number>"
       	/bin/echo "slot number must be within: `getAvailSlots -chassis`"
    	saveBladeParams $2 STATE COMPLETE_ABORT
       	exit 1
    fi
  fi
  ;;
esac

##################################
# Load test and parameter list
##################################
get_test_list

##################################
# Start testing
##################################
do_burnin_main_loop $*
esac
