#!/bin/bash


# ****************************************************************************************  #
# autoCoreUpload - Shell Script for Automatic Core Upload during Manufacture                #
# ****************************************************************************************  #

# CHANGE REQUEST
# 
# DATE                AUTHOR           CR NUMBER      DESCRIPTION
# ----------          -------------    -------------  ---------------------------------------
# 15-May-2007         Rajesh G         Q01654779      Added LabLoad Changes for Core Overriding
# 19-April-2007       Vinay/Rajesh G   Q01619917      Updated the script to :
#                                                     a) Create core_var file if it doesn't exist.
#                                                     b) Upload core only if DAT version is greater than MSC version.  
# 02-Mar-2007         Vinay/Rajesh G   Q01567391      Modified the script so that it updates the core_var file
#                                                     with appropriate core variant instead of "Auto".
# 31-Aug-2006         Pintu Kumar      Q01447279      Added retry cases for FastUpld failure case and 
#                                                     invoking reboot if mfg.mfg file is present.
# 23-Aug-2006         Vinay. S         Q01443811      Commented the testforpid section for MscService due 
#                                                     to the problem faced in manufacturing. 
# 16-June-2006        Pintu Kumar      Q01394029      Raising Alarm for other failure cases.
#                                                     Attached 'date' on all output strings.
#                                                     Checked return value for testforpid.
#
# ########################################################################################### 


. /etc/rc.d/init.d/init_functions

confFile=/nn/etc/core_var

flag=0
VAR_TYPE="" 

testforpid autoCoreUpload

#RC=$?
#if [ ! $RC -eq 0 ]
#then
#   echo "`date +%c` - testforpid FAILED for autoCoreUpload....." >> /var/log/corestat.log
#   echo "autoCoreUpload cannot continue further......!!!!!!" >> /var/log/corestat.log
#   /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload FAILED....!"
#   exit 1
#fi

#*****************************************************************************
#PROCEDURE : createCoreVar
#ARGUMENTS : NONE.
#RETURN    : 0 - if /nn/etc/core_var file is created successfully.
#            1 - failed to create /nn/etc/core_var file.
#SYNOPSIS  : Creates the /nn/etc/core_var file and populate it with appropriate core variant.
#            Follows the below steps to determin the core variant,
#            1) Tries to determine the core version running on the MSC card.
#            2) If it fails then tries to determine using the log files (ds30star.log and oldds30s.log)
#            3) Identifies the core variant from the core version.
#            4) if it's unable to determine the core version then the core_var file is updated to "Auto"
#*****************************************************************************

createCoreVar()
{

local mscCoreVersion=""
local KSUver=""
local strKSU=""
local cvFlag=0
local notfound=0

echo >> /var/log/corestat.log

if [ -e /nn/sbin/getMSCVersion ]
then
   mscCoreVersion=`/nn/sbin/getMSCVersion`
else
   echo "`date +%c` - /nn/sbin/getMSCVersion .....missing!!!" >> /var/log/corestat.log
   /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - getMSCVersion is missing ....!"
   return 1
fi

if [ -e /nn/sbin/getDATVersion ]
then
   if [ -e /nn/sbin/edge_e1.dat ]
   then
      DAT_E1=`/nn/sbin/getDATVersion /nn/sbin/edge_e1.dat`
   else
      echo "`date +%c` - [createCoreVar] - Missing /nn/sbin/edge_e1.dat - Returning !!!" >> /var/log/corestat.log
      /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload edge_e1.dat missing...!"
      return 1
   fi
   if [ -e /nn/sbin/edge_e1gl.dat ]
   then
      DAT_E1GL=`/nn/sbin/getDATVersion /nn/sbin/edge_e1gl.dat`
   else
      echo "`date +%c` - [createCoreVar] - Missing /nn/sbin/edge_e1gl.dat - Returning !!!" >> /var/log/corestat.log
      /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload edge_e1g1.dat missing....!"
      return 1
   fi
   if [ -e /nn/sbin/edge_etq.dat ]
   then
      DAT_ETQ=`/nn/sbin/getDATVersion /nn/sbin/edge_etq.dat`
   else
      echo "`date +%c` - [createCoreVar] - Missing /nn/sbin/edge_etq.dat - Returning !!!" >> /var/log/corestat.log
      /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload edge_etq.dat missing....!"
      return 1
   fi
else
   echo "`date +%c` - [createCoreVar] - Missing /nn/sbin/getDATVersion - Returning !!!" >> /var/log/corestat.log
   /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload getDATVersion file missing....!"
   return 1
fi


if [ "$mscCoreVersion" = "" ]
then
   # case where MSC Service has never come up from the first reboot.
   # May be due to non-Functional of MSC card or BAD MSC card present on the system
   # In that case MSC service will never start and ds30star.log will never be created.
   if [ ! -e /var/log/ds30star.log ]
   then
      echo "`date +%c` - [createCoreVar] - /var/log/ds30star.log NOT PRESENT !!!" >> /var/log/corestat.log
      echo "VARIANT=Auto" > /nn/etc/core_var
      echo "`date +%c` - [createCoreVar] - Cannot determine the MSC version, defaulting to Auto" >> /var/log/corestat.log
      return 0
   fi

   # First try to get it from log file (ds30star.log) as far as possible
   # In case this file is rotated there could be a problem
   # Thus we need to compare the difference between the old and the new
   # For any case this line will output lines containing KSU load as string
   # Even though for the case if the mode of logging is changed we will be checking whether the previous string
   # contains the string "KSU load" which will be always preceeded by the KSU Version in any case
   if [ ! -e /var/log/oldds30s.log ]
   then
      strKSU=`grep -a 'KSU load' /var/log/ds30star.log | tail -n 1 | awk -F"," '{print $2}' | awk '{print $1$2}'`
   else
      strKSU=`diff -a /var/log/ds30star.log /var/log/oldds30s.log | grep -a '< *' | grep -a 'KSU load' | tail -n 1 | awk -F"," '{print $2}' | awk '{print $1$2}'`

      notfound=0
      if [ "$strKSU" = "" ]
      then
         strKSU=`grep -a 'KSU load' /var/log/ds30star.log | tail -n 1 | awk -F"," '{print $2}' | awk '{print $1$2}'`
         notfound=1
      fi
   fi
   if [ "$strKSU" = "KSUload" ]
   then
      if [ ! -e /var/log/oldds30s.log ]
      then
         KSUver=`grep -a 'KSU load' /var/log/ds30star.log | tail -n 1 | awk -F"," '{print $2}' | awk '{print $3}'`
      else
         if [ $notfound = 1 ]
         then
            KSUver=`grep -a 'KSU load' /var/log/ds30star.log | tail -n 1 | awk -F"," '{print $2}' | awk '{print $3}'`
         else
            KSUver=`diff -a /var/log/ds30star.log /var/log/oldds30s.log | grep -a '< *' | grep -a 'KSU load' | tail -n 1 | awk -F"," '{print $2}' | awk '{print $3}'`
         fi
      fi
      cvFlag=1
      echo "`date +%c` - [createCoreVar] - KSU load Version - $KSUver " >> /var/log/corestat.log
   else
      echo "VARIANT=Auto" > /nn/etc/core_var
      echo "`date +%c` - [createCoreVar] - Cannot determine the MSC version, defaulting to Auto" >> /var/log/corestat.log
      return 0
   fi
else
   cvFlag=1
   KSUver="$mscCoreVersion"
fi

if [ $cvFlag = 1 ]
then
   case "$KSUver" in
      "$DAT_E1")
         echo "VARIANT=E1" > /nn/etc/core_var
         echo "`date +%c` - [createCoreVar] - Creating core_var file with  <E1>....." >> /var/log/corestat.log
         ;;
      "$DAT_E1GL")
         echo "VARIANT=E1 Global" > /nn/etc/core_var
         echo "`date +%c` - [createCoreVar] - Creating core_var file with  <E1 Global>....." >> /var/log/corestat.log
         ;;
      "$DAT_ETQ")
         echo "VARIANT=Etiquette" > /nn/etc/core_var
         echo "`date +%c` - [createCoreVar] - Creating core_var with <Etiquette>....." >> /var/log/corestat.log
         ;;
      *)
          mscDescriptor=${KSUver:2:2}

          case "$mscDescriptor" in
             "Di" | "Dc" | "Dr" | "Dg" | "Da")
                echo "VARIANT=Etiquette" > /nn/etc/core_var
                echo "`date +%c` - [createCoreVar] - Updated core_var to <Etiquette> , descriptor matched was <$mscDescriptor>....." >> /var/log/corestat.log
                ;;
             "Dj" | "Dd" | "Ds")
                echo "VARIANT=E1" > /nn/etc/core_var
                echo "`date +%c` - [createCoreVar] - Updated core_var to <E1> , descriptor matched was <$mscDescriptor>....." >> /var/log/corestat.log
                ;;
             "Dk" | "De" | "Dt" | "Dh" | "Db")
                echo "VARIANT=E1 Global" > /nn/etc/core_var
                echo "`date +%c` - [createCoreVar] - Updated core_var to <E1 Global> , descriptor matched was <$mscDescriptor>....." >> /var/log/corestat.log
                ;;
             *)
                case "$KSUver" in
                   "lablod1")
                      echo "VARIANT=Etiquette" > /nn/etc/core_var
                      echo "`date +%c` - [createCoreVar] - Updated core_var to <Etiquette> , descriptor matched was <$KSUver>....." >> /var/log/corestat.log
                     ;;
                   "lablod2")
                      echo "VARIANT=E1" > /nn/etc/core_var
                      echo "`date +%c` - [createCoreVar] - Updated core_var to <E1> , descriptor matched was <$KSUver>....." >> /var/log/corestat.log
                     ;;
                   "lablod3")
                      echo "VARIANT=E1 Global" > /nn/etc/core_var
                      echo "`date +%c` - [createCoreVar] - Updated core_var to <E1 Global> , descriptor matched was <$KSUver>....." >> /var/log/corestat.log
                      ;;
                   *)
                      echo "VARIANT=Auto" > /nn/etc/core_var
                      echo "`date +%c` - [createCoreVar] - Unrecognized core software version, defaulting to Auto" >> /var/log/corestat.log
                      /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "createCoreVar - unrecognised core version - /nn/etc/core_var defaulted to Auto"
                      return 0
               	esac
          esac
   esac
fi

echo "`date +%c` - [createCoreVar] - Successfully created the core_var file......!!!" >> /var/log/corestat.log
echo >> /var/log/corestat.log
return 0
}

#*****************************************************************************
#PROCEDURE : versionCheck
#ARGUMENTS : arg-1: Core version running on MSC card.
#            arg-2: Core version present in DAT file. 
#RETURN    : 0 - if core version in DAT file is greater than MSC. Core upload required.
#            1 - if core version in DAT file is smaller than MSC. Core upload not required.
#SYNOPSIS  : Supports only BCM4.0 core versions (30Dxxxx).   
#*****************************************************************************
versionCheck()
{
local mscComm=""
local datComm=""
local mscProduct=""
local datProduct=""
local mscIssue=""
local datIssue=""
local mscVariant=""
local datVariant=""

local mscVersion="$1"
local datVersion="$2"

mscComm=${mscVersion:0:2}
datComm=${datVersion:0:2}
mscProduct=${mscVersion:2:1}
datProduct=${datVersion:2:1}
mscIssue=${mscVersion:4:3}
datIssue=${datVersion:4:3}
mscVariant=${mscVersion:3:1}
datVariant=${datVersion:3:1}

if [[ "lablod" = ${mscVersion:0:6} || "lablod" = ${datVersion:0:6} ]]
then
   echo "`date +%c` - [versionCheck] - Version mismatch  - MSCver : $mscVersion, DATver : $datVersion. Core upload required !" >> /var/log/corestat.log
   return 0
fi

if [[ "$datComm" != "30" || "$datProduct" != "D" ]]
then
   echo "`date +%c` - [versionCheck] - DAT file version is not supported on BCM4.0 - MSCver : $mscVersion, DATver : $datVersion.Not uploading the core !" >> /var/log/corestat.log
   return 1
fi

if [[ "$mscComm" != "30" && "$datComm" = "30" ]]
then
   echo "`date +%c` - [versionCheck] - MSC is having core with incompatible version - MSCver : $mscVersion, DATver : $datVersion. Core upload required !" >> /var/log/corestat.log
   return 0
fi

if [[ "$mscProduct" != "D" && "$datProduct" == "D" ]]
then
   echo "`date +%c` - [versionCheck] - MSC is having core with incompatible product version - MSCver : $mscVersion, DATver : $datVersion. Core upload required !" >> /var/log/corestat.log 
   return 0
fi

if [[ "$mscVariant" != "$datVariant" ]]
then
   echo "`date +%c` - [versionCheck] - Variant mismatch - MSCver : $mscVersion, DATver : $datVersion. Core upload required !" >> /var/log/corestat.log
   return 0
fi

if [[ "$mscIssue" < "$datIssue" ]]
then
   echo "`date +%c` - [versionCheck] - MSC is having older core working issue - MSCver : $mscVersion, DATver : $datVersion. Core upload required !" >> /var/log/corestat.log
   return 0
else
   echo "`date +%c` - [versionCheck] - MSC is having newer core working issue - MSCver : $mscVersion, DATver : $datVersion. Core upload is not required !" >> /var/log/corestat.log
   return 1
fi
}


########## Start of script ##################

StartTime=`date +%F@%r`
echo "START TIME :: "$StartTime >> /var/log/corestat.log

if [ -e /nn/sbin/getMSCVersion ]
then
   outputMSC=`/nn/sbin/getMSCVersion`
else
   echo "`date +%c` - /nn/sbin/getMSCVersion .....missing!!!" >> /var/log/corestat.log
   /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload FAILED....!"
   exit 1
fi

if [ ! -e /nn/etc/core_var ]
then
    createCoreVar
fi

if [ ! -e /nn/etc/core_var ]
then
   echo "`date +%c` - /nn/etc/core_var...Not Found!!!" >> /var/log/corestat.log
   /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload FAILED....!"
   exit 1
else
   confLoadtype=`awk '/VARIANT/' $confFile | awk -F= '{print $2}'`
   echo `date +%c` - Requested variant : $confLoadtype >> /var/log/corestat.log
   case "$confLoadtype" in
      "Etiquette")
         DAT_FILE="/nn/sbin/edge_etq.dat"
         ;;
      "E1")
         DAT_FILE="/nn/sbin/edge_e1.dat"
         ;;
      "E1 Global")
         DAT_FILE="/nn/sbin/edge_e1gl.dat"
         ;;
      "Auto")
         # Determine variant of core software on MSC card and specify that same variant should be used.
         descriptor=${outputMSC:2:2}
         echo "`date +%c` - Current core s/w version = <$outputMSC>; variant descriptor = <$descriptor>" >> /var/log/corestat.log
         # Note: Following case statements will need to be updated when additional variant descriptors are added likely 
         #        BCM 4.1.
         case "$descriptor" in
              "Di" | "Dc" | "Dr" | "Dg" | "Da")
                 DAT_FILE="/nn/sbin/edge_etq.dat"
                 ;;
              "Dj" | "Dd" | "Ds")
                 DAT_FILE="/nn/sbin/edge_e1.dat"
                 ;;
              "Dk" | "De" | "Dt" | "Dh" | "Db")
                 DAT_FILE="/nn/sbin/edge_e1gl.dat"
                 ;;
              *)
                 case "$outputMSC" in
                    "lablod1")
                       DAT_FILE="/nn/sbin/edge_etq.dat"
                       ;;
                    "lablod2")
                       DAT_FILE="/nn/sbin/edge_e1.dat"
                       ;;
                    "lablod3")
                       DAT_FILE="/nn/sbin/edge_e1gl.dat"
                       ;;
                    *)
                       echo "`date +%c` - Unrecognized core software version <$outputMSC>{descriptor missing} - cannot perform auto core upload...!" >> /var/log/corestat.log
 	               /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload FAILED....!"
                       exit 1
	         esac
         esac
         ;;
      *)
         echo
         echo "`date +%c` - Loadtype mis-matching in conf file......<$confLoadtype>" >> /var/log/corestat.log
         echo
         /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload FAILED....!"
         exit 1
   esac

   if [ -e /nn/sbin/getDATVersion ]
   then
      outputDAT=`/nn/sbin/getDATVersion $DAT_FILE`
   else
      echo "`date +%c` - /nn/sbin/getDATVersion file .......missing." >> /var/log/corestat.log
      /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload FAILED....!"
      exit 1
   fi

   if [ "$outputDAT" = "$outputMSC" ]
   then
      echo "`date +%c` - Version matches: MSC = $outputMSC ; DAT = $outputDAT ; DAT_FILE = $DAT_FILE  ... Core Upload not required...!" >> /var/log/corestat.log

      case "$DAT_FILE" in
         "/nn/sbin/edge_etq.dat")
            VAR_TYPE="Etiquette"
            ;;
         "/nn/sbin/edge_e1.dat")
            VAR_TYPE="E1"
            ;;
         "/nn/sbin/edge_e1gl.dat")
            VAR_TYPE="E1 Global"
            ;;
         *) 
            echo "`date +%c` - Invalid DAT file, not updating the core_var file" >> /var/log/corestat.log
            /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload FAILED....!"
            exit 1 
      esac
      echo "`date +%c` - Updating core_var file to: $VAR_TYPE" >> /var/log/corestat.log
      echo "VARIANT=$VAR_TYPE" > /nn/etc/core_var
      exit 0
   fi

   returnCode=-1
   versionCheck "$outputMSC" "$outputDAT"
   returnCode=$?

   if [ $returnCode = 0 ]
   then
      /bin/rm -f /var/nn/uploadStatus.psm    # Remove file if present
      echo "start" > /var/nn/uploadStatus.psm
      sleep 20

      echo "`date +%c` - Version mis-match: MSC = $outputMSC ; DAT = $outputDAT ; DAT_FILE = $DAT_FILE ...  Core Upload Required." >> /var/log/corestat.log
      echo "`date +%c` - Load type is - "$confLoadtype >> /var/log/corestat.log

      retry=0
      echo "************************* FRESH START **************************" >> /var/log/flow.log
      /nn/sbin/FastUpld -v -d $DAT_FILE >> /var/log/flow.log
      RCode=$?
      while (($RCode))
      do
         retry=`expr $retry + 1`
         if [ $retry -ge 3 ]
         then
            echo "`date +%c` - FastUpld all << $retry >> attempts failed.....!" >> /var/log/corestat.log
            break
         fi
         echo "`date +%c` - FastUpld FAILED - Return Code = "$RCode >> /var/log/corestat.log
         echo "`date +%c` - Retrying - FastUpld....$retry" >> /var/log/corestat.log

         sleep 5  # sleeping for 5 seconds before retrying again

         echo "************************* FRESH START **************************" >> /var/log/flow.log
         /nn/sbin/FastUpld -v -d $DAT_FILE >> /var/log/flow.log
         RCode=$?
         if [ $RCode = 0 ]; then
            echo "`date +%c` - FastUpld succeeded in << `expr $retry + 1` >> attempt(s)." >> /var/log/corestat.log
            break;
         fi
      done

      echo "finish" > /var/nn/uploadStatus.psm
      sleep 20
      echo "`date +%c` - FastUpld Return Code = "$RCode >> /var/log/corestat.log
      flag=1
   else
      echo "`date +%c` - MSC = $outputMSC ; DAT = $outputDAT ; DAT_FILE = $DAT_FILE, Core upload not required !" >> /var/log/corestat.log 
      case "$DAT_FILE" in
            "/nn/sbin/edge_etq.dat")
               VAR_TYPE="Etiquette"
               ;;
            "/nn/sbin/edge_e1.dat")
               VAR_TYPE="E1"
               ;;
            "/nn/sbin/edge_e1gl.dat")
               VAR_TYPE="E1 Global"
               ;;
            *)
               echo "`date +%c` - FastUpld: Invalid DAT file, not updating the core_var file" >> /var/log/corestat.log
               exit 1
        esac
        echo "`date +%c` - FastUpld: Updating core_var file to: $VAR_TYPE" >> /var/log/corestat.log
        echo "VARIANT=$VAR_TYPE" > /nn/etc/core_var
        exit 0
   fi
      
   if [ $flag = 1 ]
   then
      if [ $RCode = 0 ]
      then
         echo "`date +%c` - Auto Core Upload - Finished...!" >> /var/log/corestat.log
         echo $RCode > /var/nn/autoUpload.sts
         case "$DAT_FILE" in
            "/nn/sbin/edge_etq.dat")
               VAR_TYPE="Etiquette"
               ;;
            "/nn/sbin/edge_e1.dat")
               VAR_TYPE="E1"
               ;;
            "/nn/sbin/edge_e1gl.dat")
               VAR_TYPE="E1 Global"
               ;;
            *) 
               echo "`date +%c` - Invalid DAT file, not updating the core_var file" >> /var/log/corestat.log
               /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload FAILED....!"
               exit 1 
        esac
        echo "`date +%c` - Updating core_var file to: $VAR_TYPE" >> /var/log/corestat.log
        echo "VARIANT=$VAR_TYPE" > /nn/etc/core_var
      else
         echo "`date +%c` - Core Upload - Failed...!" >> /var/log/corestat.log
         echo $RCode > /var/nn/autoUpload.sts
         /nn/bin/AddNnuDiagLog -mStartupSequence -lStartupSequence.log -wR -sI -v10999 "System Startup - AutoCoreUpload FAILED....!"
         if [ $retry -ge 3 ]
         then
            if [ -e /var/nn/mfgonly/mfg.mfg ]
            then
               echo "`date +%c` - /var/nn/mfgonly/mfg.mfg File is Present.....!" >> /var/log/corestat.log
               echo "`date +%c` - autoCoreUpload will perform REBOOT Now....!" >> /var/log/corestat.log
               /sbin/reboot
            fi
         fi
         exit 1
      fi
      echo "`date +%c` - Waiting for MscService to go down....." >> /var/log/corestat.log
      Mscpid=`/sbin/pidof MscService | awk '{print $1}'`
      timer=0
      while (($Mscpid))
      do
         Mscpid=`/sbin/pidof MscService | awk '{print $1}'`
         sleep 1
         let "timer += 1"
         if [ $timer -ge 1200 ]
         then
           break
         fi
      done
      echo "`date +%c` - Wait over(MAX : 1200sec) : MSC pid = $Mscpid" >> /var/log/corestat.log
      echo "`date +%c` - Re-starting MscService........" >> /var/log/corestat.log
      sleep 1m
      /etc/rc.d/init.d/MscService start
      sleep 1m
      echo "`date +%c` - DONE...!!!!!!" >> /var/log/corestat.log
   fi       
fi

EndTime=`date +%F@%r`
echo "END TIME :: "$EndTime >> /var/log/corestat.log
echo "############## Over and out ################" >> /var/log/corestat.log
echo

