#!/bin/bash 

# -------------------------------------------------------
# file   : imaging.sh
# purpose: Imaging installation script
#        : Provides unattended upgrades
# author : Alex Rosa/Vittal.S
#
#
# modifications:
# 01-05-10  Initial Creation .
# -------------------------------------------------------

### Constants
#Append /usr/local/bin to PATH if missing,accomodates multiline pathnames for paranoia reasons
export PATH="$(printf %s "${PATH}" | /bin/sed -r -n \
    -e '/(^|:)\/+usr\/local\/bin\/*($|:)/ b EXISTS' \
    -e '$ b LAST' \
    -e 'p' -e 'b' \
    -e ':LAST' -e 's%$%:/usr/local/bin%' -e 'p' -e 'q' \
    -e ':EXISTS' -e 'p' -e 'n' -e 'b EXISTS')"
_SELF_="$(basename "$(readlink -e "${BASH_SOURCE[0]}")" && echo X)" && \
readonly _SELF_="${_SELF_%$'\nX'}"
_SELFDIR_="$(dirname "$(readlink -e "${BASH_SOURCE[0]}")" && echo X)" && \
readonly _SELFDIR_="${_SELFDIR_%$'\nX'}"
readonly COMMON8K="${_SELFDIR_}/common8k"
readonly UPGRADEDIAGINC="${_SELFDIR_}/upgrade_diag.inc"
readonly grubinstaller="/usr/bin/install_bootloader.sh"
readonly root_prim_part=2
readonly root_sec_part=3
readonly optimg_part=12
readonly gcp_image_tty="ttyS1"
readonly default_image_tty="tty7"

### Include files
source ${COMMON8K} || exit 1
source ${UPGRADEDIAGINC}

if [ "$SLESOSTYPE" = "SLES12" ]
then
	MKISOOPTS="-iso-level 4"
elif [ "$SLESOSTYPE" = "SLES15" ]
then
	MKISOOPTS="-iso-level 3"
else
	MKISOOPTS=""
fi


#Check if osv_version is available
if ! command -v osv_version.sh >/dev/null 2>&1; then
   logger --id=${$} "${0}: osv_version.sh not found in \$PATH ($PATH), using internal fallback." >/dev/null 2>&1 || :
   exit 1
fi

if [ -e /usr/sbin/iptables ]
then
IPTABLESPATH=/usr/sbin/
fi
#VARIABLES
isGoogleCloudPlatform=""

SecAuditCtrl( ) {

    if [ "$CHECK_AUDIT" = "false" ]
    then
       #logstr "upgrade8k ignore proc_aud $*"
       return 1
    fi
    if [ "x${SLESOSTYPE}x" = "xSLES11x" ]
     then   
        # if service exists
        if ! chkconfig proc_aud 2>&1 | grep 'unknown service' 1>/dev/null 2>&1
        then
           /etc/init.d/proc_aud $* 1>/dev/null 2>&1 || \
           logstr "upgrade8k failed to perform: /etc/init.d/proc_aud $*"
        fi
    elif [ "x${SLESOSTYPE}x" = "xSLES12x" ] || [ "x${SLESOSTYPE}x" = "xSLES15x" ]
     then
        /etc/init.d/proc_aud $* 1>/dev/null 2>&1 || \
        logstr "upgrade8k failed to perform: /etc/init.d/proc_aud $*"
    fi

   return 0
}

# -------------------------------------------------------
# function: trap handler for errors.
# args    : None
# -------------------------------------------------------

trapnexit( )
{
   oplock exit
   _mount | grep -q "/repository/upload"
   if [ $? -eq 0 ];
   then
      umount /repository/upload 2>/dev/null
   fi

   if [ "$RECONFIG8k" = "true" ];
   then
      return 
   fi

   if [ "$LIVE8kUPGRADE" = "true" ];
   then
      return 
   fi

   if [ "$UPDATE8k" = "true" -a -d ${REPOSITORY}/upload ];
   then
      if [ "$testbed" = "cluster" -a "$mynode" = "$primhost" ];
      then
         ssh $sechost " 
            if [ -f ${REPOSITORY}/upload/node.cfg.primary -a ! -f ${REPOSITORY}/upload/node.cfg.secondary ];
            then
               for idx in `find ${REPOSITORY}/upload -name \*.zip`
               do
                  basezip=`basename $idx .zip | sed -e 's/^c-//g'`
                  rm -f ${REPOSITORY}/media/patch/${basezip}.*
               done
               mv -f ${REPOSITORY}/media/node.cfg.*     ${REPOSITORY}/upload
               mv -f ${REPOSITORY}/media/fqdn.cfg       ${REPOSITORY}/upload
               mv -f ${REPOSITORY}/media/response.cfg.* ${REPOSITORY}/upload
               mv -f ${REPOSITORY}/media/patch/*        ${REPOSITORY}/upload
               mv -f ${REPOSITORY}/media/iso/*          ${REPOSITORY}/upload
               mv -f ${REPOSITORY}/media/*.lic          ${REPOSITORY}/upload
               mv -f ${REPOSITORY}/media/export/*.lic   ${REPOSITORY}/upload
               export QUICKRESET8k="true"
               activate8k -reset
            fi
         "
      fi
      if [ ! -f ${REPOSITORY}/upload/node.cfg.primary -a ! -f ${REPOSITORY}/upload/node.cfg.secondary ];
      then
         for idx in `find ${REPOSITORY}/upload -name \*.zip`
         do
           basezip=`basename $idx .zip | sed -e 's/^c-//g'`
           rm -f ${REPOSITORY}/media/patch/${basezip}.*
         done
         mv -f ${REPOSITORY}/media/node.cfg.*     ${REPOSITORY}/upload  
         mv -f ${REPOSITORY}/media/fqdn.cfg       ${REPOSITORY}/upload
         mv -f ${REPOSITORY}/media/response.cfg.* ${REPOSITORY}/upload  
         mv -f ${REPOSITORY}/media/patch/*        ${REPOSITORY}/upload
         mv -f ${REPOSITORY}/media/iso/*          ${REPOSITORY}/upload
         mv -f ${REPOSITORY}/media/*.lic          ${REPOSITORY}/upload  
         mv -f ${REPOSITORY}/media/export/*.lic   ${REPOSITORY}/upload  
         export QUICKRESET8k="true"
         activate8k -reset
      fi
      rm -f ${REPOSITORY}/upload/dev.8kps
   fi 2>/dev/null

   if [ "$CHECK_AUDIT" = "true" ]
   then
      rm -f /software/PBI/secAuditCreate.sh /software/PBI/secAuditList.conf
   fi
   SecAuditCtrl "mop-start"
}

# ----------------------------------------------------------------
# function: getSyncPartition
# args    : none
# description:
# returns the syncpart and syncother parameters
# ----------------------------------------------------------------
getSyncPartition()
{
   cat /etc/fstab | grep "/home" | grep -v "^/dev/${diskdev}" | grep -q primary
   if [ $? -eq 0 ];
   then
      syncpart="primary"
      syncother="secondary"
   else
      syncpart="secondary"
      syncother="primary"
   fi
}

# ----------------------------------------------------------------
# function: getload
# args    : none
# description:
# returns the current load information from rpm database.
# ----------------------------------------------------------------

getload( )
{
   if [ "$1" = "self" ];
   then
      load="`rpm -aq | grep UNSPps[0-9][0-9][0-9][0-9]* \
                     | sort -t '-' -k 3 | tail -1       \
                     | awk -F '-' '{ print $2"-"$1 }'`"
   else
      load="`ssh $othernode -o ConnectTimeout=8 \"
             rpm -aq | grep UNSPps[0-9][0-9][0-9][0-9]* | \
             sort -t '-' -k 3  | tail -1\" 2>/dev/null  | \
             awk -F '-' '{ print $2"-"$1 }'`"
   fi
   echo $load
}

comparepatchset( ) {

  #<CompareLoads>
   sourceps=`echo $myload | awk -F'-' '{ print $2 }'| \
                              sed -e 's/.*UNSPps//g'    \
                                 -e 's/E/\./g'`
   source_major_version=""
   target_major_version=""
   if [ "$sourceps" != "" ]
   then
      source_major_version=`echo $myload | awk -F"." '{print $1}'`  	
   fi

   targetdvdps=`cat /repository/upload/version | egrep "^Image" | \
                  awk -F'-' '{ print $3 }'                       | \
                  sed -e 's/E/\./g' -e 's/\.x86_64//g'`
   targetuploadps=`find /repository/upload/ -name \*V\*.tar -o -name \*V\*.zip | sort | tail -1`
   if [ "$targetuploadps" != "" ];
   then
      targetps=`echo $targetuploadps | awk -F'.' '{ print $2"."$3 }'`
      target_major_version=`basename $targetuploadps | awk -F"." '{print $1}' | sed -e 's/.*-//g'`
   else
      targetps=$targetdvdps
      target_major_version=`cat /repository/upload/version | egrep "^Image" | \
                  awk -F'.' '{ print $1 }'  | cut -d ':' -f 2 | xargs`
   fi

   logstr "Major versions:  $target_major_version -> $source_major_version"
   # compare the major versions
   if osv_version.sh --major compare "$target_major_version" ge "$source_major_version";
   then
      logstr "target $target_major_version is greater than source $source_major_version, no need to check patchsets"
      return 0
   fi

   if [ "$sourceps" != "" -a "$targetps" != "" ];
   then
      psresult=`echo $sourceps'>'$targetps | bc -l`
      if [ $psresult -ne 0 ];
      then
         logstr "   - Target Patchset: $targetps"
         logstr "   - Source Patchset: $sourceps"
         logstr "   - Sorry, upgrades are only possible to a greater patchset."
         logstate "UpgradeReset"
         exit $DBRESTOREFAILED
      fi
   fi
  #</CompareLoads>
}

# ----------------------------------------------------------------
# function: setmeup
# args    : none
# description:
#   given any string it will format it to required length.
# ----------------------------------------------------------------

setmeup( )
{
   varvaluetmp=$1
   length=$2
   varlength=$3
   length=${#varvaluetmp}
   if [ $length -ge 0 -a $length -lt $varlength ];
   then
      spaces=`expr $varlength - $length`
      while [ $spaces -gt 0 ];
      do
         varvaluetmp="${varvaluetmp}' '"
         spaces=`expr $spaces - 1`
      done
   fi
   eval cfgvarres="$varvaluetmp"
}

# -------------------------------------------------------
# function: logstate
# args    : None
# description:
#   tracks the state during install.
# -------------------------------------------------------

logstate( )
{
   if [ "$VAPP8k" = "true" ];
   then
      return
   fi
   state=$1
   touch ${REPOSITORY}/upgrade8k-details
   touch ${REPOSITORY}/upgrade8k-timing
   chown srx.${srxgroup} ${REPOSITORY}/upgrade8k-details
   chown srx.${srxgroup} ${REPOSITORY}/upgrade8k-timing
   setmeup $state 28 28
   echo "[+] ${cfgvarres:0:28} `date -u '+%D %H:%M:%S'`" >> ${REPOSITORY}/upgrade8k-timing
   {
      echo "[U>] ${cfgvarres:0:28},`date '+%D %H:%M:%S'`,${statestr[`statecount ${state}`]}" 
      echo "[A>]"
      arp -an
      echo "[P>]"
      mpstat -P ALL 
      echo "[I>]"
      pidstat -r -u
      echo "[D>]"
      vmstat -d | grep -v loop
      echo "[R>]"
      route -n
      ip route show
   }  >> ${REPOSITORY}/upgrade8k-details
}

# -------------------------------------------------------
# function: checksys
# args    :  none
# description:
#   checks all critical errors.
# -------------------------------------------------------

checksys( ) {
   #<CheckHwAbstraction>

      cat /etc/fstab | grep -q "/img/optimg"
      if [ $? -ne 0 ];
      then
         echo "Detected non imaged disk."
         exit $FAIL
      fi
      cat /etc/fstab | grep "/img/optimg" | grep -q "^/dev/sda"
      scsistat=$?
      if [ $scsistat -ne 0 ];
      then
         cat /etc/mtab | egrep "/dev/sda14|/dev/sda7" | grep -q "var"
         scsistat=$?
      fi
      if [ $scsistat -eq 0 ];
      then
         echo "Detected scsi disk."
         diskdev=sda
      else
         cat /etc/fstab | grep "/img/homeimg" | grep -q "^/dev/hda"
         if [ $? -eq 0 ];
         then
            echo "Detected ide disk."
            diskdev=hda
         else
            echo "[*] Unknown disk type."
            exit $FAIL
         fi
      fi

   #</CheckHwAbstraction>
   if [ -h /etc/mtab ] #if mtab is link they we suppose we are in a sles12 environment
   then
   findmnt --fstab --evaluate |grep -q primary
    primstatus=$?
   findmnt --fstab --evaluate |grep -q secondary
    secstatus=$?
   else
   grep -q primary /etc/mtab
    primstatus=$?
   grep -q  secondary /etc/mtab
   secstatus=$?
   fi

   if [ $primstatus -ne 0 -a $secstatus -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: Looks like you are on non imaged disk."
      textncolor $BoldRed "upgrade8k: This is not supported. Good luck."
      exit $DISKIDFAILED
   fi
   if  [ $primstatus -eq 0 -a $secstatus -eq 0 ];
   then
      textncolor $BoldRed "upgrade8k: Look, you have both the active and fallback partitions mounted."
      textncolor $BoldRed "upgrade8k: This is strange.Cannot proceed with such a configuration."
      exit $DISKIDFAILED 
   fi
   mount | grep -q "/img/rootimg/"
   if [ $? -eq 0 ];
   then
      textncolor $BoldRed "upgrade8k: Looks like you have something mounted on fallback image(/img/rootimg)."
      exit $DISKIDFAILED 
   fi

   if [ $primstatus -eq 0 ];
   then
      bootdev="(hd0,1)"
      sdadev=${diskdev}2
   else
      bootdev="(hd0,2)"
      sdadev=${diskdev}3
   fi
}


# ---------------------------------------------------------------
# function: initvars
# args    : None
# description:
#   just initialize one variables.
# ---------------------------------------------------------------

initvars( )
{
   SUCCESS=0
   FAIL=2
   INSTALLRPMFAILED=3
   EXPORTDATAFAILED=4
   SETUPIMAGEFAILED=5
   BUILDREPOSITORYFAILED=6
   MOUNTISOFAILED=7 
   SYNCIMAGEFAILED=8
   DISKIDFAILED=9
   GRUBAUDITFAILED=10
   DBSWITCHFAILED=11
   GRUBINSTALLFAILED=12
   UNKNOWNINSTTYPE=13
   BUILDISOFAILED=14
   DBCHECKFAILED=15
   CFGCHECKFAILED=16
   SASTOPFAILED=17
   SRXCTRLSTOPFAILED=18
   SPLITFAILED=19
   JOINFAILED=20
   REMOTEOPTFAILED=21
   INVALIDCKSUM=22
   INVALIDBONDS=23

   BoldGreen="\033[1;32m"
   BoldBlue="\033[1;34m"
   BoldCyan="\033[1;36m"
   BoldWhite="\033[1;37m"
   BoldRed="\033[1;31m"
   UnderLine="\033[4m"
   Yellow="\033[1;33m"
   Norm="\033[0m"

   REPOSITORY=/repository
   NFSARG=""
   EXPORT=true
   IMPORT=true
   RECONFIG8k=false
   VAPP8k=false
   LOCALREPO8k=false
   REMOTE8kCMD=false
   CLEAN8k=false
   MOUNT8kDEV=false
   UPDATE8k=false
   FORCE8k=false
   SLICKINIT=false
   INITOSV8k=false
   HWMIGRATION=false
   NOSOLIDDEBUG=false
   LIVE8kUPGRADE=${LIVE8kUPGRADE:-false}
   export SYNC8k=${SYNC8k:-false}
   CFG8k=/etc/hiq8000/node.cfg
   LOGFILE=/log/prepare8k.log
   USEREXPORT=/repository/export
   DBA_PASSWDFILE="/opt/solid/RtpDb/dba.secrets"
   DBCRYPT=/unisphere/srx3000/callp/bin/db_crypt
 
   # Save the location of the upgrade rescue system in the ISO used for the upgrade
   # This should be <ISO ROOT>/boot_rescue for OSV-ISO-LINUX and <ISO ROOT>/boot in
   # the legacy V7/V8 images.
   UPGRADE_RESCUE_SYSTEM_ISORELPATH="boot"
   
   #<Flags>
   HWLOCK=/lock/.hwupdate.lock
   HWSWITCH=/repository/upgrade8k-live.hw
   LIVESWITCH=/repository/upgrade8k-live.switch
   LIVEQUIET=/repository/upgrade8k-live.quiet
   #<Flags>

   gatherostype

   # if import is in  place do not interfere with SecAudit
   if [ "$SLESOSTYPE" = "SLES12" ] || [ "$SLESOSTYPE" = "SLES15" ] && [ -f /usr/sbin/S99zverify ]
   then
      logstr "upgrade8k will ignore proc_aud"
      CHECK_AUDIT=false
   fi

   if [ "x${SLESOSTYPE}x" = "xSLES11x" -a -f /etc/init.d/zverify ]
   then
      logstr "upgrade8k will ignore proc_aud"
      CHECK_AUDIT=false
   fi

   # Disable SecAudit during upgrade
   SecAuditCtrl "mop-stop"

   checkpwd
   PATH=/sbin:${PATH}
   #<VAppStartup>
      echo "$ARGLIST" | egrep -q "\-reconfigvapp"
      if [ $? -eq 0 ];
      then
         echo "[upgrade8k]: Virtual App, capture mode."
         if [ -f /unisphere/srx3000/srx/startup/srxctrl ];
         then
            srxctrl 3 3
         fi
      fi
   #</VAppStartup>

   #<IsOnGoogle>
   res=`type -t getvmtypefromDMI`
   if [ "$res" = "function" ]; then
       vmtype=`getvmtypefromDMI`
       if [ "$vmtype" = "Google" ]; then
           isGoogleCloudPlatform="true"
           KERNEL_GCP_SERIAL="$KERNEL_GCP_SERIAL_DEFAULT"
       fi
   fi
   #</IsOnGoogle>
   USER=`id -u`
   echo "$ARGLIST" | awk '{print $1}' |  egrep -q "\-s[ \t]*$"
   if [ $? -ne 0 ];
   then
      SLICKINIT=false
      if [ $USER -ne 0 ];
      then
          echo "You  must be root to run this script."
          exit $FAIL
      fi

      # Make sure this is the only job running
      if isOnlyOne
      then
         :
      else
         cat $INFLOG 2>/dev/null | egrep -v "^CURRENT" | egrep -vq "\-s|\-verify|\-buildliveinst|\-rbuildliveinst|\-switch|\-commit|\-live"
         if [ $? -ne 0 ];
         then
            textncolor $BoldCyan "upgrade8k: Another upgrade8k job already running on $mynode: pid - $PID_JOB_RUNNING"
            echo                 ">Info"
            cat                  $INFLOG 2>/dev/null
            textncolor $BoldRed  "upgrade8k: Terminate existing running job or wait for its completion."
            exit $FAIL
         fi
      fi

      oplock force
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Another upgrade8k job has a lock."
         textncolor $BoldRed "upgrade8k: Terminate existing running job or wait for its completion."
         exit $FAIL
      fi
   else
      SLICKINIT=true
   fi
   mynode="`uname -n`"
   USER=`id -u`
   buildid=$(osv_version.sh get)

   primvar=node_1_name
   secvar=node_2_name

   _mount | egrep -q "udev|devtmpfs"
   if [ $? -eq 0 ];
   then
      ARCH="x86_64"
   else
      ARCH=""
   fi

   getcfgvar $CFG8k test_bed             testbed
   getcfgvar $CFG8k product_type         product
   getcfgvar $CFG8k $primvar             primhost
   getcfgvar $CFG8k $secvar              sechost
   getcfgvar $CFG8k nfs_ip               nfsip
   getcfgvar $CFG8k hardware_platform_id hwid 
   getcfgvar $CFG8k hw_platform          hwplatform
   getcfgvar $CFG8k installation_mode    instmode
   getcfgvar $CFG8k cluster_name         clustername
   getcfgvar $CFG8k virtualized          virtualized

   nafoxch="`cfgread nafo3`"
   if osv_version.sh --major compare sys lt V5 || [ "$nafoxch" = "" ];
   then
      getcfgvar $CFG8k node_1_cip_logical   primcip
      getcfgvar $CFG8k node_2_cip_logical   seccip
   else
      primcip="`echo $nafoxch   | awk '{ print $4 }'`"
      seccip="`echo $nafoxch    | awk '{ print $5 }'`"
   fi
   if [ "$mynode" = "$primhost" ];
   then
      othernode=$sechost
   else
      othernode=$primhost
   fi
      
   if [ "$SLICKINIT" != "true" ];
   then
   #<GetActiveInfo>
      if [ "$NoBannerTk" != "true" ];
      then
         echo                 "//////////////////////////////////////////"
         textncolor $BoldCyan "`date`"
         textncolor $BoldCyan "Note: Current Active image<$mynode>:"
         echo                 "//////////////////////////////////////////"
         /usr/bin/sync8k -q none 1>/dev/null 2>&1
      else
         /usr/bin/sync8k -q none
      fi
      if [ $? -ne 0 ];
      then
         echo "Sorry, Cannot determine active image.!"
         exit $FAIL
      fi
      activeinfo="`/usr/bin/sync8k -q none`"
      activenotrail=${activeinfo%,*}
      activeimg=${activenotrail#*:}
      passiveimg=${activeinfo#*Fallback:}
      upgrademode="`cat /img/logimg/${passiveimg}/upgrade.lock 2>/dev/null | head -1`"
   #</GetActiveInfo>
   fi

   #<InitErrMappingTable>
      initerrmapping
   #</InitErrMappingTable>

   #<SetProcMapping>
      activemode="`cat /img/logimg/${activeimg}/upgrade.lock 2>/dev/null | head -1`"
      passivemode="`cat /img/logimg/${passiveimg}/upgrade.lock 2>/dev/null | head -1`"
      if [ "$activemode" = "" -a "$passivemode" = "" ];
      then
         iptables -nL firewall 1>/dev/null 2>&1
         if [ $? -eq 0 ];
         then
            passivemode="OutageFree"
         fi
      fi
      procprimmap=""
      procsecmap=""
      for proclist in NRF:/opt/SMAW/SMAWrtp/cust_conf/SrxNRF.tcn                  \
                      psr:/opt/SMAW/SMAWrtp/cust_conf/HiqPsr.tcn                  \
                      soapServer0:/opt/SMAW/SMAWrtp/cust_conf/soapServer.tcn      \
                      soapAsyncServer0:/opt/SMAW/SMAWrtp/cust_conf/soapServer.tcn \
                      submgtSchedule0:/opt/SMAW/SMAWrtp/cust_conf/soapServer.tcn  \
                      smucom:/opt/SMAW/SMAWrtp/cust_conf/SrxSmuCom.tcn            \
                      AswoMgr:/opt/SMAW/SMAWrtp/cust_conf/hiQAswoMgr.tcn          \
                      tcagMgr:/opt/SMAW/SMAWrtp/cust_conf/SrxTCAG.tcn             \
                      pcm:/opt/SMAW/SMAWrtp/cust_conf/HiqPcm.tcn
      do
         nextprocname="`echo $proclist | awk -F':' '{ print $1 }'`"
         if [ "$passivemode" = "OutageFree" ];
         then
            procconfinfo="`echo $proclist | awk -F':' '{ print $2 }'`"
            procconffile="`basename $procconfinfo`"
            nextprocconf="`getfallback8k $procconfinfo`/$procconffile"
         else
            nextprocconf="`echo $proclist | awk -F':' '{ print $2 }'`"
         fi
         if [ -f "$nextprocconf" ];
         then
            grep -q $nextprocname $nextprocconf 
            if [ $? -eq 0 ];
            then
               procprimmap="$procprimmap ${nextprocname}1"
               procsecmap="$procsecmap ${nextprocname}2"
            fi
         fi
      done
   #<SetProcMapping>

   #<GroupFlip>
      grep -q "^rtpgrp" /etc/group
      if [ $? -eq 0 ];
      then
         srxgroup=rtpgrp
      else
         srxgroup=other
      fi
   #</GroupFlip>

   #<UserExport>
      uexport=false
      if [ -f $USEREXPORT/node.cfg.primary -o $USEREXPORT/node.cfg.secondary ];
      then
         if [ -f $USEREXPORT/patch/export.tar ];
         then
            uexport=true
         fi
      fi
   #</UserExport>

   #<HwMigration>
      if [ -f $HWLOCK -o -f $HWSWITCH ];
      then
         HWMIGRATION=true
      fi
   #</HwMigration>

   trap 'trapnexit' EXIT SIGHUP SIGINT SIGQUIT SIGTERM
}

# ---------------------------------------------------------------
# function: setup_upgrade_diagnostics
# args    : None
# description:
#   Perform all the actions to setup upgrade diagnostics
# ---------------------------------------------------------------

setup_upgrade_diagnostics( )
{
   #OSV-12908
   #<AdditionalUpgradeDiagnostics>

   #Reset diagnostics
   upgrade_diagnostics_reset

   if [ "$testbed" = "cluster" ]
   then
      upgrade_diagnostics_reset $othernode
   fi

   #Enable solid diagnostics in case of cluster
   if [ "$testbed" = "cluster" ] && [ "$NOSOLIDDEBUG" = "false" ]
   then
      upgrade_diagnostics_add SSDEBUG
   fi

   if [ "$testbed" = "cluster" ] && [ -f $REPOSITORY/diagnostics.dbg ]
   then
      upgrade_diagnostics_copy $othernode
   fi
   #</AdditionalUpgradeDiagnostics>
}

# ---------------------------------------------------------------
# function: setrepository
# args    : None
# description:
#   just initialize repository builds one if it does not exist.
# ---------------------------------------------------------------

setrepository( )
{
   cat /etc/passwd | egrep -q  "^sym:"
   if [ $? -ne 0 ];
   then
     if osv_version.sh --major compare sys lt V7;
     then
        echo "sym:x:102:113:Symphonia Framework:/enterprise:/bin/false" >> /etc/passwd
     else
        echo "sym:x:503:903:Symphonia Framework:/enterprise:/bin/false" >> /etc/passwd
     fi
   fi
   cat /etc/group | egrep -q  "^sym:"
   if [ $? -ne 0 ];
   then
     if osv_version.sh --major compare sys lt V7;
     then
        echo "sym:!:113:" >> /etc/group
     else
        echo "sym:!:903:" >> /etc/group
     fi
   fi
   
   cat /etc/fstab | grep -q "/img/softwareimg/common"
   if [ $? -eq 0 ];
   then
      textncolor $BoldCyan "upgrade8k: shared repository found."
      mkdir -p      ${REPOSITORY}/upload
      chown sym.rtpgrp ${REPOSITORY}/upload
      chmod g+w     ${REPOSITORY}/upload
   else
      textncolor $BoldGreen "upgrade8k: repository being built."
      mkdir -p      /repository /img/softwareimg/common
      chmod 0755    /repository /img/softwareimg/common
      chown sym.sym /repository /img/softwareimg/common
      mount -o bind /img/softwareimg/common /repository
      mkdir -p      ${REPOSITORY}/upload
      chown sym.rtpgrp ${REPOSITORY}/upload
      chmod g+w     ${REPOSITORY}/upload
      if [ $? -ne 0 ];
      then
         echo "upgrade8k: repository build failed."   
         exit $BUILDREPOSITORYFAILED
      fi
      echo "/img/softwareimg/common    /repository none bind 0 0" >> /etc/fstab
   fi
}


# ---------------------------------------------------------------
# function: exportdata
# args    : None
# description:
#   exports data to the shared repository.
# ---------------------------------------------------------------

exportdata( )
{
   if [ "$mynode" = "$primhost" ];
   then
      textncolor $BoldCyan "upgrade8k: Preparing to export data to shared repository."
      if [ "$testbed" = "cluster" ];
      then
         ssh $othernode -o ConnectTimeout=8 "rm -rf /repository/media/export"
         if [ $? -ne 0 ];
         then
            textncolor $BoldRed "upgrade8k: Failed to clean on $othernode."
            exit $EXPORTDATAFAILED
         fi
      fi

      rm -rf /repository/media/export
      if [ "$EXPORT" = "true" ];
      then
         export NON_OUTAGE_FREE_UPGRADE_EXPORT=true
         export8k -quiet -cfg /repository/media/export
      else
         mkdir -p /repository/media/export/patch
         if [ "$uexport" = "true" ];
         then
            cp -R $USEREXPORT /repository/media/.
         fi
      fi
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Failed to export data to shared repository."
         upgrade8k -reset
         exit $EXPORTDATAFAILED
      fi
      textncolor $BoldCyan "upgrade8k: Checking for licenses to import."
      cp -f ${REPOSITORY}/media/*.lic ${REPOSITORY}/media/export 1>/dev/null 2>&1
      if [ "$testbed" = "cluster" ];
      then
         ssh $othernode "cp -f ${REPOSITORY}/media/*.lic ${REPOSITORY}/media/export 1>/dev/null 2>&1"
      fi
   fi
}

# ---------------------------------------------------------------
# function: setupimage
# args    : None
# description:
#   User provides a zip file which contains the iso,node.cfg and
#   response.cfg if integrated simplex/cluster.
# ---------------------------------------------------------------

setupimage( )
{
    rm -rf   ${REPOSITORY}/media/iso/* ${REPOSITORY}/media/patch/* \
             ${REPOSITORY}/tmp ${REPOSITORY}/media
    mkdir -p ${REPOSITORY}/media/iso   ${REPOSITORY}/media/patch   \
             ${REPOSITORY}/media/cdrom ${REPOSITORY}/tmp
    touch    ${REPOSITORY}/media/patch/dev.8kps
    UPDATE8k=true
    
    #<Setup4Nfs>
    if [ "$NFSARG" != "" ];
    then
       textncolor $BoldCyan "upgrade8k: nfs based upgrade."
       mount -t nfs ${NFSIP}:${NFSPATH}  /repository/upload
       if [ $? -ne 0 ];
       then
          textncolor $BoldRed "upgrade8k: nfs mount of $NFSIP:$NFSISO failed."
          exit $MOUNTISOFAILED
       fi
       find ${REPOSITORY}/upload -name ${NFSISO}\* -exec cp -f {} ${REPOSITORY}/media/iso \;
       if [ $? -ne 0 ];
       then
          textncolor $BoldRed "upgrade8k: nfs copy of $NFSISO failed."
          umount /repository/upload
          exit $SETUPIMAGEFAILED
       fi
       if [ "$mynode" = "$primhost" ];
       then
          find ${REPOSITORY}/upload -type f -name node.cfg.primary -exec cp -f {} ${REPOSITORY}/media/node.cfg.primary \;
          find /etc/hiq8000         -type f -name fqdn.cfg -exec cp -f {} ${REPOSITORY}/media/fqdn.cfg \;
          find ${REPOSITORY}/upload -type f -name response.cfg.primary -exec cp -f {} ${REPOSITORY}/media/response.cfg.primary \;
          find ${REPOSITORY}/upload -type f -name ${mynode}.node.cfg -exec cp -f {} ${REPOSITORY}/media/node.cfg.primary \;
          find ${REPOSITORY}/upload -type f -name ${mynode}.response.cfg -exec cp -f {} ${REPOSITORY}/media/response.cfg.primary \;
       else
          find ${REPOSITORY}/upload -type f -name node.cfg.secondary -exec cp -f {} ${REPOSITORY}/media/node.cfg.secondary \;
          find /etc/hiq8000         -type f -name fqdn.cfg -exec cp -f {} ${REPOSITORY}/media/fqdn.cfg \;
          find ${REPOSITORY}/upload -type f -name response.cfg.secondary -exec cp -f {} ${REPOSITORY}/media/response.cfg.secondary \;
          find ${REPOSITORY}/upload -type f -name ${mynode}.node.cfg -exec cp -f {} ${REPOSITORY}/media/node.cfg.secondary \;
          find ${REPOSITORY}/upload -type f -name ${mynode}.response.cfg -exec cp -f {} ${REPOSITORY}/media/response.cfg.secondary \;
       fi
       find ${REPOSITORY}/upload -name \*.tar            -exec cp -f {} ${REPOSITORY}/media/patch \;
       find ${REPOSITORY}/upload -name \*.rpm            -exec cp -f {} ${REPOSITORY}/media/patch \;
       find ${REPOSITORY}/upload -name \*.spa            -exec cp -f {} ${REPOSITORY}/media/patch \;
       find ${REPOSITORY}/upload -name \*H8K\*.lic       -exec cp -f {} ${REPOSITORY}/media \;
       find ${REPOSITORY}/upload -name \*OpenScape\*.lic -exec cp -f {} ${REPOSITORY}/media \;
       umount /repository/upload
    fi
    #<Setup4Nfs>
    upgradezip="`ls -Atr ${REPOSITORY}/upload/*.zip 2>/dev/null`"
    upgradefiles="`ls -Atr ${REPOSITORY}/upload 2>/dev/null`"
    if [ "$NFSARG" = "" -a "$upgradefiles" = "" ];
    then
       textncolor $BoldRed "upgrade8k: Failed to locate upgrade content."
       exit $SETUPIMAGEFAILED
    fi
    pushd ${REPOSITORY}/upload 1>/dev/null 2>/dev/null
    for idx in $upgradezip
    do
       echo "   - Unzipping `basename $idx`"
       unzip -qq $idx -d ${REPOSITORY}/tmp
       if [ $? -ne 0 ];
       then
          textncolor $BoldRed "upgrade8k: Failed to unzip upgrade content(`basename $idx`)."
          exit $SETUPIMAGEFAILED
       fi
    done
    touch ${REPOSITORY}/media/patch/dev.8kps
    find ${REPOSITORY}/upload -maxdepth 1 -name \*.iso -exec mv -f {} ${REPOSITORY}/media/iso \;
    find ${REPOSITORY}/tmp -name \*.iso -exec mv -f {} ${REPOSITORY}/media/iso \;
    if [ "$mynode" = "$primhost" ];
    then
       find ${REPOSITORY}/upload -maxdepth 1 -name \*.cfg.primary -exec mv -f {} ${REPOSITORY}/media \;
       find ${REPOSITORY}/tmp -name \*.cfg.primary -exec mv -f {} ${REPOSITORY}/media \;
    else
       find ${REPOSITORY}/upload -maxdepth 1 -name \*.cfg.secondary -exec mv -f {} ${REPOSITORY}/media \;
       find ${REPOSITORY}/tmp -name \*.cfg.secondary -exec mv -f {} ${REPOSITORY}/media \;
    fi
    find ${REPOSITORY}/upload -maxdepth 1 -name \*.tar -exec mv -f {} ${REPOSITORY}/media/patch \;
    find ${REPOSITORY}/upload -maxdepth 1 -name \*.rpm -exec mv -f {} ${REPOSITORY}/media/patch \;
    find ${REPOSITORY}/upload -name \*.spa -exec mv -f {} ${REPOSITORY}/media/patch \;
    find ${REPOSITORY}/upload -name \*H8K\*.lic -exec mv -f {} ${REPOSITORY}/media \;
    find ${REPOSITORY}/upload -name \*OpenScape\*.lic -exec mv -f {} ${REPOSITORY}/media \;
    find ${REPOSITORY}/tmp -name \*.tar -exec mv -f {} ${REPOSITORY}/media/patch \;
    find ${REPOSITORY}/tmp -name \*.rpm -exec mv -f {} ${REPOSITORY}/media/patch \;
    find ${REPOSITORY}/tmp -name \*.spa -exec mv -f {} ${REPOSITORY}/media/patch \;
    find ${REPOSITORY}/tmp -name \*H8K\*.lic -exec mv -f {} ${REPOSITORY}/media \;
    find ${REPOSITORY}/tmp -name \*OpenScape\*.lic -exec mv -f {} ${REPOSITORY}/media \;
    popd 1>/dev/null 2>/dev/null

    #<CheckImageIso>
       imageiso="`ls -At ${REPOSITORY}/media/iso/*.iso 2>/dev/null| head -1`"
       if [ "$imageiso" = "" ];
       then
          textncolor $BoldRed "upgrade8k: Failed to locate image iso."
          exit $SETUPIMAGEFAILED
       fi
    #</CheckImageIso>

    #<CheckToolkit>
       toolkitrpm="`ls -At ${REPOSITORY}/media/patch/UNSPmigration*.rpm 2>/dev/null| head -1`"
       if [ "$toolkitrpm" = "" ];
       then
          textncolor $BoldGreen "upgrade8k: No toolkit rpm located,hence upgrades will be skipped."
       fi
    #</CheckToolkit>


    #<CheckCfg>

    if [ "$mynode" = "$primhost" ];
    then
       nodecfg="`ls -At ${REPOSITORY}/media/node.cfg.primary 2>/dev/null`"
       respcfg="`ls -At ${REPOSITORY}/media/response.cfg.primary 2>/dev/null`"
       ext="primary"
       othernode="$sechost"
    else
       nodecfg="`ls -At ${REPOSITORY}/media/node.cfg.secondary 2>/dev/null`"
       respcfg="`ls -At ${REPOSITORY}/media/response.cfg.secondary 2>/dev/null`"
       ext="secondary"
       othernode="$primhost"
    fi
    if [ "$nodecfg" = "" ];
    then
       textncolor $BoldRed "upgrade8k: Failed to locate node.cfg.${ext}."
       exit $SETUPIMAGEFAILED
    else
       getcfgvar $nodecfg hardware_platform_id hwid 
       getcfgvar $nodecfg solution             solution
       getcfgvar $nodecfg srx_build_id         buildtargetid
       solutionprofile="${hwid}${solution}"
       mapprofile $solutionprofile
       if osv_version.sh --major compare "$buildtargetid" lt V5 && [ "$profile" = "integrated" ];
       then
          if [ "$respcfg" = "" ];
          then
             textncolor $BoldRed "upgrade8k: Failed to locate response.cfg.${ext}."
             exit $SETUPIMAGEFAILED
          fi
       fi
    fi

    #</CheckCfg>

}

# ---------------------------------------------------------------
# function: mkinitrdhack
# args    : None
# description:
#   builds  a new initrd for vm systems only. 
# ---------------------------------------------------------------

mkinitrdhack( )
{
   if [ "$hwplatform" = "Virtual" -o "$hwid" = "V" -o "$hwid" = "v" -o "$VAPP8k" = "true" -o "$virtualized" = "1" ];
   then
      loadpath=${1}
      INITRDHOME=/repository/tmp/initrd
      rm -rf $INITRDHOME
      mkdir -p $INITRDHOME
      if [ -f ${loadpath}/loader/initrd ];
      then
         textncolor $BoldCyan "upgrade8k:Rebuilding initrd."
         cp ${loadpath}/loader/initrd ${INITRDHOME}/initrd.gz
         gunzip ${INITRDHOME}/initrd.gz
         pushd ${INITRDHOME} 1>/dev/null 2>&1
            cpio -id < initrd
            rm -f initrd
            mv ${INITRDHOME}/sbin/insmod{,.hack}
            cat << EOF > ${INITRDHOME}/sbin/insmod
#!/bin/sh
modname=\$1
strmodname=\${modname:0:12}
echo "Loading \$strmodname"
insmod.hack \$*
if [ "\$strmodname" = "/modules/mpt" ];
then
   sleep 4
fi
if [ "\$modname" = "/modules/ext3.ko" ];
then
   while ( true )
   do
      echo "Checking \${modname}+"
      mount /dev/${diskdev}2 /mnt
      if [ \$? -eq 0 ];
      then
         umount /mnt
         break;
      fi
      mount /dev/${diskdev}3 /mnt
      if [ \$? -eq 0 ];
      then
         umount /mnt
         break;
      fi
      sleep 1
   done
fi
if [ "\$strmodname" = "/modules/scs" ];
then
   sleep 4
fi
EOF
            chmod 755 ${INITRDHOME}/sbin/insmod
            find . | cpio --create --format='newc' > ${loadpath}/loader/initrd.new
            gzip ${loadpath}/loader/initrd.new
            mv -f ${loadpath}/loader/initrd{.new.gz,}
         popd 1>/dev/null 2>&1
         rm -rf $INITRDHOME
      fi 
   fi
}

# ---------------------------------------------------------------
# function: mkrescue
# args    : None
# description:
#   builds  a new recuse which loads of the disk.
# ---------------------------------------------------------------

mkrescue( ) {

   rescuepath=$1
   mediasubopt=$2
   installmode=$3
   #tty device to use during rescue
   tty2use=""
   textncolor $BoldCyan "Updating rescue system in ${rescuepath} with mode [${mediasubopt}/${installmode}]"

   initscr=/etc/init.d/image
   rm -f /tmp/rescue /tmp/rescue.gz
   cp -f $rescuepath /tmp/rescue.gz
   gunzip /tmp/rescue.gz
   if [ $? -ne 0 ];
   then
         textncolor $BoldRed "${_SELF_}: Failed to extract Rescue system live image. \
Please make sure that you have enough free space in /tmp partition. At least 700MB are \
required. Cleanup /tmp and re-launch the program."
         exit $SETUPIMAGEFAILED
   fi
   mount -o loop /tmp/rescue /mnt
   if [ $? -ne 0 ];
   then
         textncolor $BoldRed "${_SELF_}: Failed to mount the Rescue system live image. \
This is probably due to corrupted image. Please contact the next level of support."
         exit $SETUPIMAGEFAILED
   fi
   rm -f    /mnt/mediatype/*
   mkdir -p /mnt/mediatype
   touch    /mnt/mediatype/${mediatype}
   touch    /mnt/mediatype/${mediasubopt}
   touch    /mnt/mediatype/${installmode}

    #  workaround, copy S99image to mounted rescue system
    # Probably this should move to xtree when enhancing the rescue image
    if [ -d /updateSW_new ]
    then
       cp /updateSW_new/S99image /mnt/${initscr}
       cp /updateSW_new/checkeulas.sh /mnt/usr/bin
       cp /updateSW_new/i10* /mnt/usr/bin
    fi

# if target is V9 or later then install systemd service on rescue
if [ -d /mnt/usr/lib/systemd ]
then
   if [ "$isGoogleCloudPlatform" = "true" ]; then
       tty2use="$gcp_image_tty"
       loginfo "OSV installation will continue on $gcp_image_tty console."
   else
       tty2use="$default_image_tty"
   fi
   cat << EOF > /mnt/usr/lib/systemd/system/osv.service

[Unit]
Description=Service for OSV Upgrade

[Service]
Type=oneshot
ExecStart=/etc/init.d/image start
StandardInput=tty
StandardOutput=tty
TTYPath=/dev/$tty2use
TTYReset=yes
TTYVHangup=yes

[Install]
WantedBy=multi-user.target

EOF

   logstr "upgrade8k - mkrescue , copied S99image"
   pushd /mnt/usr/lib/systemd/system/multi-user.target.wants
   ln -s ../osv.service osv.service
   if [ $? -ne 0 ]
   then
      popd
      textncolor $BoldRed "upgrade8k: Failed to setup osv service running S99image to rescue system."
      exit $SETUPIMAGEFAILED
   fi
   popd
   logstr "upgrade8k - mkrescue , created osv service in systemd"
fi
   
   if [ "$VAPP8k" = "true" ];
   then
      cat /etc/hiq8000/node.cfg | sed -e 's/hw_platform:.*/hw_platform: Virtual/'             \
                                      -e 's/hardware_platform_id:.*/hardware_platform_id: V/' \
                                > /mnt/mediatype/node.cfg
   else
      cp /etc/hiq8000/node.cfg /mnt/mediatype/node.cfg
   fi
   grep -q mountrepository /mnt/${initscr}
   if [ $? -eq 0 ];
   then
      sync
      umount /mnt
      gzip /tmp/rescue
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Failed to zip rescue."
         exit $SETUPIMAGEFAILED
      fi
      cp /tmp/rescue.gz $rescuepath 
      rm -f /tmp/rescue.gz
      return
   fi
   cat << EOF > /tmp/image.remote
mountrepository( )
{
   SWIMG=/img/softwareimg
   REPOSITORY=\${SWIMG}/common
   MEDIAPATH=\${REPOSITORY}/media
   mkdir -p \$SWIMG
   mv /sbin/fsck /sbin/fsck.nocheck
   cat << FSCKEOF > /sbin/fsck
#!/bin/sh
/sbin/fsck.nocheck -m \$*
exit \$?
FSCKEOF
   chmod 755 /sbin/fsck
   mount /dev/${diskdev}10 \$SWIMG 1>/dev/null 2>&1
   if [ \$? -eq 0 ];
   then
      if [ "\`ls -A \${REPOSITORY}/media/iso 2>/dev/null\`" != "" ];
      then
         echo "[*] Located virtual media on disk."
         imageiso="\`ls -At \${REPOSITORY}/media/iso/*.iso 2>/dev/null| head -1\`"
         baseimageiso="\`basename \$imageiso\`"
         mount -t iso9660 -o loop \$imageiso /media/cdrom 
         if [ \$? -ne 0 ];
         then
            echo "[*] Skipping virtual media on disk."
            return
         fi
         export MediaHome=/media/cdrom
         export CFGMNTPATH=\${MEDIAPATH}
         export ISOPATH=\${MEDIAPATH}/iso/\$baseimageiso
      fi
   fi
}

RAMDIR=/ramdisk
mountrepository
EOF
    sed -e "/^RAMDIR=\/ramdisk/{
      r /tmp/image.remote
      d
    }" <  /mnt/${initscr} > /tmp/image
    cp       /tmp/image /mnt/${initscr}
    sync
    umount   /mnt
    gzip /tmp/rescue
    if [ $? -ne 0 ];
    then
         textncolor $BoldRed "upgrade8k: Failed to zip rescue."
         exit $SETUPIMAGEFAILED
    fi
    cp /tmp/rescue.gz $rescuepath 
    rm -f /tmp/rescue.gz
}

# ---------------------------------------------------------------
# function: buildinstaller
# args    : None
# description:
#   builds bootable grub installer.
# ---------------------------------------------------------------

buildinstaller( )
{
    mediatype=$1

    if [ "$HWMIGRATION" = "true" ];
    then
       textncolor $BoldCyan "upgrade8k: Skipping build of local installer."
       return
    fi
    
    case "$mediatype" in
       iso)
          mediasubopt=isoinstall
          ;;
       live)
          mediasubopt=liveinstall
          ;;
       local)
          if [ "$mynode" = "$primhost" ];
          then
             mediasubopt=reconfigprimary
          else
             mediasubopt=reconfigsecondary
          fi
          ;;
       *)
          echo "Unknown Installer type. Exiting."
          exit $UNKNOWNINSTTYPE
          ;;
    esac

    if [ "$mediatype" = "live" -a "$LOCALREPO8k" = "false" ];
    then
       mount -o ro /dev/hda /mnt 2>/dev/null
       status=$?
       if [ $status -ne 0 ];
       then
          for sridx in sr0 sr1
          do
             mount -o ro /dev/${sridx} /mnt 2>/dev/null
             status=$?
             if [ $status -eq 0 ];
             then
                break;
             fi
          done
       fi
       if [ $status -ne 0 ];
       then
          textncolor $BoldRed "upgrade8k: Failed to mount dvd."
          exit $MOUNTISOFAILED
       fi 
    else
       imageiso="`ls -At ${REPOSITORY}/media/iso/*.iso 2>/dev/null| head -1`"
       mkdir -p /mnt
       mount -t iso9660 -o loop,ro $imageiso /mnt
       if [ $? -ne 0 ];
       then
          textncolor $BoldRed "upgrade8k: Failed to mount $imageiso."
          exit $MOUNTISOFAILED
       fi 
    fi

    pushd /mnt 1>/dev/null 2>&1
       textncolor $BoldCyan "Extracting image dvd."
       rm -rf /updateSW/*
       
       # cpio is used as a passthrough copy of all files in ISO, excluding *.iso,*.tar,*.rpm
       # -d is for creating directories and -m for preserving file modification times
       find . ! -name "*.iso" -a ! -name "*.tar" -a ! -name "*.rpm" -a ! -name "OSV-ISO-LINUX*" -a ! -name "squashfs.img" | cpio -pdm /updateSW 1>>$LOGFILE 2>&1
       if [ $? -ne 0 ];
       then
          textncolor $BoldRed "upgrade8k: Failed to sync image to /updateSW. Check if disk is full."
          exit $SYNCIMAGEFAILED
       fi
    popd 1>/dev/null 2>&1
    umount /mnt

	# Detect the type of ISO that we just extracted, is it a classic OSV ISO or the new OSV-ISO-LINUX?
	if [ -d /updateSW/boot_rescue ]
	then
		UPGRADE_RESCUE_SYSTEM_ISORELPATH="boot_rescue"
		textncolor $BoldCyan "Detected new type of ISO [OSV-ISO-LINUX], going to use upgrade rescue from /updateSW/${UPGRADE_RESCUE_SYSTEM_ISORELPATH}"
	else
		UPGRADE_RESCUE_SYSTEM_ISORELPATH="boot"
		textncolor $BoldCyan "Detected legacy type of ISO [V7/V8], going to use upgrade rescue from /updateSW/${UPGRADE_RESCUE_SYSTEM_ISORELPATH}"
	fi

    #<Check4InstallMode>
       if [ "$QUIETINSTALL8k" = "true" ];
       then
          installmode=quiet
       else
          installmode=complain
       fi
    #</Check4InstallMode>
     
    # temporal workaround to copy new initrd
    if [ -d /updateSW_new ]
    then
       cp -p /updateSW_new/rescue /updateSW/${UPGRADE_RESCUE_SYSTEM_ISORELPATH}/x86_64/rescue
       cp -p /updateSW_new/linux /updateSW/${UPGRADE_RESCUE_SYSTEM_ISORELPATH}/x86_64/loader/linux
       cp -p /updateSW_new/initrd /updateSW/${UPGRADE_RESCUE_SYSTEM_ISORELPATH}/x86_64/loader/initrd
       cp    /updateSW_new/UNSPxtree* /updateSW/patch
    fi

    versionstr="`file /updateSW/${UPGRADE_RESCUE_SYSTEM_ISORELPATH}/x86_64/loader/linux | sed -e "s/.*bzImage, //g" | awk -F',' '{ print $1 }' | awk '{ print $2 }'`"
    if [ "$versionstr" != "" ];
    then
       if [ "$versionstr" \> "3.1" ];
       then
          rescueosversion="SLES12"
       elif [ "$versionstr" \> "3.0" ];
       then
          rescueosversion="SLES11"
       else
          rescueosversion="SLES10"
       fi
    else
       rescueosversion="SLES10"
    fi

    # ENDOF workaround
    if [ -r /updateSW/${UPGRADE_RESCUE_SYSTEM_ISORELPATH}/x86_64/rescue ];
    then
       mkrescue /updateSW/${UPGRADE_RESCUE_SYSTEM_ISORELPATH}/x86_64/rescue "${mediasubopt}" "${installmode}"
       relloadpath=${UPGRADE_RESCUE_SYSTEM_ISORELPATH}/x86_64 # TODO: Remove this variable not used anywhere
       loadpath=/updateSW/${UPGRADE_RESCUE_SYSTEM_ISORELPATH}/x86_64
    else
      if [ -r /updateSW/boot/rescue ]; # Old version of ISO, no x86_64 system?
      then
         mkrescue /updateSW/boot/rescue "$mediasubopt" "${installmode}"
         loadpath=/updateSW/boot
      else
         textncolor $BoldRed "${_SELF_}: Failed to locate Rescue system live image \
in /updateSW/ folder. If the folder is empty or missing files, please check the disk \
space available in your root filesystem partition (mount folder /)."
         exit $SETUPIMAGEFAILED
      fi
    fi

    # Looks like we dont need to hack the initrd at the moment
    # Dracut has made a good job	
    if [ ${rescueosversion} != "SLES12" ]
    then
       mkinitrdhack $loadpath
    fi

    if [ "$RECONFIG8k" = "true" ];
    then
       rescuetitle="Reconfigure Softswitch"
    else
       rescuetitle="Install Softswitch"
    fi

   case "$mediatype" in
   iso)
      {
         echo "Last upgrade8k : `date -u`"
         /unisphere/srx3000/srx/bin/sync8k -v
         echo "Import:$IMPORT"
      } > ${REPOSITORY}/media/upgrade8k.lock 
      ;;
   live)
      touch /log/upgrade.lock
      ;;  
   local)
      rm -f /img/logimg/primary/upgrade.lock /img/logimg/secondary/upgrade.lock
      touch /img/logimg/${passiveimg}/upgrade.lock
      ;;
   *)
      echo "Unknown Installer type. Exiting"
      
      exit $UNKNOWNINSTTYPE
   esac

   #<SetBootLoader>
      textncolor $BoldCyan "upgrade8k: Setting up primary boot device(${diskdev})."

      # Retrieve synpart and syncother parameters
      getSyncPartition

      # Install GRUB bootloader depending on installed loads
      logstr "Executing :${grubinstaller} \"${syncpart}\" \"/dev/${diskdev}\" ${root_prim_part} ${root_sec_part} \
      ${optimg_part} \"${rescueosversion}\" \"${rescuetitle}\" '/dev/sda'" 

      ${grubinstaller} "${syncpart}" "/dev/${diskdev}" ${root_prim_part} ${root_sec_part} \
      ${optimg_part} "${rescueosversion}" "${rescuetitle}" '/dev/sda' 1>>$LOGFILE 2>&1
      if [ $? -ne 0 ];
      then
         logstr "grubinstaller failed, exiting ..."
         exit ${GRUBINSTALLFAILED}
      fi
   #</SetBootLoader>
}

# ----------------------------------------------------------
# function: logstr
# description:
#   logs string to logfile.
# ----------------------------------------------------------

logstr( )
{
   str="$*"
   echo "`date`: $str"
}

# ---------------------------------------------------------------
# function: switchsolid
# args    : None
# description:
#    make sure first node is primary.
# ---------------------------------------------------------------

switchsolid( )
{
        # Sleep for 30 seconds to let solid synchronize
        sleep 30

        mynode=$1
        primhost=`cfgread node_1_name`
        sechost=`cfgread node_2_name`
        statusFile="/var/RtpDb/solidStatus"
        startTime=`date +'%s'`
        diffTime=0

        if [ "${mynode}" == "${primhost}" ]
        then
                othernode=${sechost}
        else
                othernode=${primhost}
        fi

        textncolor $BoldCyan "Check if Solid should be switched..."

        while ( true )
        do
                su - solid -c "RtpSolid -l" > ${statusFile}

                egrep 'PRIMARY|STANDALONE' ${statusFile} | grep -q $mynode
                if [ $? -ne 0 ];
                then
                        egrep 'SECONDARY ACTIVE' ${statusFile} | grep -q $mynode
                        myModeState=$?

                        egrep 'PRIMARY ACTIVE' ${statusFile} | grep -q $othernode
                        otherNodeState=$?

                        # SECONDARY ACTIVE - PRIMARY ACTIVE. All the other modes are invalid
                        if [ ${myModeState} -eq 0 ] && [ ${otherNodeState} -eq 0 ]
                        then
                                textncolor $BoldCyan "Switching Solid DB..."

                                su - solid -c "RtpSolid -X 1>/dev/null 2>&1"
                                if [ $? -ne 0 ];
                                then
                                        textncolor $BoldCyan "${_SELF_}: Sorry cannot switch db state."
                                fi

                                # Two cases apply here:
                                #    Switch OK: Continue to verify that the switch is OK
                                #    Switch NOT OK: Fail to switch. Try again until timeout.
                                sleep 8
                                continue

                        else
                                if [ $diffTime -gt 120 ]
                                then
                                        textncolor $BoldCyan "${_SELF_}: database state was now as expected in 120 seconds."
					rm -rf ${statusFile}
                                        exit $DBSWITCHFAILED
                                fi

                                endTime=`date +'%s'`
                                sleep 8
                                diffTime=$((endTime-startTime))

                        fi
                else
                        textncolor $BoldCyan "${mynode} is PRIMARY or STANDALONE, Solid DB switched..."
                        break
                fi
        done

        rm -rf ${statusFile}
}

#---------------------------------------------------------------
# function: checkremote
# args    : None
# description:
#   checks if remote node has the same level as current node.
# ---------------------------------------------------------------

checkremote( )
{
   remoteopt="$*"
   ps -ef f | grep asclient_reboot_done | egrep -v 'grep|startpar' 1>/dev/null 2>&1
   if [ $? -eq 0 ];
   then
      logstr "upgrade8k: Should not use a system while the system has not finished intsall."
      logstr "         : This is the case if asclient instance is running."
      logstr "         : Will still continue."
   fi

   if [ "$testbed" != "cluster" ];
   then
      return
   fi

   if [ "$FORCE8k" = "true" ];
   then
      return
   fi

   if [ "$mynode" = "$primhost" ];
   then
      othernode=$sechost
      othercip=$seccip
      othercipname="clusternode2-priv"
      pgrep RtpSolid 1>/dev/null 2>&1
      ESTATUS=$?
      if [ $ESTATUS -eq 0 -a "$upgrademode" != "OutageFree" ]
      then	
         switchsolid $mynode
      else
          SOLID_STATUS="RtpSolid is not running"  
          if [ $ESTATUS -eq 0 ];then
             SOLID_STATUS="RtpSolid is running"
          fi		
          logstr "upgrade8k: bypass switchsolid, upgrademode=$upgrademode, ${SOLID_STATUS}  "
      fi
   else
      othernode=$primhost
      othercip=$primcip
      othercipname="clusternode1-priv"
   fi

   #<CheckRtpSolid>
      pgrep RtpSolid 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         su - srx -c "RtpSolid -c"
         if [ $? -ne 0 ];
         then
            logstr "upgrade8k:RtpSolid check of database failed."
            exit $DBCHECKFAILED
         fi
      fi
   #</CheckRtpSolid>

   getSyncPartition

   rm -f /tmp/${othernode}.fstab
   echo -n "Checking for mount<$syncpart> on partner node<${othernode}> : "
   while ( true )
   do
      #[1]. First try the cluster ip

      sshcip=$othercip
      ssh ${othercip} -o ConnectTimeout=8 "cat /etc/fstab 2>/dev/null" 1>/tmp/${othernode}.fstab 2>/dev/null
      sshstatus=$?

      #[2]. Next try the logical name

      if [ $sshstatus -ne 0 ];
      then
         sshcip=$othercipname
         ssh ${othercipname} -o ConnectTimeout=8 "cat /etc/fstab 2>/dev/null" 1>/tmp/${othernode}.fstab 2>/dev/null
         sshstatus=$?
      fi

      #[3]. Last try the hostname via admin network.

      if [ $sshstatus -ne 0 ];
      then
         sshcip=$othernode
         ssh ${othernode} -o ConnectTimeout=8 "cat /etc/fstab 2>/dev/null" 1>/tmp/${othernode}.fstab 2>/dev/null
         sshstatus=$?
      fi

      if [ $sshstatus -eq 0 ];
      then
         grep -q $syncpart /tmp/${othernode}.fstab
         status=$?
         if [ $status -ne 0 ];
         then
            echo "-"
            textncolor $BoldGreen "Interesting, Both the nodes are not installed on same <$syncpart> side."
            grep -q $syncother /tmp/${othernode}.fstab
            status=$?
         fi
         if [ $status -eq 0 -o "$singleimaged" = "true" ];
         then
            logstr "ok"
            if [ "$mynode" = "$primhost" ];
            then
               logstr ""
               ssh ${sshcip} -o ConnectTimeout=8 "upgrade8k ${remoteopt}"
               if [ $? -ne 0 ];
               then
                  logstr "upgrade8k:Sorry, cannot $remoteopt remote node<$othernode>."
                  exit $REMOTEOPTFAILED
               fi
               logstr ""
            fi
            break;
         fi
         echo -n "."
      fi
      sleep 8
   done
}

#---------------------------------------------------------------
# function: checknodecfg
# args    : None
# description:
#    Detects if reconfiguration needs to be done.
#---------------------------------------------------------------

checknodecfg( )
{
   if [ -f /repository/upload/node.cfg.primary ];
   then
      echo "Good. Reconfigration node.cfg(primary) detected."
      nodecfg=/repository/upload/node.cfg.primary
   else 
      if [ -f /repository/upload/node.cfg.secondary ];
      then
         echo "Good. Reconfigration node.cfg(secondary) detected."
         nodecfg=/repository/upload/node.cfg.secondary
      else
         echo "Sorry, No Reconfigration node.cfg(primary|secondary) detected."
         exit $SETUPIMAGEFAILED
      fi
   fi
   cat /etc/hiq8000/node.cfg | sed -e 's/ //g' | egrep -v "^#|^$" | \
       awk -F ':' '{ print $2 }' | egrep -v "^#|^$" | sort          \
   > /tmp/node.cfg.current
   cat $nodecfg | sed -e 's/ //g' | egrep -v "^#|^$" |              \
       awk -F ':' '{ print $2 }' | egrep -v "^#|^$" | sort          \
   > /tmp/node.cfg.reconfig
  diff -iBwq /tmp/node.cfg.current /tmp/node.cfg.reconfig 1>/dev/null 2>&1
  if [ $? -eq 0 ];
  then
     textncolor $BoldCyan "Note: No Reconfigration is needed."
  fi
}

#---------------------------------------------------------------
# function: upgrade
# args    : None
# description:
#    Main entry point for remote upgrades.
#---------------------------------------------------------------

upgrade( ) 
{
   rm -rf ${REPOSITORY}/upgrade8k-timing ${REPOSITORY}/upgrade8k-details ${REPOSITORY}/upgrade8k-rescue \
          /tmp/upgrade8k-timing* ${REPOSITORY}/upload/dev.8kps
   if [ "$testbed" = "cluster" ];
   then
      ssh $othernode "rm -rf ${REPOSITORY}/upgrade8k-timing ${REPOSITORY}/upgrade8k-details ${REPOSITORY}/upgrade8k-rescue \
                                          /tmp/upgrade8k-timing* ${REPOSITORY}/upload/dev.8kps" 2>/dev/null
   fi

   #<SetupUpgradeDiagnostics>
   local primarynode=`cfgread node_1_name`
   if [ "$mynode" = "$primarynode" ];
   then
      setup_upgrade_diagnostics
   fi
   #</SetupUpgradeDiagnostics>

   logstate "InitOsvUpgrade"
   echo "Command: upgrade8k $ARGLIST"  1>>$LOGFILE 2>&1
   checkmount "/mnt" "logstate \"UpgradeReset\""
   if [ "$mynode" = "$primhost" ];
   then
      if [ "$SYNC8k" = "true" ];
      then
         while ( true )
         do
            echo -n "Do you wish to sync the running image to fallback partition ? "
            clearstdin
            read answer
            if [ "$answer" = "yes" -o "$answer" = "no" ];
            then
               if [ "$answer" != "yes" ];
               then
                  SYNC8k=false
                  RECONFIGARGS="${RECONFIGARGS} -nosync"
               else
                  SYNC8k=true
               fi
               break;
            fi
            continue
         done
      fi
      unlock8k -f
      if [ $? -ne 0 ];
      then
        echo "Failed to unlock.Hint:-Check connectivity."
        logstate "UpgradeReset"
        exit $FAIL
      fi
   fi
   #<VAppStartup>
      if [ "$VAPP8k" = "true" ];
      then
         if [ -f /unisphere/srx3000/srx/startup/srxctrl ];
         then
            srxctrl 3 3
         fi
         if [ "$mynode" = "$primhost" ];
         then
            cp -f /etc/hiq8000/node.cfg /repository/upload/node.cfg.primary
            if [ "$testbed" = "cluster" ];
            then
               scp /etc/hiq8000/node.cfg $othernode:/repository/upload/node.cfg.secondary
            fi
         fi
      fi
   #</VAppStartup>

   #<CheckFallback>
      if [ -f /etc/init.d/fallback -o -f /etc/init.d/activate ];
      then
         textncolor $BoldRed "upgrade8k: Run upgrade8k after fallback is totally complete."
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckFallback>

   lock8k -q
   #<VerifyUpload>
      logstate "CheckLocalDvdIntegrity"
      checkcontents      /repository/upload
      checkpsintegrity   /repository/upload
      checkisointegrity  /repository/upload
      if [ "$product" = "HiPath8000" ];
      then
         if [ -f ${REPOSITORY}/upload/node.cfg.primary ];
         then
            logstate "VerifyLocalNodeCfg"
            zen ${REPOSITORY}/upload/node.cfg.primary
            if [ $? -ne 0 ];
            then
               textncolor $BoldRed "upgrade8k: Check ${REPOSITORY}/upload/node.cfg.primary for errors."
               logstate "UpgradeReset"
               exit $FAIL
            fi
            detectcksum ${REPOSITORY}/upload/node.cfg.primary
            checkmtu ${REPOSITORY}/upload/node.cfg.primary
         fi
         if [ -f ${REPOSITORY}/upload/node.cfg.secondary ];
         then
            logstate "VerifyRemoteNodeCfg"
            zen ${REPOSITORY}/upload/node.cfg.secondary
            if [ $? -ne 0 ];
            then
               textncolor $BoldRed "upgrade8k: Check ${REPOSITORY}/upload/node.cfg.secondary for errors."
               logstate "UpgradeReset"
               exit $FAIL
            fi
            checkmtu ${REPOSITORY}/upload/node.cfg.secondary
         fi
      fi
   #<VerifyUpload>

   #<CheckPrimNode>
      if [ "$mynode" = "$sechost" -a "$REMOTE8kCMD" != "true" ];
      then
         textncolor $BoldRed "Sorry, Remote upgrades can be run from $primhost only!."
         logstate "UpgradeReset"
         exit $UNKNOWNINSTTYPE
      fi
   #</CheckPrimNode>
   if [ "$testbed" = "cluster" ];
   then
      logstate "CheckRemoteDvdIntegrity"
   fi
   if [ "$NFSARG" = "" ];
   then
      checkremote $RECONFIGARGS "-setup"
   else
      checkremote $RECONFIGARGS "-nfs $NFSARG -setup"
   fi
   logstate "SetupImage"
   comparepatchset
   setrepository
   setreconfig
   setupimage

   #<ExportOnRemoteUpgrade>
      if [ "$RECONFIG8k" = "false" ];
      then
         logstate "ExportClusterData"
         exportdata
         logstate "BuildLiveInstaller"
         buildinstaller "iso"
         # OSV-27143
         checkremote $RECONFIGARGS "-buildinst"
      else
         logstate "BuildLiveInstaller"
         buildinstaller "local"
      fi
   #</ExportOnRemoteUpgrade>
   echo                 "/////////////////////////////////////////////////////////////////"
   if [ "$VAPP8k" = "true" ];
   then
      textncolor $BoldCyan "upgrade8k:Remember to capture the node(s) to build the vapp."
   else
      textncolor $BoldCyan "upgrade8k:Remember to reboot the node(s) to complete the upgrade."
   fi
   if [ "$QUIETINSTALL8k" = "false" ];
   then
   textncolor $BoldCyan "         :Also, follow the update on console directly or via imm."
   textncolor $BoldCyan "         :You will be prompted to continue."
   fi
   if [ "$toolkitrpm" = "" ];
   then
      textncolor $BoldCyan "upgrade8k:No toolkit rpm was found. Upgrades will be skipped."
   fi
   echo                 "/////////////////////////////////////////////////////////////////"
   if [ "$VAPP8k" != "true" ];
   then
      logstate "InstallNodeOne"
      if [ "$testbed" = "cluster" ];
      then
         logstate "InstallNodeTwo"
      fi
   fi
   textncolor $BoldCyan "Done."
   echo ""
   UPDATE8k=false
   sync
   if [ "$QUIETINSTALL8k" = "true" -a "$mynode" = "$primhost" -a "$VAPP8k" = "false" ];
   then
      if [ "$testbed" = "cluster" ];
      then
         nohup ssh $othernode "sync;reboot -f" 1>/dev/null 2>&1 &
         echo "upgrade8k: Will wait for ${othernode} to go down : "
         while ( true )
         do
            ping -c 1 ${othernode}_cip0 1>/dev/null 2>&1
            if [ $? -ne 0 ];
            then
               break;
            fi
            echo -n "."
            sleep 2
         done
      fi
      sleep 8
      nohup reboot -f 1>/dev/null 2>&1 &
   fi
   #<VAppStop>
      if [ "$VAPP8k" = "true" ];
      then
         if [ -f /unisphere/srx3000/srx/startup/srxctrl ];
         then
            /unisphere/srx3000/srx/startup/srxctrl 2 2
         fi
         mv /repository/media/node.cfg.* /repository/upload
      fi
   #</VAppStop>
   exit $SUCCESS
}


# -------------------------------------------------------
# function: usage
# args    :  none
# description:
#   prompts the user to usage of this script.
# -------------------------------------------------------

usage( ) {
   echo "Usage: upgrade8k [  -h | -setrepository | -nfs | -noimport | -clean ]"
   echo "  Note: With no options upgrade8k will setup a new IMG install on next reboot."
   echo "      : upgrade8k needs to be run in only one node of a cluster."
   echo "  upgrade8k -h                : display this help."
   echo "  upgrade8k -s                : display the status of upgrade."
   echo "  upgrade8k -setrepository    : sets /repository if non-existent"
   echo "  upgrade8k -nfs              : gets the IMG iso and patches under the specified directory" 
   echo "                                from a nfs server."
   echo "                                e.g. upgrade8k -nfs 10.238.0.13:/V5_upgrade:V5_R0.5.0_03_IMG.iso"
   echo "  upgrade8k -noimport         : will not import the data back from the current system"
   echo "  upgrade8k -clean            : cleanup all the setup in the shared repository"
   echo "  upgrade8k -reset            : reset remote upgrade contents back to /repository/upload."
   echo "  upgrade8k -quiet            : starts remote upgrades without any prompts, on reboot."
   echo "  upgrade8k -nosoliddebug     : disables the collection of solid - ssdebug diagnostics during upgrade."
   echo "  upgrade8k -reconfig         : reconfiguration mode. Will reconfigure the current image with" 
   echo "                                node.cfg specifications under /repository/upload(Internal use only)."
   echo "  upgrade8k -collect          : collects upgrade logs on both nodes."
   echo "  upgrade8k -live             : initiate live upgrades."
   echo "  upgrade8k -fallback         : fallback to source release in case of live upgrade failure."
   echo "  upgrade8k -commit           : commit(install node#2) in case of successfull live upgrade on node#1."
}

#---------------------------------------------------------------
# function: dumparpcache
# args    : None
# description:
#    dumps arp cache, for surrent state to logfile
#---------------------------------------------------------------

dumparpcache( ) 
{
      echo "----------------------------------------"
      echo "Arp Cache $1"
      arp -an 
      echo "----------------------------------------"
      echo "Neighbor Table $1"
      ip neigh show 
      echo "----------------------------------------"
} 1>>$LOGFILE 2>&1


#---------------------------------------------------------------
# function: cleanarpcache
# args    : None
# description:
#    dumps arp cache, for surrent state to logfile
#---------------------------------------------------------------

cleanarpcache( ) 
{
      #<ClearARP's>
      dumparpcache
      for arpidx in `arp -an | grep "incomplete" | awk '{print $2}' |  sed -e 's/(//g' -e 's/)//g'`
      do
          logstr "   - Removing arp cache for $arpidx"
          arp -d $arpidx
          kver=`uname -r`
          if [ "$kver" \< "3.0.101" ];
          then
             arp -s $arpidx "00:00:00:00:00:00"
          else
             arp -s $arpidx "00:00:00:01:02:03"
          fi
          arp -d $arpidx
          ping -c 4 $arpidx 1>>$LOGFILE 2>&1
      done
      #</ClearARP's>
}


#---------------------------------------------------------------
# function: setreconfig
# args    : None
# description:
#    Using toolkit it is now possible to reconfigure a system which
#    is preinstalled via an image.
#---------------------------------------------------------------

setreconfig( )
{
   if [ "$RECONFIG8k" = "true" ];
   then
      checknodecfg
      mkdir -p ${REPOSITORY}/upload
      if [ "$QUIETINSTALL8k" != "true" ];
      then
         clearstdin
         echo    "Info: Place Image Dvd (version: $buildid) in DVD drive on `uname -n`"
         echo -n "      Now press enter : "
         read answer
      fi
      MediaHome="/mnt"
      mkdir -p $MediaHome
      echo -n "   - Checking for Dvd : "
      count=0
      while ( true )
      do
         mount -o ro /dev/hda $MediaHome 2>/dev/null
         status=$?
         if [ $status -ne 0 ];
         then
            mount -o ro /dev/sr0 $MediaHome 2>/dev/null
            status=$?
            if [ $status -ne 0 ];
            then
               mount -o ro /dev/sr1 $MediaHome 2>/dev/null
               status=$?
            fi
            if [ $status -ne 0 -a $count -eq 8 ];
            then
               echo "."
               echo "Sorry, Cannot mount Dvd. Check the Media or Drive."
               exit $MOUNTISOFAILED
            else
               dvdversion="`cat $MediaHome/version 2>/dev/null | grep "^Image" | \
                            awk -F':' '{ print $2 }' | sed -e 's/[ \t]*//g'    | \
                            awk -F '/' '{ print $1 }'`"
               if [ "$dvdversion" != "$buildid" ];
               then
                  umount $MediaHome
                  eject 2>/dev/null
                  echo "Versions dont match!."
                  echo "   - Detected $dvdversion"
                  echo "   - Expected $buildid"
                  exit $MOUNTISOFAILED
               fi
               if [ $status -eq 0 ];
               then
                  echo ok
                  break;
               else
                  echo -n "."
                  sleep 8
                  continue
               fi
            fi
         else
            break;
         fi
      done

      echo

      if [ "$SYNC8k" = "true" ];
      then
         /unisphere/srx3000/srx/bin/sync8k << EOF
yes

EOF
         if [ $? -ne 0 ];
         then
            echo "upgrade8k:Sorry, Cannot create online backup."
            exit $SYNC8kFAILED
         fi
      fi
      
      ISODIR=/software/imgrelocdisk
      ZISODIR=$ISODIR/zap
      rm -rf   $ISODIR
      pushd /mnt 1>/dev/null 2>&1
         textncolor $BoldCyan "upgrade8k:Building image dvd."
         find . ! -name "*.iso" -a ! -name "*.tar" -a ! -name "*.rpm" | cpio -pdm $ISODIR 1>>$LOGFILE 2>&1
         if [ $? -ne 0 ];
         then
            textncolor $BoldRed "upgrade8k: Failed to sync image to /updateSW. Check if disk is full."
            exit $BUILDISOFAILED
         fi
         find . -name "HipathImage*.rpm" | cpio -pdm $ISODIR
         rm -rf ${ISODIR}/image/*-simplex-* rm -rf ${ISODIR}/image/*-cluster-*
         rm -f ${ISODIR}/image/delta*
         >${ISODIR}/image/deltasig
         >${ISODIR}/image/deltaappsig
         if [ "$VAPP8k" = "true" ];
         then
            nextpatch="`rpm -aq | grep UNSPxtree`"
            for idx in `rpm -ql $nextpatch`
            do
               nextfile="`basename $idx`"
               nextdir="`dirname $idx`"
               if [ -f ${ISODIR}/image/$nextfile -o "$nextdir" = "/usr/bin"           \
                                                 -o "$nextfile" = "hipath8k.template" \
                                                 -o "$nextdir" = "/sbin" ];
               then
                  textncolor $Yellow "Copying $idx"
		  # OSV-1956: Copy the files with full permissions and stats
                  cp -a $idx ${ISODIR}/image/$nextfile
                  pushd $ISODIR 1>/dev/null 2>&1
                  nextmd5="`md5sum image/${nextfile}`"
                  popd 1>/dev/null 2>&1
                  {
                     cat ${ISODIR}/integrity | grep -v "image/$nextfile"
                     echo "${nextmd5}+"
                  } > ${ISODIR}/integrity.new
                  cp ${ISODIR}/integrity{.new,}
                  rm -f ${ISODIR}/integrity.new
               fi
            done
         fi
      popd 1>/dev/null 2>&1
      sync
      umount /mnt
      maphw
      mapprofile
      hwbed="$hwtype-$testbed-$profile"
      IMGHWBEDDIR=$ISODIR/image/${hwbed}
      mkdir -p $IMGHWBEDDIR $ZISODIR
      cp -p --parents /etc/HOSTNAME         $ZISODIR
      cp -p --parents /etc/hosts            $ZISODIR
      cp -p --parents /etc/hiq8000/node.cfg $ZISODIR
      if [ "$mynode" = "$primhost" ];
      then
         imgpostfix=""
      else
         imgpostfix="delta"
      fi
      {
      mkisofs $MKISOOPTS -graft-points -R -z -o ${IMGHWBEDDIR}/hipath8k${imgpostfix}.iso $ZISODIR 
      rm -rf ${ZISODIR}/etc
      mkdir -p ${ZISODIR}/enterprise
      mkisofs $MKISOOPTS -graft-points -R -z -o ${IMGHWBEDDIR}/hipath8k-enterprise${imgpostfix}.iso $ZISODIR 
      rm -rf  $ZISODIR
      cat $ISODIR/integrity | egrep -v "image/delta*|image/${hwbed}/*.iso" > /tmp/integrity
      pushd ${ISODIR} 1>/dev/null 2>&1
      {
         echo "`md5sum image/deltaappsig`+"
         echo "`md5sum image/deltasig`+"
         if [ "$mynode" = "$primhost" ];
         then
            echo "`md5sum image/${hwbed}/hipath8k-enterprise.iso`+"
            echo "`md5sum image/${hwbed}/hipath8k.iso`+"
         else
            echo "`md5sum image/${hwbed}/hipath8k-enterprisedelta.iso`+"
            echo "`md5sum image/${hwbed}/hipath8kdelta.iso`+"
         fi
      } >> /tmp/integrity
      popd 1>/dev/null 2>&1
      cp -f /tmp/integrity ${ISODIR}/integrity
      mkisofs -o ${REPOSITORY}/upload/$buildid.iso              \
              -joliet-long $MKISOOPTS -publisher Siemens -r -V "OSCVoice"  \
              -graft-points $ISODIR
      status=$?
      } 2>/dev/null
      rm -rf $ISODIR
      if [ $status -ne 0 ];
      then
         echo "Sorry, Cannot build an bootable disk."
         exit $BUILDISOFAILED
      fi
   fi
}


#---------------------------------------------------------------
# function: cleanup
# args    : None
# description:
#  At the end of remote upgrade cleanup all the setup in the
#  shared repository. This is not automatic as the user may want
#  ro reinstall.
#---------------------------------------------------------------

cleanup( )
{
   rm -rf /repository/media 
   rm -rf /repository/tmp
   if [ "$CLEAN8k" = "true" -o ! -f ${REPOSITORY}/upload/*.iso ];
   then
      rm -rf /repository/upload/*
   fi
} 1>/dev/null 2>&1

#---------------------------------------------------------------
# function: checkcontents
# args    : None
# description:
#   checks the integrity across nodes, in case of cluster. It is
#   possible user forgets to place something on one node & not on
#   other
#---------------------------------------------------------------

checkcontents( )
{
   contentsdir=$1
   if [ "$testbed" = "cluster" ];
   then
      if [ "$mynode" = "$primhost" ];
      then
         pushd $contentsdir 1>/dev/null 2>&1
         md5sum *.tar *.spa *.rpm node.cfg* dev.8kps 2>/dev/null | \
         sed -e 's/.primary//g' -e 's/.secondary//g' | sort  > /tmp/primlist.md5 
         ssh $sechost "cd $contentsdir; md5sum *.tar *.spa *.rpm node.cfg* dev.8kps 2>/dev/null | \
         sed -e 's/.primary//g' -e 's/.secondary//g' | sort" > /tmp/seclist.md5
         popd 1>/dev/null 2>&1
         if [ -s /tmp/primlist.md5 ];
         then
            echo "///////////////////////////////////"
            textncolor $BoldCyan "$primhost upload's"
            cat /tmp/primlist.md5 2>/dev/null
            echo "///////////////////////////////////"
            echo
         fi
         if [ -s /tmp/seclist.md5 ];
         then
            echo "///////////////////////////////////"
            textncolor $BoldCyan "$sechost upload's"
            cat /tmp/seclist.md5 2>/dev/null
            echo "///////////////////////////////////"
         echo
         fi
         diff -iBw /tmp/primlist.md5 /tmp/seclist.md5
         if [ $? -ne 0 ];
         then
            textncolor $BoldCyan "upgrade8k:Sorry, your upload contents are not the same."
            textncolor $BoldCyan "Hint: Check $contentsdir or usb on both nodes."
            exit $SETUPIMAGEFAILED
         fi
      fi
   fi
}

#---------------------------------------------------------------
# function: checkpsintegrity
# args    : None
# description:
#   checks the integrity of patchsets using spa files.
#   Its spa time!.
#---------------------------------------------------------------

checkpsintegrity( )
{
   Iloc=$1
   
   #<CheckPatchsets>
      Ispa=`ls $Iloc/*.spa 2>/dev/null`
      for spaidx in $Ispa
      do
         echo "   - spa file : `basename $spaidx` located."
         cat $spaidx| awk 'BEGIN           { copy = 0 } \
                                   /\[/            { copy = 0 } \
                                   /\[Files\]/     { copy = 1 } \
                                   copy { print }' | egrep -v "^\[" > /tmp/upgrade8k.flist
         cat $spaidx| awk 'BEGIN           { copy = 0 } \
                                   /\[/            { copy = 0 } \
                                   /\[Checksums\]/ { copy = 1 } \
                                   copy { print }' | egrep -v "^\[" > /tmp/upgrade8k.cksum
         for idx in `cat /tmp/upgrade8k.flist | awk -F '=' '{ print $1 }'`
         do
            fileidx=$idx
            fileset=`cat /tmp/upgrade8k.flist | grep "${idx}=" | awk -F '=' '{ print $2 }'`
            filecksum=`cat /tmp/upgrade8k.cksum | grep "${idx}=" | awk -F '=' '{ print $2 }'`
            if [ "$fileset" != "" -a "$filecksum" != "" -a -f $Iloc/${fileset} ];
            then
               nextcksum=`md5sum $Iloc/${fileset} | awk '{ print $1 }'`
               if [ "$nextcksum" != "$filecksum" ];
               then
                  echo "   - $fileset checksum is invalid"
                  echo "   -    Expected: $filecksum"
                  echo "   -    Observed: $nextcksum"
                  exit $SETUPIMAGEFAILED
               else
                  echo "   - $fileset checksum is o.k."
               fi
            fi
         done
      done
   #</CheckPatchsets>
}

#---------------------------------------------------------------
# function: checkisointegrity
# args    : None
# description:
#   checks the integrity of the image iso under upload.
#---------------------------------------------------------------

checkisointegrity( )
{
   Iloc=$1
   media=$2

   #<CheckValidDvdVersion>
   if [ "$LIVE8kUPGRADE" = "true" -a "$LOCALREPO8k" = "false" ];
   then
      if [ "$mynode" = "$primhost" ];
      then
          expbuildid="`fcfgread ${REPOSITORY}/upload/node.cfg.primary srx_build_id`"
      else
          expbuildid="`fcfgread ${REPOSITORY}/upload/node.cfg.secondary srx_build_id`"
      fi
      if [ "$expbuildid" = "" ];
      then
         textncolor $BoldRed "upgrade8k: Dont have a node.cfg for upgrade?"
         umount $MediaHome 
         exit $FAIL
      fi
      grep -q "$expbuildid" $Iloc/version
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed  "upgrade8k: Dont have a the right dvd for upgrade?"
         textncolor $BoldRed  "upgrade8k: Based on node.cfg, looking for dvd version $expbuildid."
         textncolor $BoldCyan "upgrade8k: Found following content inside dvd."
         cat $Iloc/version
         umount $MediaHome 
         exit $FAIL
      fi
   fi
   #</CheckValidDvdVersion>
   
   #<CheckImageIso>
      Iiso=`ls $Iloc/*.iso 2>/dev/null | head -1`
      if [ "$Iiso" != "" -o "$MOUNT8kDEV" = "true" ];
      then
         if [ "$MOUNT8kDEV" = "false" ];
         then
            echo "   - iso file :`basename $Iiso` located."
            mount -t iso9660 -o loop,ro $Iiso /mnt
         else
            echo "   - dvd detected."
         fi
         
         if [ $? -eq 0 ];
         then

            MediaHome="/mnt"
            ErrorFile=/tmp/failedintegrity
            rm -f $ErrorFile
            >$ErrorFile
            count=1
            pushd $MediaHome 1>/dev/null 2>&1
            cp -f $MediaHome/version /repository/upload/version
            for idx in `find $MediaHome -name \* -print`
            do
               nextfile="`echo $idx | sed -e 's/\/media\/cdrom\///g' -e 's/\/mnt\///g'`"
               if [ -d "$nextfile" ];
               then
                  continue;
               fi
               if [ "$nextfile" = "integrity" -o "$nextfile" = "boot/loader/isolinux.bin"         \
                    -o "$nextfile" = "boot/x86_64/loader/isolinux.bin" -o "$nextfile" = "version" \
                    -o "$nextfile" = "boot.catalog" -o "$nextfile" = "boot/x86_64/rescue"         \
                    -o "$nextfile" = "boot/rescue" -o "$nextfile" = "integrity.dos" -o "$nextfile" = "LiveOS/squashfs.img" \
                    -o "$nextfile" = "integrity.unix" -o "$nextfile" = "OSV-ISO-LINUX-read-only.x86_64-2.0.0" \
                    -o "$nextfile" = "config.isoclient" -o "$nextfile" = "glump" -o "$nextfile" = "liveboot" ];
               then
                   continue;
               fi
               
               # Skip all files in boot/boot_rescue since they are not part of the image
               if [[ ${nextfile} = "boot"* ]]
               then
                  continue;
               fi
			   
               if [ "$LIVE8kUPGRADE" = "true" -a "$testbed" = "cluster" ];
               then
                  stripnextfile=${nextfile/enterprise/}
                  if [ "$stripnextfile" != "$nextfile" ];
                  then
                     continue;
                  fi
                  stripnextfile=${nextfile/nuance/}
                  if [ "$stripnextfile" != "$nextfile" ];
                  then
                     continue;
                  fi
               fi
               echo -n "   - $nextfile "
               nextfilemd5sum="`md5sum $nextfile`+"
               md5sumondvd="`cat integrity | grep -F \" ${nextfile}+\"`"
               if [ "$md5sumondvd" = "$nextfilemd5sum" ];
               then
                  echo "is ok"
               else
                  Status=$Md5SumCheckFailed
                  echo "has failed"
                  echo "[$count]: sys->$nextfilemd5sum / dvd->$md5sumondvd" >> $ErrorFile
                  count=`expr $count + 1`
               fi
            done
            popd 1>/dev/null 2>&1

            if [ -s $ErrorFile ];
            then
               echo "Following Errors were detected :"
               echo "--------------------------------"
               cat $ErrorFile
               if [ "$MOUNT8kDEV" = "false" ];
               then
                  echo "   - $Iiso is invalid."
               else
                  echo "   - Your dvd is invalid."
               fi
               umount $MediaHome 2>/dev/null
               exit $SETUPIMAGEFAILED
            fi

         fi
         umount $MediaHome
      else 
         if [ "$LOCALREPO8k" = "true" ];
         then
             echo "upgrade8k: No local iso files under /repository/upload."
             exit $SETUPIMAGEFAILED
         fi
      fi
   #</CheckImageIso>
}

#---------------------------------------------------------------
# function: checkSIPports
# args    : None
# description:
#   checks if the node is listening on TCP SIP ports
#---------------------------------------------------------------
checkSIPports( )
{


   local confdir="/opt/SMAW/SMAWrtp/cust_conf"
   local portlist="
       ${confdir}/SrxSip.parm:Srx/Sip/IpPort               \
       ${confdir}/hiQCSTA.parm:hiQ/CSTA/ListenerPortNumber
   "
   ############################# OSV-4867 #############################
   local RTPParam_TLS_Disabled=$(su - srx -c "RtpCfgShow -r Srx/TLS_Disabled" | grep Value | awk -F":" '{print $2}' | sed -e 's/[ \t]//g')

   if [ ${PIPESTATUS[0]} -ne 0 ]
   then
       logstr "   - Could not get status of RTP parameter TLS_Disabled. Will consider it as RtpTrue."
   elif [ "X${RTPParam_TLS_Disabled}X" = "XRtpFalseX" ]
   then
       portlist="${portlist} ${confdir}/SrxSip.parm:Srx/Sip/IpPortTLS"
   fi
   ####################################################################

   zmod=${confdir}/zModifiedParms.parm
   for portidx in $portlist
   do
      nextfile=`echo $portidx | awk -F':' '{ print $1 }'`
      nextparm=`echo $portidx | awk -F':' '{ print $2 }'`
      nextport="`egrep \"$nextparm[ \t]\"  $zmod | awk -F'=' '{ print $2 }' | sed -e 's/ //g'`"
      if [ "$nextport" = "" ];
      then
         nextport="`egrep \"$nextparm[ \t]\"  $nextfile | awk -F'=' '{ print $2 }' | sed -e 's/ //g'`"
         if [ "$nextport" = "" ];
         then
            continue
         fi
      fi
      expr $nextport + 1 1>/dev/null 2>&1
      if [ $? -ne 0 ];
      then
         continue
      fi
      logstr "   - Checking $portidx,$nextport"
      lsof -i :$nextport 1>/dev/null 2>&1
      if [ $? -ne 0 ];
      then
         logstr "    - Failed to find process listening at port $portidx."
         exit $FAIL
      fi
	  
	 # for extra debugging uncomment the next line
	 # print_tk_debug $LOGFILE
   done
   

}


#---------------------------------------------------------------
# function: match_cfg_img_version
# args    : [-v --verbose]
# description:
#   checks if node.cfg has the same version with iso image
#---------------------------------------------------------------

match_cfg_img_version( )
{
  # Check if global variables about version are empty

  if [ -z ${__IMG_VERSION__} ] || [ -z ${__CFG_VERSION__} ];
  then
	read_cfg_iso_ver
	if [ ${?} -ne 0 ];
	then
		textncolor $BoldRed "upgrade8k: Unable to read global variables about ISO image and node.cfg versions."
        	logstate "UpgradeReset"
        	exit ${FAIL}
	fi
  fi

  # Verify that versions are compatible

  if [ ${__IMG_VERSION__[1]} -ne ${__CFG_VERSION__[1]} ];
  then
	textncolor $BoldRed "upgrade8k: ISO image version ${__IMG_VERSION__[1]} is incompatible with node.cfg build version ${__CFG_VERSION__[1]}."
	logstate "UpgradeReset"
	exit ${FAIL}
  else
	######## V8 minor version explicit workaround ########
	if [ ${__IMG_VERSION__[1]} -eq 8 ] && [ ${__IMG_VERSION__[2]} -ne ${__CFG_VERSION__[2]} ];
	then
		textncolor $BoldRed "upgrade8k: ISO image version ${__IMG_VERSION__[1]} ${__IMG_VERSION__[2]} is incompatible with node.cfg build version ${__CFG_VERSION__[1]} ${__CFG_VERSION__[2]}."
          	logstate "UpgradeReset"
          	exit ${FAIL}
      	fi
      	######################################################
  fi
}

# ----------------------------------------------------------------
# function: mapnafodev
# args    : none
# description:
#   In V6 or higher we have a new mapping( BO3621 ).
# ----------------------------------------------------------------

mapnafodev( ) {
   case $2 in
      bond0)
         eval ${1}=bonding_dev0
         ;;
      bond1)
         eval ${1}=bonding_dev1
         ;;
      bond2)
         eval ${1}=bonding_dev2
         ;;
      bond3)
         eval ${1}=cluster_dev
         ;;
      *)
         eval ${1}=$2
         ;;
   esac
}

#---------------------------------------------------------------
# function: openxchssh
# args    : None
# description:
#   opens ssh over xchannel.
#---------------------------------------------------------------

openxchssh( )
{
   logstate "OpenXChannelSSH"
   if [ "$mynode" = "$primhost" ];
   then
      nafosig="`cfgread nafo1| awk '{ print $2 }'`"
      nafoadmin="`cfgread nafo0| awk '{ print $2 }'`"
      if [ "$nafosig" = "$nafoadmin" ];
      then
         echo "upgrade8k:Admin and Signalling are shared. Opening $nafosig device" 
         nafoadminsecsn="`cfgread nafo0|  awk '{ print $10 }'`"
         admingw="`cfgread admin_1_gateway`"
         defaultrouter="`cfgread default_router`"
         mapnafodev nafoadmintag $nafoadmin
         admbondset="`cfgread $nafoadmintag`"
         ifconfig $nafoadmin up
         ifconfig $nafoadmin arp
         for admidx in $admbondset
         do
            echo "Bring up $admidx"
            ifconfig $admidx up
            ifconfig $admidx arp
         done
         if [ "$admingw" != "" ];
         then
            echo "Adding admin gw route : route add -net $nafoadminsecsn gw $admingw dev $nafoadmin"
            route add -net $nafoadminsecsn gw $admingw dev $nafoadmin
         fi
         if [ "$defaultrouter" != "" -a "$defaultrouter" != "$admingw" ];
         then
            echo "Adding default route : route add default gw $defaultrouter dev $nafoadmin"
            route add default gw $defaultrouter dev $nafoadmin
         fi
         route -n
      fi 1>>$LOGFILE 2>&1
      iptables-save>/tmp/ipts
      if [ $? -ne 0 ];
      then
         nrules=`iptables -nL  | egrep -vi "^chain|target|^$" | wc -l`
         if [ $nrules -eq 0 ];
         then
            logstate "OpenXChannelSSHEmpty"
            textncolor $Yellow "upgrade8k : No security rules in kernel."
         else
            logstate "OpenXChannelSSHFailed"
            textncolor $BoldRed "upgrade8k : Failed to open ssh over x-channel."
            exit $FAIL
         fi
      fi
      ExtendedChainName=xchcom
      ExtendedStrictChain=allcom
      ${IPTABLESPATH}iptables -F $ExtendedChainName
      chainstatus=$?
      if [ "$nafosig" = "$nafoadmin" -a $chainstatus -eq 0 ];
      then
         primip="`cfgread node_1_ip`"
         secip="`cfgread  node_2_ip`"
         iptables -A $ExtendedChainName -s $secip  -d $primip   -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
         iptables -A $ExtendedChainName -s $primip -d $secip    -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
         iptables -A $ExtendedChainName -s $secip  -d $primip   -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
         iptables -A $ExtendedChainName -s $primip -d $secip    -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
      fi
   fi
}

#---------------------------------------------------------------
# function: closexchssh
# args    : None
# description:
#   closes ssh over xchannel.
#---------------------------------------------------------------

closexchssh( )
{
   if [ "$mynode" = "$primhost" ];
   then
      nafosig="`cfgread nafo1| awk '{ print $2 }'`"
      nafoadmin="`cfgread nafo0| awk '{ print $2 }'`"
      if [ "$nafosig" = "$nafoadmin" ];
      then
         echo "upgrade8k: Admin and Signalling are shared. Closing $nafosig device" 1>>$LOGFILE 
         mapnafodev nafoadmintag $nafoadmin
         admbondset="`cfgread $nafoadmintag`"
         ifconfig $nafoadmin down
         ifconfig $nafoadmin -arp
         for admidx in $admbondset
         do
            ifconfig $admidx down
            ifconfig $admidx -arp
         done
      fi
      iptables-restore</tmp/ipts
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k : Failed to close ssh over x-channel."
         exit $FAIL
      fi
   fi
}

#---------------------------------------------------------------
# function: ommstate
# args    : None
# description:
#   sets up omm state for pcm to read.
#---------------------------------------------------------------

ommstate( )
{
   if [ "$testbed" != "cluster" -o "$mynode" != "$primhost" ];
   then
      return
   fi

   omnode=$1
   omstate=$2

   textncolor $BoldPurple "upgrade8k : Setting OMM state : $omstate"
   OmFile="/srx_share/OperationMode.txt"
   echo $omstate > ${OmFile}.tmp
   chown srx.$srxgroup ${OmFile}.tmp
   if [ "$omnode" = "remote" ];
   then
      scp ${OmFile}.tmp $othernode:/tmp
      ssh $othernode "mv $OmFile{.tmp,}"
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "Cannot set omm state."
         exit $FAIL
      fi
   else
      mv $OmFile{.tmp,}
   fi
}

#---------------------------------------------------------------
# function: checkprocs
# args    : None
# description:
# checks for healthy system.
#---------------------------------------------------------------

checkprocs( )
{
   inspectnode=$1
   inspectid=$2
   
   echo -n "   - Checking for any defunct processes on $inspectnode : "
   RtpBinDir=/opt/SMAW/SMAWrtp/bin
   if [ -f ${RtpBinDir}/nm_list_processes ];
   then
      RtpListCmd=${RtpBinDir}/nm_list_processes
   else
      if [ -f ${RtpBinDir}/RtpNmListProcesses ];
      then
         RtpListCmd=${RtpBinDir}/RtpNmListProcesses
      else
         RtpListCmd=""
      fi
   fi
   failedprocs=`su - srx -c "$RtpListCmd -a 2>/dev/null                             | \
                             grep $inspectid 2>/dev/null" | grep RTP_NM_NOTRUNNING  | \
                             awk '{ print $3 }' | grep -v $inspectnode`
   if [ "$failedprocs" = "" ];
   then
      echo "none."
   else
      for idx in $failedprocs
      do
            echo "      - $idx"
      done
      textncolor $BoldRed "upgrade8k: Check your system. "
      textncolor $BoldRed "upgrade8k: Some processes are not running on $inspectnode."
      logstate "UpgradeReset"
      exit $FAIL
   fi
}

#---------------------------------------------------------------
# function: setupsessiont
# args    : None
# description:
#   sets up session timers to be turned off during upgrades.
#---------------------------------------------------------------

setupsessiont( )
{
   #<DumpSessionTimer>
       touch /repository/sessiont.txt
       chown srx.${srxgroup} /repository/sessiont.txt
       su - srx -c "RtpCfgShow -r Srx/Sip/Session_Timer 1>/repository/sessiont.txt 2>/dev/null"
       if [ $? -eq 0 ];
       then
          chmod 744 /repository/sessiont.txt
          sessiont=`cat /repository/sessiont.txt 2>/dev/null | grep "^Value" | awk -F':' '{ print $2 }' | sed -e 's/ //g'`
          cat /repository/sessiont.txt 1>>$LOGFILE 2>&1
          if [ "$testbed" = "cluster" ];
          then
             scp -p /repository/sessiont.txt $othernode:/repository/sessiont.txt
          fi
       else
          sessiont=""
       fi
   #</DumpSessionTimer>
    cat << EOF > /repository/sessiontctrl
#!/usr/bin/expect --

# Note: assumes default (blank) password
proc login {} {
   expect "Login:"
   send "sysad\r"
   expect "CLI>"
}

# Send a CLI command and react to error message, if any
# The function appends \r - do not send it in the string
proc send_check_error { command } {
   send "\$command\r"
   expect {
      "*more details*: " {
         send "no\r"
         expect "CLI>"
      }
   "CLI>"
   }
}

set op  [lrange \$argv 0   0]
eval spawn RtpAdmCli -p 40 -x

login

send_check_error "confModifyParameter \"Srx/Sip/Session_Timer\" \"\$op\"\r"
send_check_error "confGetParameterInfo \"Srx/Sip/Session_Timer\"\r"
sleep 1

# Exit CLI (back to shell)
# At this point we expect to be at the CLI> prompt again
send "exit\r"
interact


EOF
   chmod 755 /repository/sessiontctrl
   if [ "$testbed" = "cluster" ];
   then
      scp -p /repository/sessiontctrl $othernode:/repository/sessiontctrl
   fi
   #<OffSessionTiming>
      if [ "$sessiont" != "" ];
      then
         su - srx -c "/repository/sessiontctrl \"NO\""
      fi 1>>$LOGFILE 2>&1
   #</OffSessionTiming>

}

#---------------------------------------------------------------
# function: setupprocctrl
# args    : None
# description:
#   this is used to setup process ctl scripts. used to start &
#   stop certain processes.
#---------------------------------------------------------------

setupprocctrl( )
{
      cat << EOF > /repository/procctrl
#!/usr/bin/expect --

# Note: assumes default (blank) password
proc login {} {
   expect "Login:"
   send "sysad\r"
   expect "CLI>"
}

# Send a CLI command and react to error message, if any
# The function appends \r - do not send it in the string
proc send_check_error { command } {
   send "\$command\r"
   expect {
      "*more details*: " {
         send "no\r"
         expect "CLI>"
      }
   "CLI>"
   }
}

proc stopprocess {proc} {
   send_check_error "procStopProcess \"\$proc\"\r"
}

proc startprocess {proc} {
   send_check_error "procStartConfiguredProcess \"\$proc\"\r"
}

set op  [lrange \$argv 0   0]
set p1  [lrange \$argv 1   1]
set p2  [lrange \$argv 2   2]
set p3  [lrange \$argv 3   3]
set p4  [lrange \$argv 4   4]
set p5  [lrange \$argv 5   5]
set p6  [lrange \$argv 6   6]
set p7  [lrange \$argv 7   7]
set p8  [lrange \$argv 8   8]
set p9  [lrange \$argv 9   9]
set p10 [lrange \$argv 10 10]
set p11 [lrange \$argv 11 11]
set p12 [lrange \$argv 12 12]
set p13 [lrange \$argv 13 13]
set p14 [lrange \$argv 14 14]
set p15 [lrange \$argv 15 15]
set p16 [lrange \$argv 16 16]
set proclist "\$p1 \$p2 \$p3 \$p4 \$p5 \$p6 \$p7 \$p8 \$p9 \$p10 \$p11 \$p12 \$p13 \$p14 \$p15 \$p16"

eval spawn RtpAdmCli -p 40 -x

login

if {\$op > 0} {
   foreach proc \$proclist {
        startprocess "\$proc"
   }
} else {
   foreach proc \$proclist {
         stopprocess  "\$proc"
   }
}
sleep 1

# Exit CLI (back to shell)
# At this point we expect to be at the CLI> prompt again
send "exit\r"
interact

EOF
   chmod 755 /repository/procctrl
   textncolor $Yellow "upgrade8k: Distributing process control across nodes."
   scp -p /repository/procctrl $othernode:/repository/procctrl

}

#---------------------------------------------------------------
# function: setupcdr
# args    : None
# description:
#   This is for closing all uce ctx and sending cdr's.
#   Sorry, had to build on existing code. 
#---------------------------------------------------------------

setupcdr( ) {

   #[-]. Build closectx.
   synccdr=${1:-"true"}
   grep -qi "^RtpTicMgr" /opt/SMAW/SMAWrtp/conf/RtpTic.tcn
   if [ $? -eq 0 ];
   then
      if [ "$synccdr" = "true" ];
      then
         cdrproc=RtpTicMgr02
      else
         cdrproc=RtpTicMgr01
      fi
   else
      if [ "$synccdr" = "true" ];
      then
         cdrproc=RtpTicWrite02
      else
         cdrproc=RtpTicWrite01
      fi
   fi
   rm -f /tmp/closectx /tmp/ctxutil.help /tmp/cdrwrite
   su - srx -c "/unisphere/srx3000/callp/bin/ctxutil -dev << EOF 1>/tmp/ctxutil.help 2>/dev/null

0
EOF
   " 

   cdroption=""
   cat /tmp/ctxutil.help | grep "Close all open UCE contexts and Send CDR" | grep -q "203\."
   if [ $? -eq 0 ];
   then
      cdroption="203"
   fi
   cat /tmp/ctxutil.help | grep "Close all open UCE contexts and Send CDR" | grep -q "16\."
   if [ $? -eq 0 ];
   then
      cdroption="16"
   fi
   
   if [ "$cdroption" != "" ];
   then
      cat << EOF > /tmp/closectx 
#!/bin/sh
   echo "   - Preparing to close all active uce contexts."
   if osv_version.sh --major compare sys ge V5 && [ -x /opt/SMAW/SMAWrtp/bin/RtpTicTool ];
   then
      echo "   - Ticket state before closing contexts."
      su - srx -c "/opt/SMAW/SMAWrtp/bin/RtpTicTool"
   fi
   su - srx -c "/unisphere/srx3000/callp/bin/ctxutil -dev << CDREOF
$cdroption
y

0
  
CDREOF
   "
   if osv_version.sh --major compare sys ge V5 && [ -x /opt/SMAW/SMAWrtp/bin/RtpTicTool ];
   then
      echo "   - Ticket state after closing contexts."
      su - srx -c "/opt/SMAW/SMAWrtp/bin/RtpTicTool"
   fi
   su - srx -c "/tmp/cdrwrite"
   sleep 8
EOF
      cat << EOF > /tmp/cdrwrite
#!/usr/bin/expect --

# Note: assumes default (blank) password
proc login {} {
   expect "Login:"
   send "sysad\r"
   expect "CLI>"
}

# Send a CLI command and react to error message, if any
# The function appends \r - do not send it in the string
proc send_check_error { command } {
   send "\$command\r"
   expect {
      "*more details*: " {
         send "no\r"
         expect "CLI>"
      }
   "CLI>"
   }
}

proc stopprocess {} {
   send_check_error "procStopProcess \"$cdrproc\"\r"
}

proc startprocess {} {
   send_check_error "procStartConfiguredProcess \"$cdrproc\"\r"
}

eval spawn RtpAdmCli -p 40 -x

login

stopprocess
sleep 1
startprocess

# Exit CLI (back to shell)
# At this point we expect to be at the CLI> prompt again
send "exit\r"
interact

EOF

      chmod 755 /tmp/closectx
      chmod 755 /tmp/cdrwrite
      if [ "$synccdr" = "true" ];
      then
         scp -p /tmp/closectx $othernode:/tmp/closectx
         scp -p /tmp/cdrwrite $othernode:/tmp/cdrwrite
      fi
   fi

}

# ---------------------------------------------------------------
# function: getDbaPassword
# args    : $1 can be <decrypted>, <encrypted> or empty
# description:
#   Gets password of the dba DB user.
#   If the first arg is "decrypted" means that we should read the password
#   from a file where the dba passwd is stored in plain text (old solid engines)
#
#   If the first arg is "encrypted" means that we should read the password
#   from a file where the dba passwd is stored in encrypted format
#
#   In case the is no arg, the already set password is returned
# ---------------------------------------------------------------

getDbaPassword ( ) {
   local passwd_type=$1
   local tmp_dba_pass

   case ${passwd_type} in
      "")
         echo "$dbapasswd"
         return 0
         ;;
      'encrypted')
         $DBCRYPT dec ${DBA_PASSWDFILE} /tmp/dba.secrets.dec 1>/dev/null 2>>$LOGFILE
         tmp_dba_pass=$(cat /tmp/dba.secrets.dec 2>/dev/null)
         rm -f /tmp/dba.secrets.dec
         ;;
      'decrypted')
         tmp_dba_pass=$(cat ${DBA_PASSWDFILE} 2>/dev/null)
         ;;
      *)
         return 1
   esac
   echo "${tmp_dba_pass}"
}

# ---------------------------------------------------------------
# function: getDbaPassword
# args    : $1 the new dba password
# description:
#   Sets dba password (dbapasswd variable).
# ---------------------------------------------------------------

setDbaPassword ( ) {
   dbapasswd=$(formatStringAsShellInput ${1:-"dba"})
}

#---------------------------------------------------------------
# function: sethsbstate
# args    : None
# description:
#    setup the hsb state, for solid db.
#---------------------------------------------------------------

sethsbstate( )
{
   SOLBINDIR=/opt/solid/bin
   hsbstate=$1
   if [ "$hsbstate" != "primary" -a "$hsbstate" != "secondary" ];
   then
      return
   fi
   if osv_version.sh --major compare sys ge V6;
   then
      setDbaPassword $(getDbaPassword encrypted)

      solcon=${SOLBINDIR}/solcon_solid
      soldd=${SOLBINDIR}/soldd_solid
      solexp=${SOLBINDIR}/solexp_solid
      solload=${SOLBINDIR}/solload_solid
      solsql=${SOLBINDIR}/solsql_solid

   else
      setDbaPassword $(getDbaPassword decrypted)

      solcon=${SOLBINDIR}/solcon
      soldd=${SOLBINDIR}/soldd
      solexp=${SOLBINDIR}/solexp
      solload=${SOLBINDIR}/solload
      solsql=${SOLBINDIR}/solsql
   fi
   su - solid -c "$solsql -a -e \"admin command 'hsb switch primary' \" \"tcp 16760\" dba $(getDbaPassword)" 1>>$LOGFILE 2>&1
}

#---------------------------------------------------------------
# function: setupswitch
# args    : None
# description:
#   sets up commit sequence. firewall's node#2, node#1 to handle
#   traffic.
#---------------------------------------------------------------

setupswitch( ) {
   textncolor $BoldPurple "upgrade8k : Switching traffic."
   logstate "TrafficSwitchBegin"
   #<CheckTestBed>
   if [ "$mynode" != "$primhost" ];
   then
      echo "Aborted."
      textncolor $BoldRed "Run upgrade8k from ${primhost} only."
      exit $FAIL
   fi
   #<CheckTestBed>
   if [ "$testbed" != "cluster" ];
   then
      echo "upgrade8k: This interface is valid only on a cluster."
      exit $FAIL
   fi
   #</CheckTestBed>

   mylayout=`/unisphere/srx3000/srx/bin/sync8k -q none`
   mypart="`echo $mylayout | awk -F ',' '{ print $1 }'   \
                           | sed -e 's/secondary.*/\u&/' \
                                 -e 's/primary.*/\u&/'   \
                                 -e 's/://g'`"
   logstate "$mypart"

   #<CheckPorts>
   checkSIPports 
   #</CheckPorts>

   #<CheckQuietMode>
      if [ -f $LIVEQUIET ];
      then
         export QUIETINSTALL8k=true
      fi
   #</CheckQuietMode>

   if [ "$QUIETINSTALL8k" != "true" ];
   then
      while ( true )
      do
         echo -n "Do you wish to continue (yes/no)? "
         clearstdin
         read answer
         if [ "$answer" = "yes" -o "$answer" = "no" ];
         then
            if [ "$answer" = "no" ];
            then
               echo "Aborted."
               exit $FAIL
            else
               break;
            fi
         fi
         continue
      done
   fi

   dumparpcache "before setupswitch"
   touch $LIVESWITCH
   if [ "$HWMIGRATION" = "true" ];
   then
      logstr "   - Switching with new hardware."
      touch $HWSWITCH
   fi
   openxchssh
   #<CheckAdminNw>
      checkcount=0
      while [ $checkcount -le 16 ];
      do
         ssh  -o ConnectTimeout=8 $othernode "ls" 1>/dev/null 2>&1        
         if [ $? -eq 0 ];
         then
            logstr "   - Your partner admin nework($othernode) is reachable at `date`."
            break;
         fi
         logstr "   - Urgent.Your partner node($othernode) is not reachable at `date`."
         cleanarpcache
         sleep 8
         checkcount=$[checkcount+1]
      done
   #</CheckAdminNw>
   #<DumpSessionTimer>
       su - srx -c "RtpCfgShow -r Srx/Sip/Session_Timer 1>/repository/sessiont.txt 2>/dev/null"
       if [ $? -eq 0 ];
       then
          chmod 744 /repository/sessiont.txt
          sessiont=`cat /repository/sessiont.txt 2>/dev/null | grep "^Value" | awk -F':' '{ print $2 }' | sed -e 's/ //g'`
          cat /repository/sessiont.txt 1>>$LOGFILE 2>&1
       else
          sessiont=""
       fi
       #<OffSessionTiming>
          if [ "$sessiont" != "" ];
          then
             su - srx -c "/repository/sessiontctrl \"NO\""
          fi 1>>$LOGFILE 2>&1
       #</OffSessionTiming>
       scp -p $othernode:/repository/sessiont.txt /repository/sessiont.txt 2>/dev/null
   #</DumpSessionTimer>

   logstate "SwitchXchRemoteStrict"
   nice -n -20 ssh $othernode "split8k -fwstrict"
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: cannot split the nodes($othernode)."
      nice -n -20 ssh $othernode "join8k -nfw -join"
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: cannot join node into operation.($othernode)."
      fi
      closexchssh
      exit $FAIL
   fi
   logstate "JoinLocalXchComplete"
   nice -n -20 join8k -nfw -fwxch -join
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: cannot join node into operation.($mynode)."
   fi

   logstate "RestartSnort"

   #<RestartSnort>
   systemctl restart IDS.service 1>/dev/null 2>&1 || \
   textncolor $BoldRed "upgrade8k: Failed to restart IDS service"
   #</RestartSnort>

   #<Publisher>
   if [ "$mynode" = "$primhost" ];
   then
      nafosigdev="`cfgread nafo1| awk '{ print $2 }'`"
   else
      nafosigdev="`cfgread nafo1| awk '{ print $3 }'`"
   fi
   cat << EOF > /usr/bin/publisher
#!/bin/sh
   devidx=$nafosigdev
   ipv4list="\`ip addr list \$devidx | grep "inet " | cut -d' ' -f6 | cut -d/ -f1\`"
   ipv6list="\`ip addr list \$devidx | grep "inet6" | cut -d' ' -f6\`"
   arpcount=2
   echo "`date`" >> /tmp/publisher_upgrade.log
   while ( true )
   do
      if [ -f /log/publisher.lock ];
      then
         rm -f /log/publisher.lock ];
         break;
      fi
      for ipidx in \$ipv4list
      do
         {
            loopcount=0
            while [ \$loopcount -le \$arpcount ];
            do
               arping -U -c 1 -I \$devidx \$ipidx
               loopcount=\$[loopcount+1]
            done
         } 1>/dev/null 2>&1 
      done
      sleep 8
   done
   exit 0
EOF
   chmod 777 /usr/bin/publisher
   nohup /usr/bin/publisher 1>/dev/null 2>&1 & 
   logstate "InitiatePublisher"
   #</Publisher>

   #<License>
      logstr "   - Reimporting any valid licenses, if any."
      {
         if ls /repository/license/*.lic 1> /dev/null 2>&1;
         then
            # OSV-9542
            logstr "   - Re-installing new license file."
            cp /repository/license/*.lic /opt/unisphere/srx3000/cla/import
         else
            cp /repository/license/*.xml /opt/unisphere/srx3000/cla/import
         fi
         rm -rf /repository/license
      }   2>/dev/null
   #</License>

   sethsbstate primary 
   dumparpcache "after setupswitch"

   logstate "TrafficSwitchEnd"
   sync
}

#---------------------------------------------------------------
# function: setupcommit
# args    : None
# description:
#   commits the transactions. Installs load on 2nd node.
#---------------------------------------------------------------

setupcommit( )
{
   textncolor $BoldPurple "upgrade8k : Commiting upgrade."
   echo "Command: upgrade8k $ARGLIST"  1>>$LOGFILE 2>&1
   logstate "CommitBegin"
   #<CheckTestBed>
   if [ "$mynode" != "$primhost" ];
   then
      echo "Aborted."
      textncolor $BoldRed "Run upgrade8k from ${primhost} only."
      exit $FAIL
   fi
   #<CheckTestBed>
   if [ "$testbed" != "cluster" ];
   then
      echo "upgrade8k: This interface is valid only on a cluster."
      exit $FAIL
   fi
   #</CheckTestBed>

   #<CheckQuietMode>
      if [ -f $LIVEQUIET ];
      then
         export QUIETINSTALL8k=true
      fi
   #</CheckQuietMode>

   #<CheckSwitch>
      if [ ! -f $LIVESWITCH ];
      then
         echo "upgrade8k: This interface is valid only after a traffic switch."
         exit $FAIL
      fi
   #<CheckSwitch>

   if [ "$QUIETINSTALL8k" != "true" ];
   then
      while ( true )
      do
         echo -n "Do you wish to continue (yes/no)? "
         clearstdin
         read answer
         if [ "$answer" = "yes" -o "$answer" = "no" ];
         then
            if [ "$answer" = "no" ];
            then
               echo "Aborted."
               exit $FAIL
            else
               break;
            fi
         fi
         continue
      done
   fi

   dumparpcache "before setupcommit"
   openxchssh
   rm -f $LIVEQUIET
   rm -f $LIVESWITCH
   rm -f $HWSWITCH
   textncolor $BoldCyan "upgrade8k: Terminating publisher."
   #<Publisher>
      pgrep publisher 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         logstate "TerminatePublisher"
         touch /log/publisher.lock
         sleep 8
         killproc -t 10 publisher
         rm -f /usr/bin/publisher
      fi
   #</Publisher>

   #<GetSessionT>
      sessiont=""
      if [ -f /repository/sessiont.txt ];
      then
         sessiont=`cat /repository/sessiont.txt 2>/dev/null | grep "^Value" | awk -F':' '{ print $2 }' | sed -e 's/ //g'`
      fi
   #</GetSessionT>

   textncolor $BoldCyan "upgrade8k: Closing all call contexts on $othernode."
   #<DumpKnownCdr>
      ssh $othernode "
         if [ -x /tmp/closectx ];
         then
            /tmp/closectx
         fi
      " 1>>$LOGFILE 2>&1
   #</DumpKnownCdr>

   nice -n -20 join8k -nfw 
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: cannot join node into operation.($mynode)."
      exit $FAIL
   fi
   #<RestoreSessionT>
      if [ "$sessiont" != "" ];
      then
         echo "Srx/Sip/Session_Timer=$sessiont"
         su - srx -c "/repository/sessiontctrl $sessiont"
      fi 1>>$LOGFILE 2>&1 
   #</RestoreSessionT>

   logstate "InstallNodeTwo"
   sync
   if [ "$HWMIGRATION" = "true" ];
   then
      textncolor $Yellow "upgrade8k: Node#2 ($othernode) will halt."
      textncolor $Yellow "upgrade8k: Replace new hardware with DVD and USB. Choose Install."
      cmd="halt -p -f"
   else
      textncolor $Yellow "upgrade8k: Node#2 ($othernode) will reboot now to be installed."
      cmd="reboot -f"
   fi
   nohup ssh $othernode "sync;$cmd" 1>/dev/null 2>&1 &
   #Give some time to the remote system to poweroff.
   sleep 10
   if osv_version.sh --major compare sys ge V9;
   then
      # wait the other node to reboot

      nafo_admin=`cfgread nafo0| awk '{print $2}'` 
      nafo_xch=`cfgread nafo3| awk '{print $2}'` 
            
      if [ "$nafo_admin" = "$nafo_xch" ]
      then 
         #<CheckOtherNode>
         textncolor $Yellow "Xchannel share with admin. Wait for remote node to start rebooting and restore new keys"
         checkcount=0
         local rep
         while [ $checkcount -le 16 ];
         do
            #Timeout should be greater than ConnectTimeout x 2.
            err=`timeout 20 ssh  -o ConnectTimeout=8 $othernode "ls" 2>&1 1>/dev/null`
            rep="$?"
            case $rep in
            124)
                textncolor $Yellow "SSH timeout at `date`."
                echo "SSH has returned: $err."
                sleep 8
                checkcount=$[checkcount+1]
            ;;
            255)
                textncolor $Yellow "Remote node ($othernode) is not reachable at `date`."
                echo "SSH has returned: $err."
                break;
            ;;
            0)
                textncolor $Yellow "Remote node($othernode) is reachable at `date`."
                sleep 8
                checkcount=$[checkcount+1]
            ;;
            *)
                echo "SSH return code $rep at `date` with return."
                echo "SSH has returned: $err."
                sleep 8
                checkcount=$[checkcount+1]
            ;;
            esac
         done
         if [ $checkcount -gt 16 ]; then
            textncolor $Yellow "SSH attempts have exceeded the limit at `date`."
         fi
         #</CheckOtherNode>

      fi
   fi
   
   #<ipsec_keys>
   textncolor $BoldPurple "upgrade8k : applying new ipsec keys"
   setkey -f /etc/sec/setkey.conf

   if osv_version.sh --major compare sys ge V9 && [ -x /usr/local/bin/.setipsec ];
   then
      /usr/local/bin/.setipsec -encrypt  2>&1 >/dev/null 
      textncolor $BoldPurple "upgrade8k : encrypting ipsec keys"     
   fi
   #</ipsec_keys>
   if [ -f /img/rootimg/etc/init.d/zorig/bz_node_com_test ];
   then
      mv -f /img/rootimg/etc/init.d/zorig/bz_node_com_test /img/rootimg/etc/init.d/bz_node_com_test
      chroot /img/rootimg insserv bz_node_com_test
      chroot /img/rootimg insserv 
   fi 2>/dev/null

   sethsbstate primary 
   dumparpcache "after setupcommit"
   logstate "CommitEnd"
}

#---------------------------------------------------------------
# function: setupfallback
# args    : None
# description:
#    rolls back to the old state.
#---------------------------------------------------------------

setupfallback( ) {
   local ACTIVATE_IN_FALLBACK=false

   #Reset diagnostics
   if [ -f $REPOSITORY/diagnostics.dbg ];
   then
      upgrade_diagnostics_disable ALL
   fi
   upgrade_diagnostics_reset
   if [ "$mynode" = "$primhost" ] && [ "$testbed" = "cluster" ];
   then
      upgrade_diagnostics_reset $othernode
   fi

   textncolor $BoldPurple "upgrade8k : Attempting fallback to original state."
   echo "Command: upgrade8k $ARGLIST"  1>>$LOGFILE 2>&1
   logstate "FallbackBegin"
   {
      echo "upgrade8k: Checking chain xchcom."
      iptables -nL xchcom 
   } 1>>$LOGFILE 2>&1
   xchchain=$?
   #<CheckTestBed>
   if [ "$mynode" != "$primhost" ];
   then
      echo "Aborted."
      textncolor $BoldRed "Run upgrade8k from ${primhost} only."
      logstate "UpgradeReset"
      exit $FAIL
   fi
   #<CheckTestBed>
   if [ "$testbed" != "cluster" ];
   then
      echo "upgrade8k: This interface is valid only on a cluster."
      logstate "UpgradeReset"
      exit $FAIL
   fi

   if [ "$FORCE8k" = "true" ];
   then
      force="-f"
   fi

   #<GetSessionT>
      sessiont=""
      if [ -f /repository/sessiont.txt ];
      then
         sessiont=`cat /repository/sessiont.txt 2>/dev/null | grep "^Value" | awk -F':' '{ print $2 }' | sed -e 's/ //g'`
      fi
   #</GetSessionT>

   #<CheckQuietMode>
      if [ -f $LIVEQUIET ];
      then
         export QUIETINSTALL8k=true
      fi
   #</CheckQuietMode>

   logstate "FallbackBeginPrompt"
   if [ "$QUIETINSTALL8k" != "true" ];
   then
      while ( true )
      do
         echo -n "Do you wish to continue (yes/no)? "
         clearstdin
         read answer
         if [ "$answer" = "yes" -o "$answer" = "no" ];
         then
            if [ "$answer" = "no" ];
            then
               echo "Aborted."
               logstate "UpgradeReset"
               exit $FAIL
            else
               break;
            fi
         fi
         continue
      done
   fi
   logstate "FallbackBeginAccept"

   dumparpcache "before setupfallback"
   openxchssh
   rm -f $LIVEQUIET
   rm -f $LIVESWITCH
   rm -f $HWSWITCH
   #<Publisher>
      pgrep publisher 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         logstate "TerminatePublisher"
         touch /log/publisher.lock
         sleep 8
         killproc -t 10 publisher
         rm -f /usr/bin/publisher
      fi
   #</Publisher>

   activemode="`cat /img/logimg/${activeimg}/upgrade.lock 2>/dev/null | head -1`"
   passivemode="`cat /img/logimg/${passiveimg}/upgrade.lock 2>/dev/null | head -1`"
   if [ "$activemode" = "" -a "$passivemode" = "" ];
   then
      iptables -nL firewall 1>/dev/null 2>&1
      if [ $? -eq 0 -o "$FORCE8k" = "true" ];
      then
         passivemode="OutageFree"
      fi
   fi

   #<IpSecKeys>
   setkey -D | egrep -q "esp|ah"
   keystatus=$?
   if [ -f /etc/sec/setkey.conf -a $keystatus -ne 0 ];
   then
      setkey -f /etc/sec/setkey.conf
   else 
      if osv_version.sh --major compare sys ge V9 && [ -f /etc/sec/.setkey.conf ] && [ $keystatus -ne 0 ];
      then
         /usr/local/bin/.setipsec -exe
         ipsec_ret=$?
         textncolor $BoldPurple "upgrade8k : Setting ipsec keys from encrypted store, status(${ipsec_ret})" 
      fi	
   fi
   #</IpSecKeys>

   if [ -f /etc/init.d/zorig/bz_node_com_test ];
   then
      mv -f /etc/init.d/zorig/bz_node_com_test /etc/init.d/bz_node_com_test 
      insserv bz_node_com_test
      insserv 
   fi 2>/dev/null

   if [ -f /img/rootimg/etc/init.d/zorig/bz_node_com_test ];
   then
      mv -f /img/rootimg/etc/init.d/zorig/bz_node_com_test /img/rootimg/etc/init.d/bz_node_com_test
      chroot /img/rootimg insserv bz_node_com_test
      chroot /img/rootimg insserv 
   fi 2>/dev/null

   logstate "UpgradeReset"
   upgrade8k $force -reset
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: Outage free upgrade reset failed on $mynode."
   fi
   if [ "$activemode" != "OutageFree" -a "$passivemode" != "OutageFree" ];
   then
      echo "upgrade8k: No live upgrade in progress."
      srxctrl 4 nc
      {
         if [ "$sessiont" != "" ];
         then
            echo "Srx/Sip/Session_Timer=$sessiont"
            su - srx -c "/repository/sessiontctrl $sessiont"
         fi
         ssh $othernode -o ConnectTimeout=8 "su - srx -c \"/repository/procctrl 1 $procsecmap\""
      } 1>>$LOGFILE 2>&1
      exit $?
   fi
   #</CheckTestBed>
   if [ "$activemode" = "OutageFree" ];
   then
      textncolor $BoldRed "upgrade8k: Your active image initiated live upgrade."
      #[X] Note. In this state you have not started installing target.
      logstate "JoinLocalXChannel"
      nice -n -20 join8k -nfw -join
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Outage free upgrade join failed($mynode)."
         logstate "UpgradeReset"
         exit $FAIL
      fi
      logstate "JoinRemoteXChannel"
      nice -n -20 ssh $othernode  -o ConnectTimeout=8 "join8k -nfw -join"
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Outage free upgrade join failed.($othernode)."
         logstate "UpgradeReset"
         exit $FAIL
      fi
      upgrade8k $force -reset
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Outage free upgrade reset failed on $mynode."
      fi

      #<Wait4ClusterUp>
      logstate "HeartbeatCheckBegin"
      echo -n "[xtree]: Waiting for cluster to come online : "
      nodecount=2
      while ( true )
      do
         if osv_version.sh --major compare sys ge V5;
         then
            nodesonline=`crmmon -1 2>/dev/null | grep "^Node: " | \
                         awk -F ':' '{ print $3 }' | sed -e 's/[ ]*//g' | grep online | wc -l`
         else
            nodesonline=`cftool -n 2>/dev/null | egrep "^${mynode}|^${othernode}" | \
                         awk '{ print $3 }' | sed -e 's/[ ]*//g' | grep UP | wc -l`
         fi
         if [ "$nodesonline" -eq $nodecount ];
         then
            echo "ok"
            break
         fi
         sleep 2
      done
      sleep 4
      echo "High availability state :"
      echo "-------------------------"
      if osv_version.sh --major compare sys ge V5;
      then
         crmmon -1
      else
         cftool -n
      fi
      logstate "HeartbeatCheckEnd"
      #</Wait4ClusterUp>
      
      #<FinishActivation>
          logstate "InitActivation"
         /unisphere/srx3000/srx/bin/activate8k -done
      #</FinishActivation>

      #<RestartSnort>
      {
         systemctl restart IDS.service
         ssh $othernode -o ConnectTimeout=8 "
             systemctl restart IDS.service "
      } 1>>$LOGFILE 2>&1
      #</RestartSnort>

      logstate "BringSystemStateFour"
      srxctrl 4 nc
      {   
         su - srx -c "/repository/procctrl 1 $procprimmap"
         ssh $othernode -o ConnectTimeout=8 "su - srx -c \"/repository/procctrl 1 $procsecmap\""
         if [ "$sessiont" != "" ];
         then
            echo "Srx/Sip/Session_Timer=$sessiont"
            su - srx -c "/repository/sessiontctrl $sessiont"
         fi 
      } 1>>$LOGFILE 2>&1
   fi

   if [ "$passivemode" = "OutageFree" ];
   then
      textncolor $BoldRed "upgrade8k: Your fallback image initiated live upgrade."
      textncolor $BoldPurple "upgrade8k: Initiating fallback reload."
      killproc srxctrl
      logstate "ResetBootParms"
      echo "2 0 /log/startup_srx.log /log/startup_rtp.log" > \
                 /img/unisphereimg/${passiveimg}/srx3000/srx/startup/srxBootParams

      logstate "ResetUpgradeContents"
      upgrade8k $force -reset
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Outage free upgrade reset failed on $mynode."
      fi

      logstate "InitiateActivateFallback"
      /unisphere/srx3000/srx/bin/activate8k -f -local -manual
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Initiating fallback reload failed($mynode)."
         logstate "UpgradeReset"
         exit $FAIL
      else
         ACTIVATE_IN_FALLBACK=true
      fi

      #<Restore old ipsec>
      # In V9 we create a fresh set of ipsec keys so we need to  restore the old ipsec keys 
      # so we can ssh to partner node, which is in source load.
      if osv_version.sh --major compare sys ge V9;
      then
         restoreSecKeys  "/img/rootimg/etc/sec/setkey.conf.old_liveupgrade" 
      fi
      #</Restore old ipsec>
      logstate "SplitXChLocalStrict"
      nice -n -20 split8k -fwstrict
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: srxctrl cannot split($mynode).Will continue."
      fi
      logstate "JoinRemoteXChannel"
      nice -n -20 ssh $othernode -o ConnectTimeout=8 "join8k -nfw"
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Outage free upgrade join failed.($othernode)."
      fi

      #<RestartSnort>
      {
         ssh $othernode -o ConnectTimeout=8 "
             systemctl restart IDS.service "
      } 1>>$LOGFILE 2>&1
      #</RestartSnort>

      #<RestartProcs>
      {   
         scp -p $othernode:/repository/sessiont.txt /repository/sessiont.txt 2>/dev/null
         ssh $othernode -o ConnectTimeout=8 "su - srx -c \"/repository/procctrl 1 $procsecmap\""
         sessiont=`cat /repository/sessiont.txt 2>/dev/null | grep "^Value" | awk -F':' '{ print $2 }' | sed -e 's/ //g'`
         echo "Srx/Sip/Session_Timer=$sessiont"
         if [ "$sessiont" != "" ];
         then
            ssh $othernode -o ConnectTimeout=8 "
               su - srx -c \"
                     /repository/sessiontctrl $sessiont
               \"
            "
         fi
      } 1>>$LOGFILE 2>&1
      #</RestartProcs>

      #<DumpKnownCdr>
      setupcdr false
      if [ -x /tmp/closectx ];
      then
         /tmp/closectx
      fi 1>>$LOGFILE 2>&1
      #</DumpKnownCdr>

      if [ $xchchain -ne 0 ];
      then
         logstate "JoinLocalHeartbeat"
         nice -n -20 join8k -join
         if [ $? -ne 0 ];
         then
            textncolor $BoldRed "upgrade8k: Outage free upgrade join failed.($mynode)."
            exit $FAIL
         fi

         textncolor $BoldCyan "upgrade8k: Bringing system to state#2."
         logstate "BringSystemStateTwo"
         /unisphere/srx3000/srx/startup/srxctrl 2 nc
         if [ $? -ne 0 ];
         then
            textncolor $BoldRed "upgrade8k: srxctrl cannot stop($mynode)."
            logstate "UpgradeReset"
         fi

         logstate "StopLocalHeartbeat"
         nice -n -20 split8k -split
         if [ $? -ne 0 ];
         then
            textncolor $BoldRed "upgrade8k: Outage free upgrade split failed on $mynode."
            killproc heartbeat
         fi
      fi
      
      if [ "${ACTIVATE_IN_FALLBACK}" = "true" ]
      then
         textncolor $BoldRed "upgrade8k: already initiated fallback reload on ($mynode)."
      else
         logstate "InitiateActivateFallback"
         /unisphere/srx3000/srx/bin/activate8k -f -local -manual
         if [ $? -ne 0 ];
         then
            textncolor $BoldRed "upgrade8k: Initiating fallback reload failed($mynode)."
            logstate "UpgradeReset"
            exit $FAIL
         fi
      fi
      logstate "JoinRemoteHeartbeat"
      nice -n -20 ssh $othernode -o ConnectTimeout=8 "join8k -join"

      sync
      logstate "InitiateActivateFallbackReboot"
      if [ "$HWMIGRATION" = "true" ];
      then
         textncolor $BoldRed "upgrade8k: Node#1 ($mynode) will halt."
         textncolor $BoldRed "upgrade8k: Replace the old hardware."
         rm -f $HWLOCK $HWSWITCH
         halt -p -f
      else
         /unisphere/srx3000/srx/bin/activate8k -f -local -reboot
      fi
      sync
   fi
   dumparpcache "after setupfallback"

   logstate "FallbackEnd"
   logstate "UpgradeReset"
   textncolor $Yellow "upgrade8k: Fallback complete."
   echo "Done."
}

#---------------------------------------------------------------
# function: checkgw
# args    : None
# description:
#---------------------------------------------------------------

checkgw( ) {
   gwcheck=$1
   nodeid=$2
   routetags="admin_${nodeid}_gateway signaling_${nodeid}_gateway billing_${nodeid}_gateway xch_${nodeid}_gateway"
   if [ "$nodeid" = "1" ];
   then
      routetags="$routetags default_router"
   else
      routetags="$routetags default_router_2"
   fi
   for gwidx in $routetags
   do
      gwidxval=`cfgread $gwidx`
      if [ "$gwidxval" != "" ];
      then
         egrep -q ${gwidxval} $gwcheck
         if [ $? -ne 0 ];
         then
            ping -c 4 ${gwidxval} 1>/dev/null 2>&1
            if [ $? -ne 0 ];
            then
               arp -an | egrep -q "(${gwidxval})"
               if [ $? -ne 0 ];
               then
                  echo "Target Tag: $gwidx(${gwidxval}) not in current routing table." >> /tmp/routes.missing
               fi
            fi
         fi
      fi
   done
}

#---------------------------------------------------------------
# function: checkdualmedia
# args    : None
# description:
#   checks if the repo & dvd are both present. If so, we check
#   the versions. If the dvd version is higher than the repo 
#   version we may have a conflict.
#---------------------------------------------------------------

checkdualmedia( )
{
    nisos=`ls /repository/upload/*.iso 2>/dev/null | wc -l`
    if [ $nisos -eq 0 ];
    then
       textncolor $BoldRed "upgrade8k: No images found in repository."
       exit $FAIL
    fi
    if [ $nisos -ge 2 ];
    then
       textncolor $BoldRed "upgrade8k: Too many isos found in repository."
       logstate "UpgradeReset"
       exit $FAIL
    fi
    imageiso=`ls /repository/upload/*.iso`
    mount -t iso9660 -o loop,ro $imageiso /mnt
       if [ -f /mnt/version -a -d /mnt/boot -a -d /mnt/image ];
       then
          isoload=`cat /mnt/version | grep "^Label" | awk -F':' '{ print $2 }' | sed -e 's/ //g'`
       else
          umount /mnt
          textncolor $BoldRed "upgrade8k: iso is not an image iso?."
          logstate "UpgradeReset"
          exit $FAIL
       fi
    umount /mnt
    dvdload=""
    for sridx in hda sr0 sr1
    do
       mount -o ro /dev/${sridx} /mnt 2>/dev/null
       status=$?
       if [ $status -eq 0 ];
       then
          if [ -f /mnt/version -a -d /mnt/boot -a -d /mnt/image ];
          then
             dvdload=`cat /mnt/version 2>/dev/null | grep "^Label" | awk -F':' '{ print $2 }' | sed -e 's/ //g'`
             umount /mnt
             break;
          else
             umount /mnt
          fi
       fi
    done
    if [ "$dvdload" != "" ];
    then
       if [ "$isoload" != "$dvdload" -o "$isoload" = "$dvdload" ];
       then
          textncolor $BoldRed "upgrade8k: Dual media detected."
          echo "   isoload - $isoload on /repository/upload."
          echo "   dvdload - $dvdload physical media on drive."
          textncolor $BoldRed "upgrade8k: Remove one of the above media."
          logstate "UpgradeReset"
          exit $FAIL
       fi
    fi
}

#---------------------------------------------------------------
# function: checkcfgsrc
# args    : None
# description:
#   For virtual systems we check if there are multiple sources
#   of node.cfg. If so we do not let the system upgrade.
#---------------------------------------------------------------

checkcfgsrc( )
{
   if [ "$hwplatform" = "Virtual" -o "$hwid" = "V" -o "$hwid" = "v" -o "$VAPP8k" = "true" -o "$virtualized" = "1" ];
   then
      mediafound=false
      for idx in fd0 hda hdb hdc hdd hde sr0 sr1
      do
         mount /dev/${idx} /mnt
            if [ $? -eq 0 ];
            then
               if [ -f /mnt/node.cfg.primary -o -f /mnt/node.cfg.secondary ];
               then
                  if [ "$mediafound" = "true" ];
                  then
                     textncolor $BoldRed "upgrade8k: Hmm. You have many sources of node.cfg."          
                     textncolor $BoldRed "upgrade8k: Check floppy & cd drives on VM."          
                     exit $FAIL
                  fi
                  mediafound=true
               fi
               umount /mnt
            fi
      done
   fi 2>/dev/null
}

#---------------------------------------------------------------
# function: detectcksum
# args    : None
# description:
#   verifies if the md5sum on node.cfg matches the calculated.
#---------------------------------------------------------------

detectcksum( ) {
   VERIFYCFG=$1
   TMPCFG=/tmp/node.cfg.cksum
   if [ -f "$VERIFYCFG" ];
   then
      cfgcksum="`grep 'checksum:' $VERIFYCFG | awk '{ print $3 }'`"
      numlines=`wc -l $VERIFYCFG | awk '{ print $1 }'`
      if [ $numlines -gt 2 ]
      then
           numlines=`expr $numlines - 2`
      fi
      head -n $numlines $VERIFYCFG > $TMPCFG
      actualcksum=`md5sum  $TMPCFG | awk '{ print $1 }'`
      rm -f $TMPCFG
      if [ "$actualcksum" != "$cfgcksum" ];
      then
         textncolor $BoldRed "upgrade8k: Invalid checksum in $VERIFYCFG."
         echo "   - Expected checksum : $cfgcksum"
         echo "   - Current checksum  : $actualcksum"
         logstate "UpgradeReset"
         exit $INVALIDCKSUM
      else
         textncolor $BoldCyan "upgrade8k: Verified node.cfg checksum."
      fi
   else
      textncolor $BoldRed "upgrade8k: Could not verify $VERIFYCFG."
      logstate "UpgradeReset"
      exit $INVALIDCKSUM
   fi
}

#---------------------------------------------------------------
# function: checknwitfmap
# args    : None
# description:
#    checks if there are more devices than n/w.
#---------------------------------------------------------------

checknwitfmap( ) {
   nodecfg=$1
   if [ "$1" = "" ];
   then
      return
   fi

   nprimbonds=`cat $nodecfg| egrep "^nafo0:|^nafo1:|^nafo2:|nafo3:" | awk -F':' '{ print $2 }' \
                | awk '{ print $2 }' | sort | uniq | wc -l`
   nprimsnets=`cat $nodecfg| egrep "^nafo0:|^nafo1:|^nafo2:|nafo3:" | awk -F':' '{ print $2 }' \
                | awk '{ print $7 }' | sort | uniq | wc -l`
   nsecnbonds=`cat $nodecfg| egrep "^nafo0:|^nafo1:|^nafo2:|nafo3:" | awk -F':' '{ print $2 }' \
                | awk '{ print $3 }' | sort | uniq | wc -l`
   nsecnsnets=`cat $nodecfg| egrep "^nafo0:|^nafo1:|^nafo2:|nafo3:" | awk -F':' '{ print $2 }' \
                | awk '{ print $10 }'| sort | uniq | wc -l`
 
   if [ "$nprimbonds" -ne "$nprimsnets" ];
   then
      textncolor $BoldRed "upgrade8k: Number of subnets for node#1($nprimsnets) does not match bonds($nprimbonds)."
      logstate "UpgradeReset"
      exit $INVALIDBONDS
   fi
   if [ "$testbed" != "cluster" ];
   then
      if [ "$nsecnbonds" -ne "$nsecnsnets" ];
      then
         textncolor $BoldRed "upgrade8k: Number of subnets for node#2($nsecnsnets) does not match bonds($nsecnbonds)."
         textncolor $BoldRed "Live upgrade is not supported with this configuration."
         logstate "UpgradeReset"
         exit $INVALIDBONDS
      fi
   fi
}

#---------------------------------------------------------------
# functions: isvalidmtu, checkmtu
# args    : None
# description:
#    checks if the mtu of running system matches one on node.cfg.
#---------------------------------------------------------------

isvalidmtu( ) {
   nodecfg=$1
   nafo=$2
   nafomtu=`cat $nodecfg| egrep "^$nafo:" | awk -F':' '{ print $2 }' | awk '{ print $12 }'`
   nafodev=`cat $nodecfg| egrep "^$nafo:" | awk -F':' '{ print $2 }' | awk '{ print $2 }'`
   nafoipx=`cat $nodecfg| egrep "^$nafo:" | awk -F':' '{ print $2 }' | awk '{ print $4 }'`
   nafoipy=`cat $nodecfg| egrep "^$nafo:" | awk -F':' '{ print $2 }' | awk '{ print $5 }'`
   if [ "$nafodev" != "" -a "$nafomtu" != "" ];
   then
      runningmtu=`ifconfig $nafodev | grep  "MTU:" | sed -e 's/.* MTU://' -e 's/ .*//'`
      if [ "$runningmtu" = "" ]
      then
	      runningmtu=$(ifconfig $nafodev | grep  "mtu" | awk ' { print $NF } ')
      fi
      if [ "$runningmtu" != "$nafomtu" ];
      then
         logstr "   - Validating $nafo MTU($nafomtu) with running MTU($runningmtu) with additional tests."
         status=0
         pktsize=`expr $nafomtu - 28`
         logstr "   - Sending unfragmented packets of size($pktsize bytes) to $nafoipx."
         ping -I $nafodev -M do -c 4 -s $pktsize $nafoipx 1>>$LOGFILE 2>&1
         status=$?
         if [ $status -eq 0 ];
         then
            logstr "   - Sending unfragmented packets of size($pktsize bytes) to $nafoipy."
            ping -I $nafodev -M do -c 4 -s $pktsize $nafoipy 1>>$LOGFILE 2>&1
            status=$?
         fi
         if [ "$status" -ne 0 ];
         then
            logstr "   - Failed Validating $nafo MTU($nafomtu) with running MTU($runningmtu)."
            textncolor $BoldRed "Hint: Check your MTU under nafo for $nodecfg."
            logstate "UpgradeReset"
            exit $FAIL
         else
            logstr "   - Success Validating $nafo MTU($nafomtu) packets on $nafodev."
         fi
      else
         logstr "   - Success Validating $nafo MTU($nafomtu) with running MTU($runningmtu)."
      fi
   fi
}

checkmtu( ) {
   
   nodecfg=$1
   if [ "$nodecfg" = "" -o ! -f "$nodecfg" ];
   then
      return
   fi
   targetbuildid="`fcfgread $nodecfg srx_build_id`"
   if osv_version.sh --major compare "$targetbuildid" ge V5;
   then
      isvalidmtu $nodecfg "nafo0"
      isvalidmtu $nodecfg "nafo1"
      isvalidmtu $nodecfg "nafo2"
      if [ "$testbed" = "cluster" ];
      then
         if osv_version.sh --major compare sys ge V5;
         then
            isvalidmtu $nodecfg "nafo3"
         fi
      fi
   fi
}

#---------------------------------------------------------------
# function: check_cfg_ipv6
# args    : [node.cfg.primary path]
# description:
#    based on JIRA OSV-2587 this function verifies
#    that node.cfg.primary ipv6 parameters values
#    are not NULL if value IP_Version is set as "Dual"
#---------------------------------------------------------------

check_cfg_ipv6( )
{
    # Check if global variables about version are empty

    if [ -z ${__IMG_VERSION__} ] || [ -z ${__CFG_VERSION__} ];
    then
      read_cfg_iso_ver
      if [ ${?} -ne 0 ];
      then
        textncolor $BoldRed "upgrade8k: Unable to read global variables about ISO image and node.cfg versions."
        logstate "UpgradeReset"
        exit ${FAIL}
      fi
    fi


    # Do the check only in case target version is >= V8R1

    if [[ ${__CFG_VERSION__[1]} -eq 8 && ${__CFG_VERSION__[2]} -gt 0 ]] || [[ ${__CFG_VERSION__[1]} -gt 8 ]];
    then
      # Read node.cfg.primary and check if "IP_Version" value is "Dual"

      if [ -z "${1}" ]; then
        local primary_cfg="${REPOSITORY}/upload/node.cfg.primary"
      else
        local primary_cfg=${1}
      fi

      local ip_version="`fcfgread ${primary_cfg} IP_Version`"

      if [ "${ip_version}" = "Dual" ];
      then
	  # Define IPv6 parameters of node.cfg.primary to be checked if empty

	  local params="subnet_1_ipv6 subnet_2_ipv6"

	  # Check each defined value if null

	  for param in ${params}
	  do
	      local value="`fcfgread ${primary_cfg} ${param}`"
	      if [ -z "${value}" ]; then
		textncolor $BoldRed "upgrade8k: '${param}' value of node.cfg.primary can't be empty while 'IP_Version' value is set to '${ip_version}'."
		logstate "UpgradeReset"
		exit $CFGCHECKFAILED
	      fi
	  done
      fi
    fi
}

#---------------------------------------------------------------
# function: insertFallbackService
# args    : None
# description:
#   add a systemd service for fallback
#   
#---------------------------------------------------------------
insertFallbackService( ) {

   if [ -d /usr/local/lib/systemd ]
   then

      cat << SYSD >/usr/local/lib/systemd/system/fallback.service
[Unit]
Description=Fallback service for OSV Upgrade
Requires=bz.target
After=bz.target bz_node_com_test.service srx_security.service srx_startup.service swo_startup.service spt_startup.service
Before=getty@tty1.service db_control.service activate.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/etc/init.d/fallback start 2>&1
StandardInput=tty
StandardOutput=tty
StandardError=tty
TTYPath=/dev/tty1

[Install]
WantedBy=osv.target

SYSD

      # now that the service is created make it run at osv.target.wants
      pushd /etc/systemd/system/osv.target.wants/
      ln -s /usr/local/lib/systemd/system/fallback.service fallback.service
      popd

   fi
}

#---------------------------------------------------------------
# function: hwmigration
# args    : None
# description: Used for outage free hardware migration
#---------------------------------------------------------------

hwmigration( ) {
   textncolor $BoldCyan "upgrade8k: Hardware migration outage free initiated."
   textncolor $BoldCyan "upgrade8k: Cleaning older log files."

   #<CheckFallback>
      if [ -f /etc/init.d/fallback -o -f /etc/init.d/activate ];
      then
         textncolor $BoldRed "upgrade8k: Run upgrade8k after fallback is totally complete."
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckFallback>

   #<InitOsvLu>
      rm -rf ${REPOSITORY}/upgrade8k-timing ${REPOSITORY}/upgrade8k-details ${REPOSITORY}/upgrade8k-rescue \
             /tmp/upgrade8k-timing*
      ssh $othernode "rm -rf ${REPOSITORY}/upgrade8k-timing ${REPOSITORY}/upgrade8k-details ${REPOSITORY}/upgrade8k-rescue" 2>/dev/null
      echo "Command: upgrade8k $ARGLIST"  1>>$LOGFILE 2>&1
      logstate "InitOsvUpgrade"
   #<InitOsvLu>
   if [ "$mynode" != "$primhost" ];
   then
      echo "Aborted."
      textncolor $BoldRed "Run upgrade8k from ${primhost} only."
      logstate "UpgradeReset"
      exit $FAIL
   fi
   #<CheckTestBed>
   if [ "$testbed" != "cluster" ];
   then
      echo "upgrade8k: This interface is valid only on a cluster."
      logstate "UpgradeReset"
      exit $FAIL
   fi
   #</CheckTestBed>

   #<CheckConsole>
   curtty=`tty`
   echo $curtty | grep -q "tty" 
   if [ $? -eq 0 ];
   then
       echo "upgrade8k: This interface is being run from console."
   fi
   #</CheckConsole>

   #<CheckPartition>
      textncolor $BoldCyan "upgrade8k: Checking layouts."
      mylayout=`/unisphere/srx3000/srx/bin/sync8k -q none`
      mypart="`echo $mylayout | awk -F ',' '{ print $1 }'   \
                              | sed -e 's/secondary.*/\u&/' \
                                    -e 's/primary.*/\u&/'   \
                                    -e 's/://g'`"

      otherlayout=`ssh $othernode "/unisphere/srx3000/srx/bin/sync8k -q none"`
      if [ "$mylayout" != "$otherlayout" ];
      then
         echo "upgrade8k: This interface can be run only when layouts match."
         echo "   - $mynode: $mylayout"
         echo "   - $othernode: $otherlayout"
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckPartition>

   #<CheckLoad>
      textncolor $BoldCyan "upgrade8k: Checking load."
      myload="`getload self`"
      otherload="`getload partner`"
      textncolor $Yellow "   - Load on $mynode : $myload"
      textncolor $Yellow "   - Load on $othernode : $otherload"
      if [ "$myload" != "$otherload" ];
      then
         echo "upgrade8k: The load versions/patchset levels dont match."
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckLoad>

   #<CheckMnt>
      lsof /mnt 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         echo "upgrade8k: mountpoint /mnt is in use on $mynode."
         logstate "UpgradeReset"
         exit $FAIL
      fi
      ssh $othernode "lsof /mnt" 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         echo "upgrade8k: mountpoint /mnt is in use on $othernode."
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckMnt>

   #<CleanRepo>
      upgrade8k -init -reset
   #</CleanRepo>

   #[1a]. Check the node.cfg for errors. 
   logstate "$mypart"
   logstate "VerifyLocalNodeCfg"
   if [ "$LOCALREPO8k" = "false" ];
   then
      prepare8k -live -zen
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Missing or Invalid node.cfg on $mynode."
         logstate "UpgradeReset"
         exit $CFGCHECKFAILED
      fi
   fi

   if osv_version.sh --major compare sys ge V9;
   then
      checkmtu ${REPOSITORY}/config/V9.00.01.ALL.12/node.cfg
   fi
   
   logstate "VerifyRemoteNodeCfg"
   if [ "$LOCALREPO8k" = "false" ];
   then
      ssh $othernode "prepare8k -live -zen"
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Missing or Invalid node.cfg on $othernode."
         logstate "UpgradeReset"
         exit $CFGCHECKFAILED
      fi
   fi

   #[1e]. Check ipv4 gateways are ones on your box.
   textncolor $BoldCyan "upgrade8k: Checking routing."
   rm -f /tmp/routes.missing
   route -n | awk '{ print $2 }' | sort | uniq | egrep -v "Gateway|IP" > /tmp/prim.ipv4gw
   checkgw /tmp/prim.ipv4gw 1
   if [ "$testbed" = "cluster" ];
   then
      ssh $othernode "route -n | awk '{ print \$2 }' | sort | uniq | egrep -v \"Gateway|IP\" > /tmp/sec.ipv4gw" 2>/dev/null
      scp $othernode:/tmp/sec.ipv4gw /tmp/sec.ipv4gw
      checkgw /tmp/sec.ipv4gw 2
   fi
   if [ -s /tmp/routes.missing ];
   then
      textncolor $Yellow "upgrade8k: Target routes not in current routing table."
      textncolor $Yellow "Invalid routing may lead to failed upgrade, loss of functionality."
      cat /tmp/routes.missing
      textncolor $Yellow "This may not be an error, but user needs to confirm if gateways are valid."
      textncolor $Yellow "upgrade8k: Enter 'Y' or 'y' to ignore."
      echo -n "Do you wish to continue [Y=yes/N=No]?"
      if [ "$QUIETINSTALL8k" != "true" ];
      then
         clearstdin
         read answer
         if [ "$answer" = "Y" -o "$answer" = "y" ];
         then
            echo "upgrade8k: Ignoring routing issue."
         else
            echo "Hint: Check gateways in your node.cfg.primary."
            logstate "UpgradeReset"
            exit $CFGCHECKFAILED
         fi
      else
         echo "upgrade8k: Ignoring routing issue."
      fi
   fi

   textncolor $Yellow "Note: You are in hardware migration mode."

   su - srx -c "RtpCfgShow -r Srx/Sip/Session_Timer 2>/dev/null" | egrep -e "^Value.*NO.*" 1>/dev/null 2>&1
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: The Srx/Sip/Session_Timer is enabled or cannot be read."
      textncolor $BoldRed "During the upgrade, the session timer will be disabled."
      textncolor $BoldRed "Calls originated before disabling the timer have a max duration of 90 minutes."
      textncolor $BoldRed "Calls originated after disabling the timer are not affected."
      echo ""
      textncolor $BoldCyan "upgrade8k: You should continue only if you agree with the preceding config data."
   else
      clearstdin
   fi

   if [ "$QUIETINSTALL8k" != "true" ];
   then
      while ( true )
      do
         clearstdin
         echo -n "Do you wish to continue (yes/no)? "
         read answer
         if [ "$answer" = "yes" -o "$answer" = "no" ];
         then
            if [ "$answer" = "no" ];
            then
               echo "Aborted."
               logstate "UpgradeReset"
               exit $FAIL
            else
               break;
            fi
         fi
         continue
      done
   fi

   dumparpcache "before setuplive"
   rm -f /log/publisher.lock
   rm -f $LIVEQUIET
   if [ "$QUIETINSTALL8k" = "true" ];
   then
      touch $LIVEQUIET
   fi
   setupprocctrl
   #[1g]. Check for healthy system.
   logstate "UpgradeHealthCheck"
   checkprocs $mynode    CE_01
   checkprocs $othernode CE_02

   #[1h]. Session timers control script
   setupsessiont 

   #[1j] Setup closectx.
   setupcdr

   #[2]. Create exported data
   logstate "ExportClusterData"
   if [ "$EXPORT" = "true" ];
   then
      if [ "$QUIETINSTALL8k" = "true" ];
      then
         if [ "$HWMIGRATION" = "true" ];
         then
            export8k -hw -quiet -liveexp 
         else
            export8k -hw -quiet -liveexp -local
         fi
      else
         if [ "$HWMIGRATION" = "true" ];
         then
            export8k -hw -liveexp 
         else
            export8k -hw -liveexp -local
         fi
      fi
   else
      rm -rf /software/toolkit
      ssh $othernode "rm -rf /software/toolkit"
      if [ "$uexport" = "true" ];
      then
         mkdir -p /software/toolkit/${mynode} /software/toolkit/${othernode}
         cp -R $USEREXPORT/. /software/toolkit/${mynode}/.
         scp -r $othernode:$USEREXPORT/. /software/toolkit/${othernode}/. 
      fi
   fi
   if [ $? -ne 0 ];
   then
       logstate "InitiateFallbackRequest"
       textncolor $BoldRed "upgrade8k: Cannot export data."
       clearstdin
       echo -n "upgrade8k: Press enter to fallback : "
       read answer
       logstate "InitiateFallbackAccept"
       upgrade8k -quiet -fallback
       logstate "UpgradeReset"
       exit $EXPORTDATAFAILED
   fi
   
   #[3]. Bring current node to #2.
   logstate "BringSystemStateTwo"
   /unisphere/srx3000/srx/startup/srxctrl 2 nc
   if [ $? -ne 0 ];
   then
      logstate "InitiateFallbackRequest"
      textncolor $BoldRed "upgrade8k: srxctrl cannot stop($mynode)."
      clearstdin
      echo -n "upgrade8k: Press enter to fallback : "
      read answer
      logstate "InitiateFallbackAccept"
      upgrade8k -quiet -fallback
      logstate "UpgradeReset"
      exit $SRXCTRLSTOPFAILED
   fi

   #<TurnOffProcs>
   {
      ssh $othernode "su - srx -c \"/repository/procctrl 0 $procsecmap\""
   } 1>>$LOGFILE 2>&1 
   #</TurnOffProcs>

   #[4]. turn off shutdown agent
   logstate "SplitXChLocalStrict"
   scp -p -o ConnectTimeout=8 /repository/upgrade8k-timing clusternode2-priv:/repository/upgrade8k-timing 
   nice -n -20 split8k -split -fwstrict
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: cannot split the nodes($mynode)."
      logstate "SplitXChannelFailed"
      logstate "JoinLocalXChannel"
      nice -n -20 join8k -nfw -join
      if [ $? -eq 0 ];
      then
         logstate "InitiateFallbackRequest"
         clearstdin
         echo -n "upgrade8k: Press enter to fallback : "
         read answer
         logstate "InitiateFallbackAccept"
         upgrade8k -quiet -fallback
      else
         logstate "JoinXChannelFailed"
         textncolor $BoldRed "upgrade8k: cannot join the nodes either($mynode).Contact support."
         logstate "UpgradeReset"
         exit $JOINFAILED
      fi
      logstate "SplitXChannelFailed"
      logstate "UpgradeReset"
      exit $SPLITFAILED
   fi

   openxchssh
   logstate "SplitXChannelLazy"
   nice -n -20 ssh $othernode "split8k -split -fwxch"
   status=$?
   if [ $status -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: cannot split the nodes($othernode)."
      logstate "JoinLocalXChannel"
      nice -n -20 join8k -nfw -join
      joinprimstatus=$?
      logstate "JoinRemoteXChannel"
      nice -n -20 ssh $othernode "join8k -nfw -join"
      joinsecstatus=$?
      if [ $joinprimstatus -ne 0 -o $joinsecstatus -ne 0 ];
      then
         logstate "JoinXChannelFailed"
         textncolor $BoldRed "upgrade8k: cannot join nodes either($othernode)."
      fi
      clearstdin
      logstate "InitiateFallbackRequest"
      echo -n "upgrade8k: Press enter to fallback : "
      read answer
      logstate "InitiateFallbackAccept"
      upgrade8k -quiet -fallback
      logstate "UpgradeReset"
      textncolor $BoldRed "upgrade8k: Fallback done."
      exit $SPLITFAILED
   fi

   #[5]. Ready to install
   closexchssh

   #<DisableBzTest>
      mkdir -p /etc/init.d/zorig
      if [ -f /etc/init.d/bz_node_com_test ];
      then
         mv /etc/init.d/bz_node_com_test /etc/init.d/zorig/bz_node_com_test 
      fi
      cat << EOF > /etc/init.d/fallback
#!/bin/bash
### BEGIN INIT INFO
# Provides:          fallback
# Required-Start:
# X-UnitedLinux-Should-Start: \$network \$syslog inetd srx_security srx_startup swo_startup spt_startup
# Required-Stop:
# X-UnitedLinux-Should-Stop: \$network \$syslog inetd srx_security srx_startup swo_startup spt_startup
# Default-Start:     3 5
# Default-Stop:      0 1 2 4 6
# Short-Description: xtree
# Description:       xtree
#
### END INIT INFO

. /etc/rc.status
. "${UPGRADEDIAGINC}"
rc_reset

rexit( )
{
   if [ -d /usr/local/lib/systemd ]
   then
      #systemctl disable fallback
      rm /etc/systemd/system/osv.target.wants/fallback.service
   else
      insserv -r fallback
   fi

   insserv 2>/dev/null
   exec rm -f /etc/rc.d/rc3.d/*fallback /etc/init.d/fallback

   if [ -f $REPOSITORY/diagnostics.dbg ];
   then
      upgrade_diagnostics_disable ALL
   fi

   upgrade_diagnostics_reset
   upgrade_diagnostics_reset $othernode
}

case "\$1" in
    start)
       echo "[fallback]: Starting fallback."
       if [ -f /etc/sec/setkey.conf ];
       then
          setkey -f /etc/sec/setkey.conf
       else 
          if osv_version.sh --major compare sys ge V9 && [ -f /etc/sec/.setkey.conf ];
          then
             /usr/local/bin/.setipsec -exe >/dev/null 2>&1 
             ipsec_ret=\$?
             echo "[fallback]: Setting ipsec keys from encrypted store, status(\${ipsec_ret})"
          fi	
       fi

       #<PartialFallback?>
          mynode="\`uname -n\`"
          if osv_version.sh --major compare sys ge V7 && [ "\$mynode" = "$primhost" ];
          then
             ssh $othernode -o ConnectTimeout=8 "pgrep XcmSndMonitor" 1>/dev/null 2>&1
             xcmstatus=\$?
             ssh $othernode -o ConnectTimeout=8 "pgrep sipsm" 1>/dev/null 2>&1
             callpstatus=\$?
             if [ \$xcmstatus -ne 0 -a \$callpstatus -eq 0 ];
             then
                echo "[fallback]: Invoking join."
                ssh $othernode -o ConnectTimeout=8 "join8k -nfw -join"
                join8k -nfw -join
                ssh $othernode -o ConnectTimeout=8 "
                   if [ -f ${REPOSITORY}/procctrl ];
                   then
                      su - srx -c \"${REPOSITORY}/procctrl 1 $procsecmap\" 1>>$LOGFILE 2>&1
                   fi
                "
             fi

          fi
       #</PartialFallback?>
      
       #<IsActivate>
       # Check if by mistake the load activation service is running.
       # We cannot perform 'upgrade8k -quiet -fallback' or 'upgrade8k -quiet -reset' while it runs
       # ~srx/bin/activate8k
       activate8k_pids="\$(pgrep -x activate8k)"
       # SLES11 activation service: /etc/init.d/activate
       activate_service_pids="\$(pgrep -x activate)"
       # SLES12 activation service: /usr/local/lib/systemd/system/activate.service
       activate_systemd_pids="\$(pgrep -x activate8k.initservice)"
       while ( true )
       do
           # If the file is present the activation service has not finished yet... 
           if [ "X\${activate8k_pids}X" != "XX" -o "X\${activate_service_pids}X" != "XX" -o "X\${activate_systemd_pids}X" != "XX" ]
           then
               echo "fallback: Image activation programs are currently running with PIDs[\${activate8k_pids} \${activate_service_pids} \${activate_systemd_pids}], will wait for 30 seconds..."
               sleep 30
               continue
           else
               break;
           fi
       done
       #</IsActivate>

       upgrade8k -quiet -fallback
       upgrade8k -quiet -reset
       echo "fallback: Will auto collect system data."
       if [ "\$mynode" = "$primhost" ];
       then
          upgrade8k -collect
       fi
       ;;
    *)
       echo "fallback: Nothing to do."
       rexit
       ;;
esac
echo "fallback: Done."
rexit 
EOF
      insertFallbackService
      chmod 755 /etc/init.d/fallback
      {
         if [ ! -d /usr/local/lib/systemd ]
         then
            insserv -r bz_node_com_test
            insserv fallback
            insserv
         fi

      } 2>/dev/null

   #</DisableBzTest>

   #<SetSrxBootParms>
      echo "2 0 /log/startup_srx.log /log/startup_rtp.log" > \
            /unisphere/srx3000/srx/startup/srxBootParams
   #</SetSrxBootParms>

   dumparpcache "after setuplive"
   logstate "InstallNodeOne"
   sync

   textncolor $Yellow "upgrade8k: Node ($mynode) will halt."
   textncolor $Yellow "upgrade8k: Replace new hardware with USB."
   echo -n "upgrade8k: Eject USB drives and and press enter: "
   clearstdin
   read answer
   cmd="halt -p -f"

   echo "Done."

   sync
   $cmd 1>>$LOGFILE 2>&1
}

#---------------------------------------------------------------
# function: setuplive
# args    : None
# description:
#   used for outage free upgrade. Remember nothing can go wrong.
#   Or will it?
#---------------------------------------------------------------

setuplive( ) {
   textncolor $BoldCyan "upgrade8k: Outage free upgrade initiated."
   textncolor $BoldCyan "upgrade8k: Cleaning older log files."
   {
      rm -rf /log/data-*.tar.gz /repository/upload/dev.8kps /repository/rttables
      ssh $othernode -o ConnectTimeout=8 "rm -rf /log/data-*.tar.gz /repository/upload/dev.8kps /repository/rttables" 
   } 2>/dev/null
   checkmount "/mnt" "logstate \"UpgradeReset\""
   #<CheckFallback>
      if [ -f /etc/init.d/fallback -o -f /etc/init.d/activate ];
      then
         textncolor $BoldRed "upgrade8k: Run upgrade8k after fallback is totally complete."
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckFallback>

   #<InitOsvLu>
      rm -rf ${REPOSITORY}/upgrade8k-timing ${REPOSITORY}/upgrade8k-details ${REPOSITORY}/upgrade8k-rescue \
             /tmp/upgrade8k-timing*
      ssh $othernode "rm -rf ${REPOSITORY}/upgrade8k-timing ${REPOSITORY}/upgrade8k-details ${REPOSITORY}/upgrade8k-rescue" 2>/dev/null
      echo "Command: upgrade8k $ARGLIST"  1>>$LOGFILE 2>&1
      logstate "InitOsvUpgrade"
   #<InitOsvLu>
   if [ "$mynode" != "$primhost" ];
   then
      echo "Aborted."
      textncolor $BoldRed "Run upgrade8k from ${primhost} only."
      logstate "UpgradeReset"
      exit $FAIL
   fi
   #<CheckTestBed>
   if [ "$testbed" != "cluster" ];
   then
      echo "upgrade8k: This interface is valid only on a cluster."
      logstate "UpgradeReset"
      exit $FAIL
   fi
   #</CheckTestBed>

   #<LogUpload>
      {
         echo "Upload contents on $mynode."
         ls /repository/upload
         echo "Upload contents on $othernode."
         ssh $othernode "ls /repository/upload"
      } 1>>$LOGFILE 2>&1
   #</LogUpload>

   #<CheckConsole>
   curtty=`tty`
   echo $curtty | grep -q "tty" 
   if [ $? -eq 0 ];
   then
       echo "upgrade8k: This interface is being run from console."
   fi
   #</CheckConsole>

   #<CheckImport>
      if [ "$IMPORT" = "false" ];
      then
         echo "upgrade8k: You need valid export data for live upgrade."
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckImport>

   #<CheckPartition>
      textncolor $BoldCyan "upgrade8k: Checking layouts."
      mylayout=`/unisphere/srx3000/srx/bin/sync8k -q none`
      mypart="`echo $mylayout | awk -F ',' '{ print $1 }'   \
                              | sed -e 's/secondary.*/\u&/' \
                                    -e 's/primary.*/\u&/'   \
                                    -e 's/://g'`"
   #<CheckNodeCfg>
      checkcfgsrc
   #</CheckNodeCfg>

      otherlayout=`ssh $othernode "/unisphere/srx3000/srx/bin/sync8k -q none"`
      if [ "$mylayout" != "$otherlayout" ];
      then
         echo "upgrade8k: This interface can be run only when layouts match."
         echo "   - $mynode: $mylayout"
         echo "   - $othernode: $otherlayout"
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckPartition>

   #<CheckLoad>
      textncolor $BoldCyan "upgrade8k: Checking load."
      myload="`getload self`"
      otherload="`getload partner`"
      textncolor $Yellow "   - Load on $mynode : $myload"
      textncolor $Yellow "   - Load on $othernode : $otherload"
      if [ "$myload" != "$otherload" ];
      then
         echo "upgrade8k: The load versions/patchset levels dont match."
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckLoad>

   #<CheckMnt>
      lsof /mnt 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         echo "upgrade8k: mountpoint /mnt is in use on $mynode."
         logstate "UpgradeReset"
         exit $FAIL
      fi
      ssh $othernode "lsof /mnt" 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         echo "upgrade8k: mountpoint /mnt is in use on $othernode."
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckMnt>

   #<CheckLicense>
      licfile=/tmp/license.count
      licensecount=`find /repository/upload -type f -name "*.lic" 2>/dev/null| egrep -v "OpenScape|H8K" | wc -l`
      ssh $othernode "find /repository/upload -type f -name \"*.lic\" 2>/dev/null| egrep -v \"OpenScape|H8K\" | wc -l > $licfile" 2>/dev/null
      scp $othernode:$licfile $licfile 2>/dev/null
      otherlicensecount=`cat $licfile`
      if [ $licensecount -gt 0 -o $otherlicensecount -gt 0 ];
      then
         echo "upgrade8k: Non standard licenses found."
         echo "Hint: Remove non standard licenses under /repository/upload, and try again."
         logstate "NonStandardLicense"
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckLicense>

   #<CleanRepo>
      upgrade8k -init -reset
   #</CleanRepo>

   #<SetupUpgradeDiagnostics>
      setup_upgrade_diagnostics
   #</SetupUpgradeDiagnostics>

   #<CheckDev>
      echo "upgrade8k: Checking local repository for upgrade contents."
      test -r /repository/upload/node.cfg.primary
      localstatus=$?
      ssh $othernode "test -r /repository/upload/node.cfg.secondary" 1>/dev/null 2>&1
      remotestatus=$?
      if [ $localstatus -eq 0 -o $remotestatus -eq 0 ];
      then
         if [ $localstatus -eq 0 -a $remotestatus -eq 0 ];
         then
            LOCALREPO8k=true
            logstr "   - Will use local repository for upgrade."
            checkdualmedia
         else
            textncolor $BoldRed "upgrade8k: Partial data found in repository."
            textncolor $BoldRed "upgrade8k: check /repository/upload of both nodes."
            logstate "UpgradeReset"
            exit $FAIL
         fi
      else
         logstr "   - Will use dvd media for upgrade."
      fi
   #</CheckDev>

   
   # Read and set global variables about version
   
   read_cfg_iso_ver
   if [ ${?} -ne 0 ];
   then
   	textncolor $BoldRed "upgrade8k: Unable to read global variables about ISO image and node.cfg versions."
        logstate "UpgradeReset"
        exit ${FAIL}
   fi

   #[1a]. Check the node.cfg for errors. 
   logstate "$mypart"
   logstate "VerifyLocalNodeCfg"
   if [ "$LOCALREPO8k" = "false" ];
   then
      prepare8k -live -zen 
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Missing or Invalid node.cfg on $mynode."
         logstate "UpgradeReset"
         exit $CFGCHECKFAILED
      fi
   else
      zen ${REPOSITORY}/upload/node.cfg.primary
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Invalid node.cfg on $mynode."
         logstate "UpgradeReset"
         exit $CFGCHECKFAILED
      fi
   fi

   checkmtu ${REPOSITORY}/upload/node.cfg.primary

   logstate "VerifyRemoteNodeCfg"
   if [ "$LOCALREPO8k" = "false" ];
   then
      ssh $othernode "prepare8k -live -zen"
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Missing or Invalid node.cfg on $othernode."
         logstate "UpgradeReset"
         exit $CFGCHECKFAILED
      fi
   else
      ssh $othernode "zen ${REPOSITORY}/upload/node.cfg.secondary" 2>/dev/null
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Invalid node.cfg on $othernode."
         logstate "UpgradeReset"
         exit $CFGCHECKFAILED
      fi
   fi

   #[1b]. Check toolkit availability
   if [ ! -f ${REPOSITORY}/upload/UNSPmigration*.rpm ];
   then
      textncolor $BoldRed "upgrade8k: No toolkit found."
      echo "Hint: Place toolkit RPM under patch/ inside usb."
      logstate "UpgradeReset"
      exit $CFGCHECKFAILED
   fi

   #[1c]. Check node.cfg availability
   if [ ! -f ${REPOSITORY}/upload/node.cfg.primary ];
   then
      textncolor $BoldRed "upgrade8k: No node.cfg found."
      echo "Hint: Place node.cfg.primary under / inside usb."
      logstate "UpgradeReset"
      exit $CFGCHECKFAILED
   fi

   # Check if node.cfg.primary has correct IPv6 subnet parameters
   check_cfg_ipv6 ${REPOSITORY}/upload/node.cfg.primary

   #[1d]. Verify checksum
   detectcksum ${REPOSITORY}/upload/node.cfg.primary
   checknwitfmap ${REPOSITORY}/upload/node.cfg.primary

   #[1e]. Check ipv4 gateways are ones on your box.
   textncolor $BoldCyan "upgrade8k: Checking routing."
   rm -f /tmp/routes.missing
   route -n | awk '{ print $2 }' | sort | uniq | egrep -v "Gateway|IP" > /tmp/prim.ipv4gw
   checkgw /tmp/prim.ipv4gw 1
   if [ "$testbed" = "cluster" ];
   then
      ssh $othernode "route -n | awk '{ print \$2 }' | sort | uniq | egrep -v \"Gateway|IP\" > /tmp/sec.ipv4gw" 2>/dev/null
      scp $othernode:/tmp/sec.ipv4gw /tmp/sec.ipv4gw
      checkgw /tmp/sec.ipv4gw 2
   fi
   if [ -s /tmp/routes.missing ];
   then
      textncolor $Yellow "upgrade8k: Target routes not in current routing table."
      textncolor $Yellow "Invalid routing may lead to failed upgrade, loss of functionality."
      cat /tmp/routes.missing
      textncolor $Yellow "This may not be an error, but user needs to confirm if gateways are valid."
      textncolor $Yellow "upgrade8k: Enter 'Y' or 'y' to ignore."
      echo -n "Do you wish to continue [Y=yes/N=No]?"
      if [ "$QUIETINSTALL8k" != "true" ];
      then
         clearstdin
         read answer
         if [ "$answer" = "Y" -o "$answer" = "y" ];
         then
            echo "upgrade8k: Ignoring routing issue."
         else
            echo "Hint: Check gateways in your node.cfg.primary."
            logstate "UpgradeReset"
            exit $CFGCHECKFAILED
         fi
      else
         echo "upgrade8k: Ignoring routing issue."
      fi
   fi

   #[1f]. Check differences in node.cfg.
   logstate "ZenTagComparison"
   targetbuildid="`fcfgread ${REPOSITORY}/upload/node.cfg.primary srx_build_id`"
   if osv_version.sh --major compare "$targetbuildid" lt V6;
   then
      textncolor $BoldRed "upgrade8k: Live upgrade is not supported for target:$targetbuildid."
      logstate "UpgradeReset"
      exit $CFGCHECKFAILED
   fi
   textncolor $BoldCyan "upgrade8k: node.cfg tags comparison."
   zen diff /etc/hiq8000/node.cfg ${REPOSITORY}/upload/node.cfg.primary
   if [ $? -ne 0 ];
   then
       echo "upgrade8k: Well, your source node.cfg is not slick."
       echo "upgrade8k: You can continue only if you are sure."
   else
      clearstdin
   fi

   # Match iso image version with node.cfg version
   match_cfg_img_version

   #<CheckHwMigration>
      sourcehw="`cfgread hw_platform`"
      targethw="`fcfgread ${REPOSITORY}/upload/node.cfg.primary hw_platform`"
      if [ "$sourcehw" != "$targethw" ];
      then
         textncolor $BoldCyan "upgrade8k: Hardware migration scenario."
         HWMIGRATION=true
      fi
       if [ "$HWMIGRATION" = "true" -a "$LOCALREPO8k" = "true" ];
       then
          textncolor $BoldRed "upgrade8k: Hardware migration cannot use local repository for upgrade."
          echo "Hint: Clean local repository - user DVD/USB for upgrade."
          logstate "UpgradeReset"
          exit $CFGCHECKFAILED
       fi
   #</CheckHwMigration>

   if [ "$HWMIGRATION" = "true" ];
   then
      textncolor $Yellow "Note: You are in hardware migration mode."
   fi
   su - srx -c "RtpCfgShow -r Srx/Sip/Session_Timer 2>/dev/null" | egrep -e "^Value.*NO.*" 1>/dev/null 2>&1
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: The Srx/Sip/Session_Timer is enabled or cannot be read."
      textncolor $BoldRed "During the upgrade, the session timer will be disabled."
      textncolor $BoldRed "Calls originated before disabling the timer have a max duration of 90 minutes."
      textncolor $BoldRed "Calls originated after disabling the timer are not affected."
      echo ""
      textncolor $BoldCyan "upgrade8k: You should continue only if you agree with the preceding config data."
   else
      clearstdin
   fi

   if [ "$QUIETINSTALL8k" != "true" ];
   then
      while ( true )
      do
         clearstdin
         echo -n "Do you wish to continue (yes/no)? "
         read answer
         if [ "$answer" = "yes" -o "$answer" = "no" ];
         then
            if [ "$answer" = "no" ];
            then
               echo "Aborted."
               logstate "UpgradeReset"
               exit $FAIL
            else
               break;
            fi
         fi
         continue
      done
   fi

   if osv_version.sh --major compare sys lt V4;
   then
      . /unisphere/srx3000/srx/.profile
   fi

   dumparpcache "before setuplive"
   rm -f /log/publisher.lock
   rm -f $LIVEQUIET
   if [ "$QUIETINSTALL8k" = "true" ];
   then
      touch $LIVEQUIET
   fi
   setupprocctrl
   #[1g]. Check for healthy system.
   logstate "UpgradeHealthCheck"
   checkprocs $mynode    CE_01
   checkprocs $othernode CE_02

   #[1h]. Session timers control script
   setupsessiont 

   #[1i]. Check dvd for errors.
   logstate "CheckLocalDvdIntegrity"
   textncolor $BoldCyan "upgrade8k: Verifying contents for live upgrade on $mynode."
   textncolor $BoldCyan "Start:`date`"
   export LIVE8kUPGRADE=true
   if [ "$LOCALREPO8k" = "false" ];
   then
      upgrade8k -verify
   else
      upgrade8k -local -verify
   fi
   status=$?
   if [ $status -ne 0 ];
   then
      logstate "InitiateFallbackRequest"
      if [ "$LOCALREPO8k" = "false" ];
      then
         rm -rf ${REPOSITORY}/upload/*
         ssh $othernode "rm -rf ${REPOSITORY}/upload/*" 2>/dev/null
      fi
      clearstdin
      echo -n "upgrade8k: Press enter to fallback : "
      read answer
      logstate "InitiateFallbackAccept"
      upgrade8k -quiet -fallback
      logstate "UpgradeReset"
      exit $SETUPIMAGEFAILED
   fi
 
   logstate "CheckRemoteDvdIntegrity"
   textncolor $BoldCyan "upgrade8k: Verifying contents for live upgrade on $othernode."
   textncolor $BoldCyan "Start:`date`"
   if [ "$LOCALREPO8k" = "false" ];
   then
      ssh $othernode  "export LIVE8kUPGRADE=true; upgrade8k -verify"
   else
      ssh $othernode  "export LIVE8kUPGRADE=true; upgrade8k -local -verify"
   fi
   if [ $? -ne 0 ];
   then
      logstate "InitiateFallbackRequest"
      if [ "$LOCALREPO8k" = "false" ];
      then
         rm -rf ${REPOSITORY}/upload/*
         ssh $othernode "rm -rf ${REPOSITORY}/upload/*" 2>/dev/null
      fi
      clearstdin
      echo -n "upgrade8k: Press enter to fallback : "
      read answer
      logstate "InitiateFallbackAccept"
      upgrade8k -quiet -fallback
      logstate "UpgradeReset"
      exit $SETUPIMAGEFAILED
   fi
   textncolor $BoldCyan "upgrade8k: Verify ends for live upgrade."
   textncolor $BoldCyan "End:`date`"

   comparepatchset

   #[1j] Setup closectx.
   setupcdr

   #[2]. Create exported data
   logstate "ExportClusterData"
   if [ "$EXPORT" = "true" ];
   then
      if [ "$QUIETINSTALL8k" = "true" ];
      then
         if [ "$HWMIGRATION" = "true" ];
         then
            export8k -hw -quiet -liveexp 
         else
            export8k -quiet -liveexp -local
         fi
      else
         if [ "$HWMIGRATION" = "true" ];
         then
            export8k -hw -liveexp 
         else
            export8k -liveexp -local
         fi
      fi
   else
      rm -rf /software/toolkit
      ssh $othernode "rm -rf /software/toolkit"
      if [ "$uexport" = "true" ];
      then
         mkdir -p /software/toolkit/${mynode} /software/toolkit/${othernode}
         cp -R $USEREXPORT/. /software/toolkit/${mynode}/.
         scp -r $othernode:$USEREXPORT/. /software/toolkit/${othernode}/. 
      fi
   fi
   if [ $? -ne 0 ];
   then
       logstate "InitiateFallbackRequest"
       textncolor $BoldRed "upgrade8k: Cannot export data."
       clearstdin
       echo -n "upgrade8k: Press enter to fallback : "
       read answer
       logstate "InitiateFallbackAccept"
       upgrade8k -quiet -fallback
       logstate "UpgradeReset"
       exit $EXPORTDATAFAILED
   fi
   
   #[3]. Bring current node to #2.
   logstate "BringSystemStateTwo"
   /unisphere/srx3000/srx/startup/srxctrl 2 nc
   if [ $? -ne 0 ];
   then
      logstate "InitiateFallbackRequest"
      textncolor $BoldRed "upgrade8k: srxctrl cannot stop($mynode)."
      clearstdin
      echo -n "upgrade8k: Press enter to fallback : "
      read answer
      logstate "InitiateFallbackAccept"
      upgrade8k -quiet -fallback
      logstate "UpgradeReset"
      exit $SRXCTRLSTOPFAILED
   fi

   #<TurnOffProcs>
   {
      ssh $othernode "su - srx -c \"/repository/procctrl 0 $procsecmap\""
   } 1>>$LOGFILE 2>&1 
   #</TurnOffProcs>

   #[4]. turn off shutdown agent
   logstate "SplitXChLocalStrict"
   scp -p -o ConnectTimeout=8 /repository/upgrade8k-timing clusternode2-priv:/repository/upgrade8k-timing 
   nice -n -20 split8k -split -fwstrict
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: cannot split the nodes($mynode)."
      logstate "SplitXChannelFailed"
      logstate "JoinLocalXChannel"
      nice -n -20 join8k -nfw -join
      if [ $? -eq 0 ];
      then
         logstate "InitiateFallbackRequest"
         clearstdin
         echo -n "upgrade8k: Press enter to fallback : "
         read answer
         logstate "InitiateFallbackAccept"
         upgrade8k -quiet -fallback
      else
         logstate "JoinXChannelFailed"
         textncolor $BoldRed "upgrade8k: cannot join the nodes either($mynode).Contact support."
         logstate "UpgradeReset"
         exit $JOINFAILED
      fi
      logstate "SplitXChannelFailed"
      logstate "UpgradeReset"
      exit $SPLITFAILED
   fi

   openxchssh
   logstate "SplitXChannelLazy"
   nice -n -20 ssh $othernode "split8k -split -fwxch"
   status=$?
   if [ $status -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: cannot split the nodes($othernode)."
      logstate "JoinLocalXChannel"
      nice -n -20 join8k -nfw -join
      joinprimstatus=$?
      logstate "JoinRemoteXChannel"
      nice -n -20 ssh $othernode "join8k -nfw -join"
      joinsecstatus=$?
      if [ $joinprimstatus -ne 0 -o $joinsecstatus -ne 0 ];
      then
         logstate "JoinXChannelFailed"
         textncolor $BoldRed "upgrade8k: cannot join nodes either($othernode)."
      fi
      clearstdin
      logstate "InitiateFallbackRequest"
      echo -n "upgrade8k: Press enter to fallback : "
      read answer
      logstate "InitiateFallbackAccept"
      upgrade8k -quiet -fallback
      logstate "UpgradeReset"
      textncolor $BoldRed "upgrade8k: Fallback done."
      exit $SPLITFAILED
   fi

   #[5]. Ready to install
   textncolor $BoldCyan "upgrade8k: Building boot installer for $mynode."
   #<LocalNode>
      logstate "BuildLiveInstaller"
      if [ "$LOCALREPO8k" = "true" ];
      then
         upgrade8k -local -quiet -buildliveinst
      else
         if [ "$HWMIGRATION" = "true" ];
         then
            upgrade8k -hw -quiet -buildliveinst
         else
            upgrade8k -quiet -buildliveinst
         fi
      fi
      status=$?
      if [ $status -ne 0 ];
      then
         logstate "ResetLiveInstaller"
         upgrade8k -reset
         textncolor $BoldRed "upgrade8k: Cannot build bootable installer."
         logstate "InitiateFallbackRequest"
         clearstdin
         echo -n "upgrade8k: Press enter to fallback : "
         read answer
         logstate "InitiateFallbackAccept"
         nice -n -20 join8k -nfw -join
         joinprimstatus=$?
         nice -n -20 ssh $othernode "join8k -nfw -join"
         joinsecstatus=$?
         if [ $joinprimstatus -ne 0 -o $joinsecstatus -ne 0 ];
         then
            textncolor $BoldRed "upgrade8k: cannot join nodes either($othernode)."
         fi
         clearstdin
         logstate "InitiateFallbackRequest"
         echo -n "upgrade8k: Press enter to fallback : "
         read answer
         logstate "InitiateFallbackAccept"
         upgrade8k -quiet -fallback
         logstate "UpgradeReset"
         textncolor $BoldRed "upgrade8k: Fallback done."
         exit $FAIL
      fi
   #</LocalNode>
   closexchssh

   #<DisableBzTest>
      mkdir -p /etc/init.d/zorig
      if [ -f /etc/init.d/bz_node_com_test ];
      then
         mv /etc/init.d/bz_node_com_test /etc/init.d/zorig/bz_node_com_test 
      fi
      cat << EOF > /etc/init.d/fallback
#!/bin/bash
### BEGIN INIT INFO
# Provides:          fallback
# Required-Start:
# X-UnitedLinux-Should-Start: \$network \$syslog inetd srx_security srx_startup swo_startup spt_startup
# Required-Stop:
# X-UnitedLinux-Should-Stop: \$network \$syslog inetd srx_security srx_startup swo_startup spt_startup
# Default-Start:     3 5
# Default-Stop:      0 1 2 4 6
# Short-Description: xtree
# Description:       xtree
#
### END INIT INFO

. /etc/rc.status
. "${UPGRADEDIAGINC}"
rc_reset

rexit( )
{
   if [ -d /usr/local/lib/systemd ]
   then
      #systemctl disable fallback
      rm /etc/systemd/system/osv.target.wants/fallback.service
   else
      insserv -r fallback
   fi

   insserv 2>/dev/null
   exec rm -f /etc/rc.d/rc3.d/*fallback /etc/init.d/fallback

   #Reset diagnostics
   upgrade_diagnostics_reset

   if [ "$testbed" = "cluster" ]
   then
      upgrade_diagnostics_reset $othernode
   fi
}

case "\$1" in
    start)
       echo "[fallback]: Starting fallback."
       if [ -f /etc/sec/setkey.conf ];
       then
          setkey -f /etc/sec/setkey.conf
       else 
          if osv_version.sh --major compare sys ge V9 && [ -f /etc/sec/.setkey.conf ];
          then
             /usr/local/bin/.setipsec -exe >/dev/null 2>&1 
             ipsec_ret=\$?
             echo "[fallback]: Setting ipsec keys from encrypted store, status(\${ipsec_ret})"
          fi	
       fi

       #<PartialFallback?>
          mynode="\`uname -n\`"
          if osv_version.sh --major compare sys ge V7 && [ "\$mynode" = "$primhost" ];
          then
             ssh $othernode -o ConnectTimeout=8 "pgrep XcmSndMonitor" 1>/dev/null 2>&1
             xcmstatus=\$?
             ssh $othernode -o ConnectTimeout=8 "pgrep sipsm" 1>/dev/null 2>&1
             callpstatus=\$?
             if [ \$xcmstatus -ne 0 -a \$callpstatus -eq 0 ];
             then
                echo "[fallback]: Invoking join."
                ssh $othernode -o ConnectTimeout=8 "join8k -nfw -join"
                join8k -nfw -join
                ssh $othernode -o ConnectTimeout=8 "
                   if [ -f ${REPOSITORY}/procctrl ];
                   then
                      su - srx -c \"${REPOSITORY}/procctrl 1 $procsecmap\" 1>>$LOGFILE 2>&1
                   fi
                "
             fi

          fi
       #</PartialFallback?>
      
       #<IsActivate>
       # Check if by mistake the load activation service is running.
       # We cannot perform 'upgrade8k -quiet -fallback' or 'upgrade8k -quiet -reset' while it runs
       # ~srx/bin/activate8k
       activate8k_pids="\$(pgrep -x activate8k)"
       # SLES11 activation service: /etc/init.d/activate
       activate_service_pids="\$(pgrep -x activate)"
       # SLES12 activation service: /usr/local/lib/systemd/system/activate.service
       activate_systemd_pids="\$(pgrep -x activate8k.initservice)"
       while ( true )
       do
           # If the file is present the activation service has not finished yet... 
           if [ "X\${activate8k_pids}X" != "XX" -o "X\${activate_service_pids}X" != "XX" -o "X\${activate_systemd_pids}X" != "XX" ]
           then
               echo "fallback: Image activation programs are currently running with PIDs[\${activate8k_pids} \${activate_service_pids} \${activate_systemd_pids}], will wait for 30 seconds..."
               sleep 30
               continue
           else
               break;
           fi
       done
       #</IsActivate>

       upgrade8k -quiet -fallback
       upgrade8k -quiet -reset
       echo "fallback: Will auto collect system data."
       if [ "\$mynode" = "$primhost" ];
       then
          upgrade8k -collect
       fi
       ;;
    *)
       echo "fallback: Nothing to do."
       rexit
       ;;
esac
echo "fallback: Done."
rexit 
EOF
      insertFallbackService
      chmod 755 /etc/init.d/fallback
      {
         if [ ! -d /usr/local/lib/systemd ]
         then
            insserv -r bz_node_com_test
            insserv fallback
            insserv
         fi

      } 2>/dev/null

   #</DisableBzTest>

   #<SetSrxBootParms>
      echo "2 0 /log/startup_srx.log /log/startup_rtp.log" > \
            /unisphere/srx3000/srx/startup/srxBootParams
   #</SetSrxBootParms>

   dumparpcache "after setuplive"
   logstate "InstallNodeOne"
   sync
   if [ "$HWMIGRATION" = "true" ];
   then
      textncolor $Yellow "upgrade8k: Node#1 ($mynode) will halt."
      textncolor $Yellow "upgrade8k: Replace new hardware with DVD and USB. Choose Install."
      echo -n "upgrade8k: Eject DVD and USB drives from both nodes now and press enter : "
      clearstdin
      read answer
      cmd="halt -p -f"
   else
      textncolor $Yellow "upgrade8k: Node#1 ($mynode) will reboot now to be installed."
      cmd="reboot -f"
   fi
   echo "Done."
   sync
   $cmd 1>>$LOGFILE 2>&1
}

#---------------------------------------------------------------
# function: livehook
# args    : None
# description:
#   Well. Time for reality. Sometimes we have to change things
#   at a point we already set it up. For e.g. dbpassword for 
#   node#2. Here is your chance.
#---------------------------------------------------------------

livehook( )
{
   pgrep xtree 1>/dev/null 2>&1
   xtreestatus=$?
   pgrep solid 1>/dev/null 2>&1
   solidstatus=$?
   if [ "$upgrademode" = "OutageFree" -a "$xtreestatus" -eq 0 -a "$solidstatus" -ne 0 ];
   then
      if [ "$mynode" = "$primhost" ];
      then
         logstr "   - Executing hooks for live upgrade on $mynode."
      else
         logstr "   - Executing hooks for live upgrade on $othernode."
         scp -p $othernode:${DBA_PASSWDFILE} ${DBA_PASSWDFILE}
         if osv_version.sh --major compare sys ge V6;
         then
            setDbaPassword $(getDbaPassword encrypted)
         else
            setDbaPassword $(getDbaPassword decrypted)
         fi
         rm -f /home/solid/RtpDb/*
         su - solid -c "solid -C RTPDB -U dba -P $(getDbaPassword) -x exit"
         if [ $? -ne 0 ];
         then
            logstr "   - Interesting. Cannot create empty database."
         fi
      fi
   fi
}

#---------------------------------------------------------------
# function: setupsimplexlive
# args    : None
# description:
#   used for outage free upgrade. Remember nothing can go wrong.
#   Or will it?
#---------------------------------------------------------------

setupsimplexlive( ) {
   textncolor $BoldCyan "upgrade8k: Outage free upgrade initiated."
   textncolor $BoldCyan "upgrade8k: Cleaning older log files."
   rm -rf /log/data-*.tar.gz /repository/upload/dev.8kps /repository/rttables 2>/dev/null
   checkmount "/mnt" "logstate \"UpgradeReset\""
   #<CheckFallback>
      if [ -f /etc/init.d/fallback -o -f /etc/init.d/activate ];
      then
         textncolor $BoldRed "upgrade8k: Run upgrade8k after fallback is totally complete."
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckFallback>

   #<InitOsvLu>
      rm -rf ${REPOSITORY}/upgrade8k-timing \
             ${REPOSITORY}/upgrade8k-details ${REPOSITORY}/upgrade8k-rescue /tmp/upgrade8k-timing*
      echo "Command: upgrade8k $ARGLIST"  1>>$LOGFILE 2>&1
      logstate "InitOsvUpgrade"
   #</InitOsvLu>
   if [ "$mynode" != "$primhost" ];
   then
      echo "Aborted."
      textncolor $BoldRed "Run upgrade8k from ${primhost} only."
      logstate "UpgradeReset"
      exit $FAIL
   fi

   #<CheckTestBed>
   if [ "$testbed" != "simplex" ];
   then
      echo "upgrade8k: This interface is valid only on a simplex."
      logstate "UpgradeReset"
      exit $FAIL
   fi
   #</CheckTestBed>
 
   #<LogUpload>
      {
         echo "Upload contents on $mynode."
         ls /repository/upload
      } 1>>$LOGFILE 2>&1
   #</LogUpload>

   #<CheckConsole>
   curtty=`tty`
   echo $curtty | grep -q "tty"
   if [ $? -eq 0 ];
   then
       echo "upgrade8k: This interface is being run from console."
   fi
   #</CheckConsole>

   #<CheckNodeCfg>
      checkcfgsrc
   #</CheckNodeCfg>

   #<CheckPartition>
      textncolor $BoldCyan "upgrade8k: Checking layouts."
      mylayout=`/unisphere/srx3000/srx/bin/sync8k -q none`
      mypart="`echo $mylayout | awk -F ',' '{ print $1 }'    \
                              | sed -e 's/secondary.*/\u&/'  \
                                    -e 's/primary.*/\u&/'    \
                                    -e 's/://g'`"
   #</CheckPartition>

   #<CheckLoad>
      textncolor $BoldCyan "upgrade8k: Checking load."
      myload="`getload self`"
      textncolor $Yellow "   - Load on $mynode : $myload"
   #</CheckLoad>

   #<CheckMnt>
      lsof /mnt 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         echo "upgrade8k: mountpoint /mnt is in use on $mynode."
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckMnt>

   #<CheckLicense>
      licensecount=`find /repository/upload -type f -name "*.lic" 2>/dev/null| egrep -v "OpenScape|H8K" | wc -l`
      if [ $licensecount -gt 0 ];
      then
         echo "upgrade8k: Non standard licenses found."
         echo "Hint: Remove non standard licenses under /repository/upload, and try again."
         logstate "UpgradeReset"
         exit $FAIL
      fi
   #</CheckLicense>

   #<CleanRepo>
      upgrade8k -init -reset
   #</CleanRepo>

   #<CheckDev>
      echo "upgrade8k: Checking local repository for upgrade contents."
      test -r /repository/upload/node.cfg.primary
      localstatus=$?
      if [ $localstatus -eq 0 ];
      then
         LOCALREPO8k=true
         logstr "   - Will use local repository for upgrade."
         checkdualmedia
      else
         logstr "   - Will use dvd media for upgrade."
      fi
   #</CheckDev>

   # Read and set global variables about version
   read_cfg_iso_ver
   if [ ${?} -ne 0 ];
   then
        textncolor $BoldRed "upgrade8k: Unable to read global variables about ISO image and node.cfg versions."
        logstate "UpgradeReset"
        exit ${FAIL}
   fi

   #[1a]. Check the node.cfg for errors.
   logstate "$mypart"
   logstate "VerifyLocalNodeCfg"
   if [ "$LOCALREPO8k" = "false" ];
   then
      prepare8k -live -zen
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Missing or Invalid node.cfg on $mynode."
         logstate "UpgradeReset"
         exit $CFGCHECKFAILED
      fi
   else
      zen ${REPOSITORY}/upload/node.cfg.primary
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Invalid node.cfg on $mynode."
         logstate "UpgradeReset"
         exit $CFGCHECKFAILED
      fi
   fi

   checkmtu ${REPOSITORY}/upload/node.cfg.primary

   #[1b]. Check toolkit availability
   if [ ! -f ${REPOSITORY}/upload/UNSPmigration*.rpm ];
   then
      textncolor $BoldRed "upgrade8k: No toolkit found."
      echo "Hint: Place toolkit RPM under patch/ inside usb."
      logstate "UpgradeReset"
      exit $CFGCHECKFAILED
   fi

   #[1c]. Check node.cfg availability
   if [ ! -f ${REPOSITORY}/upload/node.cfg.primary ];
   then
      textncolor $BoldRed "upgrade8k: No node.cfg found."
      echo "Hint: Place node.cfg.primary under / inside usb."
      logstate "UpgradeReset"
      exit $CFGCHECKFAILED
   fi

   # Check if node.cfg.primary has correct IPv6 subnet parameters
   check_cfg_ipv6 ${REPOSITORY}/upload/node.cfg.primary

   #[1d]. Verify checksum
   detectcksum ${REPOSITORY}/upload/node.cfg.primary

   #[1e]. Check ipv4 gateways are ones on your box.
   textncolor $BoldCyan "upgrade8k: Checking routing."
   rm -f /tmp/routes.missing
   route -n | awk '{ print $2 }' | sort | uniq | egrep -v "Gateway|IP" > /tmp/prim.ipv4gw
   checkgw /tmp/prim.ipv4gw 1

   if [ -s /tmp/routes.missing ];
   then
      textncolor $BoldRed "upgrade8k: Target routes not in current routing table."
      textncolor $BoldRed "Invalid routing may lead to failed upgrade, loss of functionality."
      cat /tmp/routes.missing
      textncolor $BoldRed "upgrade8k: Enter 'Y' or 'y' to ignore."
      echo -n "Do you wish to continue [Y=yes/N=No]?"
      if [ "$QUIETINSTALL8k" != "true" ];
      then
         clearstdin
         read answer
         if [ "$answer" = "Y" -o "$answer" = "y" ];
         then
            echo "upgrade8k: Ignoring routing issue."
         else
            echo "Hint: Check gateways in your node.cfg.primary."
            logstate "UpgradeReset"
            exit $CFGCHECKFAILED
         fi
      else
         echo "upgrade8k: Ignoring routing issue."
      fi
   fi

   #[1f]. Check differences in node.cfg.
   logstate "ZenTagComparison"
   targetbuildid="`fcfgread ${REPOSITORY}/upload/node.cfg.primary srx_build_id`"
   if osv_version.sh --major compare "$targetbuildid" lt V6;
   then
      textncolor $BoldRed "upgrade8k: Live upgrade is not supported for target:$targetbuildid."
      logstate "UpgradeReset"
      exit $CFGCHECKFAILED
   fi
   textncolor $BoldCyan "upgrade8k: node.cfg tags comparison."
   zen diff /etc/hiq8000/node.cfg ${REPOSITORY}/upload/node.cfg.primary
   if [ $? -ne 0 ];
   then
       echo "upgrade8k: Well, your source node.cfg is not slick."
       echo "upgrade8k: You can continue only if you are sure."
       textncolor $BoldCyan " Well, your source node.cfg is not slick"
   else
      clearstdin
   fi

   # Match iso image version with node.cfg version
   match_cfg_img_version

   #<CheckHwMigration>
      sourcehw="`cfgread hw_platform`"
      targethw="`fcfgread ${REPOSITORY}/upload/node.cfg.primary hw_platform`"
      if [ "$sourcehw" != "$targethw" ];
      then
         textncolor $BoldCyan "upgrade8k: Hardware migration scenario."
         HWMIGRATION=true
      fi
      if [ "$HWMIGRATION" = "true" -a "$LOCALREPO8k" = "true" ];
      then
         textncolor $BoldRed "upgrade8k: Hardware migration cannot use local repository for upgrade."
         echo "Hint: Clean local repository - user DVD/USB for upgrade."
         logstate "UpgradeReset"
         exit $CFGCHECKFAILED
      fi
   #</CheckHwMigration>

   if [ "$HWMIGRATION" = "true" ];
   then
      textncolor $Yellow "Note: You are in hardware migration mode."
   fi
   su - srx -c "RtpCfgShow -r Srx/Sip/Session_Timer 2>/dev/null" | egrep -e "^Value.*NO.*" 1>/mylog1.log 2>&1
   su - srx -c "RtpCfgShow -r Srx/Sip/Session_Timer 2>/dev/null" | egrep -e "^Value.*NO.*" 1>/dev/null 2>&1
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: The Srx/Sip/Session_Timer is enabled or cannot be read."
      textncolor $BoldRed "During the upgrade, the session timer will be disabled."
      textncolor $BoldRed "Calls originated before disabling the timer have a max duration of 90 minutes."
      textncolor $BoldRed "Call processing is not available while upgrade is in progress."
      echo ""
      textncolor $BoldCyan "upgrade8k: You should continue only if you agree with the preceding config data."
   else
      clearstdin
   fi
   textncolor $BoldRed "QUIETINSTALL8k=$QUIETINSTALL8k"

   if [ "$QUIETINSTALL8k" != "true" ];
   then
      while ( true )
      do
         clearstdin
         echo -n "Do you wish to continue (yes/no)? "
         read answer
         if [ "$answer" = "yes" -o "$answer" = "no" ];
         then
            if [ "$answer" = "no" ];
            then
               echo "Aborted."
               logstate "UpgradeReset"
               exit $FAIL
            else
               break;
            fi
         fi
         continue
      done
   fi
set +x
   if osv_version.sh --major compare sys lt V4;
   then
      . /unisphere/srx3000/srx/.profile
   fi
   rm -f $LIVEQUIET
   if [ "$QUIETINSTALL8k" = "true" ];
   then
      touch $LIVEQUIET
   fi
   
   dumparpcache "before setupsimplexlive"
   #[1g]. Check for healthy system.
   logstate "UpgradeHealthCheck"
   checkprocs $mynode    CE_01

   #[1h]. Setup session timer
   setupsessiont

   #[1i]. Check dvd for errors.
   logstate "CheckLocalDvdIntegrity"
   textncolor $BoldCyan "upgrade8k: Verifying contents for live upgrade on $mynode."
   textncolor $BoldCyan "Start:`date`"
   export LIVE8kUPGRADE=true
   if [ "$LOCALREPO8k" = "false" ];
   then
      upgrade8k -verify
   else
      upgrade8k -local -verify
   fi
   status=$?
   if [ $status -ne 0 ];
   then
      logstate "InitiateFallbackRequest"
      if [ "$LOCALREPO8k" = "false" ];
      then
         rm -rf ${REPOSITORY}/upload/*
      fi
      clearstdin
      echo -n "upgrade8k: Press enter to fallback : "
      read answer
      logstate "InitiateFallbackAccept"
      upgrade8k -quiet -fallback
      logstate "UpgradeReset"
      exit $SETUPIMAGEFAILED
   fi

   textncolor $BoldCyan "upgrade8k: Verify ends for live upgrade."
   textncolor $BoldCyan "End:`date`"

   comparepatchset

   #[2]. Create exported data
   logstate "ExportClusterData"
   if [ "$EXPORT" = "true" ];
   then
      if [ "$QUIETINSTALL8k" = "true" ];
      then
         if [ "$HWMIGRATION" = "true" ];
         then
            export8k -hw -quiet -liveexp 
         else
            export8k -quiet -liveexp -local
         fi
      else
         if [ "$HWMIGRATION" = "true" ];
         then
            export8k -hw -liveexp 
         else
            export8k -liveexp -local
         fi
      fi
   else
      rm -rf /software/toolkit
      if [ "$uexport" = "true" ];
      then
         mkdir -p /software/toolkit/${mynode} 
         cp -R $USEREXPORT/. /software/toolkit/${mynode}/.
      fi
   fi
   if [ $? -ne 0 ];
   then
       logstate "InitiateFallbackRequest"
       textncolor $BoldRed "upgrade8k: Cannot export data."
       clearstdin
       echo -n "upgrade8k: Press enter to fallback : "
       read answer
       logstate "InitiateFallbackAccept"
       upgrade8k -quiet -fallback
       logstate "UpgradeReset"
       exit $EXPORTDATAFAILED
   fi

   #[3]. Bring current node to #2.
   logstate "BringSystemStateTwo"
   /unisphere/srx3000/srx/startup/srxctrl 2 nc
   if [ $? -ne 0 ];
   then
      logstate "InitiateFallbackRequest"
      textncolor $BoldRed "upgrade8k: srxctrl cannot stop($mynode)."
      clearstdin
      echo -n "upgrade8k: Press enter to fallback : "
      read answer
      logstate "InitiateFallbackAccept"
      upgrade8k -quiet -fallback
      logstate "UpgradeReset"
      exit $SRXCTRLSTOPFAILED
   fi

   #[4]. Ready to install
   textncolor $BoldCyan "upgrade8k: Building boot installer for $mynode."

   #<LocalNode>
      logstate "BuildLiveInstaller"
      if [ "$LOCALREPO8k" = "true" ];
      then
         upgrade8k -local -quiet -buildliveinst
      else
         if [ "$HWMIGRATION" = "true" ];
         then
            upgrade8k -hw -quiet -buildliveinst
         else
            upgrade8k -quiet -buildliveinst
         fi
      fi
      status=$?
      if [ $status -ne 0 ];
      then
         logstate "ResetLiveInstaller"
         upgrade8k -reset
         textncolor $BoldRed "upgrade8k: Cannot build bootable installer."
         logstate "InitiateFallbackRequest"
         clearstdin
         echo -n "upgrade8k: Press enter to fallback : "
         read answer
         logstate "InitiateFallbackAccept"
         upgrade8k -quiet -fallback
         logstate "UpgradeReset"
         textncolor $BoldRed "upgrade8k: Fallback done."
         exit $FAIL
      fi
   #</LocalNode>

  #<DisableBzTest>
      mkdir -p /etc/init.d/zorig
      if [ -f /etc/init.d/bz_node_com_test ];
      then
         mv /etc/init.d/bz_node_com_test /etc/init.d/zorig/bz_node_com_test
      fi
      cat << EOF > /etc/init.d/fallback
#!/bin/sh
### BEGIN INIT INFO
# Provides:          fallback
# Required-Start:
# X-UnitedLinux-Should-Start: $network $syslog inetd srx_security srx_startup swo_startup spt_startup
# Required-Stop:
# X-UnitedLinux-Should-Stop: $network $syslog inetd srx_security srx_startup swo_startup spt_startup
# Default-Start:     3 5
# Default-Stop:      0 1 2 4 6
# Short-Description: xtree
# Description:       xtree
#
### END INIT INFO

. /etc/rc.status
. "${UPGRADEDIAGINC}"
rc_reset

rexit( )
{
   if [ -d /usr/local/lib/systemd ]
   then
      #systemctl disable fallback
      rm /etc/systemd/system/osv.target.wants/fallback.service
   else
      insserv -r fallback
   fi
   insserv 2>/dev/null
   exec rm -f /etc/rc.d/rc3.d/*fallback /etc/init.d/fallback
}

case "\$1" in
    start)
       echo "fallback: Starting fallback."
       if [ -f /etc/sec/setkey.conf ];
       then
          setkey -f /etc/sec/setkey.conf
       else 
          if osv_version.sh --major compare sys ge V9 && [ -f /etc/sec/.setkey.conf ];
          then
             /usr/local/bin/.setipsec -exe >/dev/null 2>&1 
             ipsec_ret=\$?
             echo "[fallback]: Setting ipsec keys from encrypted store, status(\${ipsec_ret})"
          fi	
       fi
       #<IsActivate>
       while ( true )
       do
          if [ -f /etc/init.d/activate ];
          then
             sleep 8
             continue
          else
             break;
          fi
       done
       #</IsActivate>
       upgrade8k -quiet -fallback
       upgrade8k -quiet -reset
       echo "fallback: Will auto collect system data."
       upgrade8k -collect
       ;;
  *)
       echo "fallback: Nothing to do."
       rexit
       ;;
esac
echo "fallback: Done."
rexit
EOF
      insertFallbackService
      chmod 755 /etc/init.d/fallback
      {
         if [ ! -d /usr/local/lib/systemd ]
         then
            insserv -r bz_node_com_test
            insserv fallback
            insserv
         fi
      } 2>/dev/null

   #</DisableBzTest>

   #<SetSrxBootParms>
      echo "2 0 /log/startup_srx.log /log/startup_rtp.log" > \
            /unisphere/srx3000/srx/startup/srxBootParams
   #</SetSrxBootParms>

   dumparpcache "after setupsimplexlive"
   logstate "InstallNodeOne"
   if [ "$HWMIGRATION" = "true" ];
   then
      textncolor $Yellow "upgrade8k: Node#1 ($mynode) will halt."
      textncolor $Yellow "upgrade8k: Replace new hardware with DVD and USB. Choose Install."
      echo -n "upgrade8k: Eject DVD and USB drives now and press enter : "
      clearstdin
      read answer
      cmd="halt -p -f"
   else
      textncolor $Yellow "upgrade8k: Node#1 ($mynode) will reboot now to be installed."
      cmd="reboot -f"
   fi

   echo "Done."
   sync
   $cmd 1>>$LOGFILE 2>&1
}

#---------------------------------------------------------------
# function: setupsimplexfallback
# args    : None
# description:
#    rolls back to the old state.
#---------------------------------------------------------------

setupsimplexfallback( ) {
   textncolor $BoldPurple "upgrade8k : Attempting fallback to original state."
   echo "Command: upgrade8k $ARGLIST"  1>>$LOGFILE 2>&1
   logstate "FallbackBegin"
   #<CheckTestBed>
   if [ "$mynode" != "$primhost" ];
   then
      echo "Aborted."
      textncolor $BoldRed "Run upgrade8k from ${primhost} only."
      exit $FAIL
   fi
   #<CheckTestBed>
   if [ "$testbed" != "simplex" ];
   then
      echo "upgrade8k: This interface is valid only on a cluster."
      exit $FAIL
   fi

   if [ "$FORCE8k" = "true" ];
   then
      force="-f"
   fi

   #<GetSessionT>
      sessiont=""
      if [ -f /repository/sessiont.txt ];
      then
         sessiont=`cat /repository/sessiont.txt 2>/dev/null | grep "^Value" | awk -F':' '{ print $2 }' | sed -e 's/ //g'`
      fi
   #</GetSessionT>

   #<CheckQuietMode>
      if [ -f $LIVEQUIET ];
      then
         export QUIETINSTALL8k=true
      fi
   #</CheckQuietMode>

   logstate "FallbackBeginPrompt"
   if [ "$QUIETINSTALL8k" != "true" ];
   then
      while ( true )
      do
         echo -n "Do you wish to continue (yes/no)? "
         clearstdin
         read answer
         if [ "$answer" = "yes" -o "$answer" = "no" ];
         then
            if [ "$answer" = "no" ];
            then
               echo "Aborted."
               exit $FAIL
            else
               break;
            fi
         fi
         continue
      done
   fi
   logstate "FallbackBeginAccept"

   rm -f $LIVEQUIET
   rm -f $LIVESWITCH
   rm -f $HWSWITCH
   activemode="`cat /img/logimg/${activeimg}/upgrade.lock 2>/dev/null | head -1`"
   passivemode="`cat /img/logimg/${passiveimg}/upgrade.lock 2>/dev/null | head -1`"
   if [ "$activemode" = "" -a "$passivemode" = "" ];
   then
      iptables -nL firewall 1>/dev/null 2>&1
      if [ $? -eq 0 -o "$FORCE8k" = "true" ];
      then
         passivemode="OutageFree"
      fi
   fi

   
   #<IpSecKeys>
   if [ ! -f /etc/sec/setkey.conf -a ! -f /etc/sec/.setkey.conf ]
   then
      textncolor $BoldRed "No ipsec key conf file found on $mynode"
   fi

   setkey -D | egrep -q "esp|ah"
   keystatus=$?
   if [ -f /etc/sec/setkey.conf -a $keystatus -ne 0 ];
   then
      setkey -f /etc/sec/setkey.conf
   else
      if osv_version.sh --major compare sys ge V9 && [ -f /etc/sec/.setkey.conf ] && [ $keystatus -ne 0 ];
      then
         /usr/local/bin/.setipsec -exe
         ipsec_ret=$?
         textncolor $BoldPurple "upgrade8k : Setting ipsec keys from encrypted store, status(${ipsec_ret})" 
      fi	
   fi
   #</IpSecKeys>

   if [ -f /etc/init.d/zorig/bz_node_com_test ];
   then
      mv -f /etc/init.d/zorig/bz_node_com_test /etc/init.d/bz_node_com_test
      insserv bz_node_com_test
      insserv 
   fi 2>/dev/null

   if [ -f /img/rootimg/etc/init.d/zorig/bz_node_com_test ];
   then
      mv -f /img/rootimg/etc/init.d/zorig/bz_node_com_test /img/rootimg/etc/init.d/bz_node_com_test
      chroot /img/rootimg insserv bz_node_com_test
      chroot /img/rootimg insserv 
   fi 2>/dev/null

   logstate "UpgradeReset"
   upgrade8k $force -reset
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "upgrade8k: Outage free upgrade reset failed on $mynode."
   fi
   if [ "$activemode" != "OutageFree" -a "$passivemode" != "OutageFree" ];
   then
      echo "upgrade8k: No live upgrade in progress."
      srxctrl 4 nc
      if [ "$sessiont" != "" ];
      then
         echo "Srx/Sip/Session_Timer=$sessiont"
         su - srx -c "/repository/sessiontctrl $sessiont"
      fi 1>>$LOGFILE 2>&1
      exit $?
   fi
   #</CheckTestBed>

   if [ "$activemode" = "OutageFree" ];
   then
      textncolor $BoldRed "upgrade8k: Your active image initiated live upgrade."
      #[X] Note. In this state you have not started installing target.

      upgrade8k $force -reset
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Outage free upgrade reset failed on $mynode."
      fi
      echo "High availability state :"
      echo "-------------------------"
      if osv_version.sh --major compare sys ge V5;
      then
         crmmon -1
      else
         cftool -n
      fi
      logstate "HeartbeatCheckEnd"
      #</Wait4ClusterUp>

      #<FinishActivation>
          logstate "InitActivation"
         /unisphere/srx3000/srx/bin/activate8k -done
      #</FinishActivation>

      #<RestartSnort>
         systemctl restart IDS.service 1>/dev/null 2>&1 || \
         textncolor $BoldRed "upgrade8k: Failed to restart IDS service"
      #</RestartSnort>

      logstate "BringSystemStateFour"
      srxctrl 4 nc
      if [ "$sessiont" != "" ];
      then
         echo "Srx/Sip/Session_Timer=$sessiont"
         su - srx -c "/repository/sessiontctrl $sessiont"
      fi
   fi

   if [ "$passivemode" = "OutageFree" ];
   then
      textncolor $BoldRed "upgrade8k: Your fallback image initiated live upgrade."
      textncolor $BoldPurple "upgrade8k: Initiating fallback reload."
      killproc srxctrl
      logstate "ResetBootParms"
      echo "2 0 /log/startup_srx.log /log/startup_rtp.log" > \
                 /img/unisphereimg/${passiveimg}/srx3000/srx/startup/srxBootParams

      textncolor $BoldCyan "upgrade8k: Bringing system to state#2."
      logstate "BringSystemStateTwo"
      /unisphere/srx3000/srx/startup/srxctrl 2 nc
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: srxctrl cannot stop($mynode)."
      fi
      logstate "ResetUpgradeContents"
      upgrade8k $force -reset
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Outage free upgrade reset failed on $mynode."
      fi

      logstate "InitiateActivateFallback"
      /unisphere/srx3000/srx/bin/activate8k -f -local -manual
      if [ $? -ne 0 ];
      then
         textncolor $BoldRed "upgrade8k: Initiating fallback reload failed($mynode)."
         exit $FAIL
      fi

      sync
      logstate "InitiateActivateFallbackReboot"
      if [ "$HWMIGRATION" = "true" ];
      then
         textncolor $BoldRed "upgrade8k: Node#1 ($mynode) will halt."
         textncolor $BoldRed "upgrade8k: Replace old hardware."
         rm -f $HWLOCK $HWSWITCH
         halt -p -f
      else
         /unisphere/srx3000/srx/bin/activate8k -f -local -reboot
      fi
      sync
   fi
   logstate "FallbackEnd"
   textncolor $Yellow "upgrade8k: Fallback complete."
   echo "Done."

}

#---------------------------------------------------------------
# function: setupsimplexcommit
# args    : None
# description:
#   commits the transactions. Installs load on 2nd node.
#---------------------------------------------------------------

setupsimplexcommit( )
{
   textncolor $BoldPurple "upgrade8k : Commiting upgrade."
   echo "Command: upgrade8k $ARGLIST"  1>>$LOGFILE 2>&1
   logstate "CommitBegin"
   #<CheckTestBed>
   if [ "$mynode" != "$primhost" ];
   then
      echo "Aborted."
      textncolor $BoldRed "Run upgrade8k from ${primhost} only."
      exit $FAIL
   fi

   #<CheckSwitch>
      if [ ! -f $LIVESWITCH ];
      then
         echo "upgrade8k: This interface is valid only after a traffic switch."
         exit $FAIL
      fi
   #<CheckSwitch>

   #<CheckTestBed>
   if [ "$testbed" != "simplex" ];
   then
      echo "upgrade8k: This interface is valid only on a cluster."
      exit $FAIL
   fi
   #</CheckTestBed>
 
   setkey -f /etc/sec/setkey.conf

   #<GetSessionT>
      sessiont=""
      if [ -f /repository/sessiont.txt ];
      then
         sessiont=`cat /repository/sessiont.txt 2>/dev/null | grep "^Value" | awk -F':' '{ print $2 }' | sed -e 's/ //g'`
      fi
   #</GetSessionT>

   #<RestoreSessionT>
      if [ "$sessiont" != "" ];
      then
         echo "Srx/Sip/Session_Timer=$sessiont"
         su - srx -c "/repository/sessiontctrl $sessiont"
      fi 1>>$LOGFILE 2>&1
   #</RestoreSessionT>

   rm -f $LIVEQUIET
   rm -f $LIVESWITCH
   rm -f $HWSWITCH

   logstate "CommitEnd"
   echo "Done."

}

#---------------------------------------------------------------
# function: setupsimplexswitch
# args    : None
# description:
#   sets up commit sequence. firewall's node#2, node#1 to handle
#   traffic.
#---------------------------------------------------------------

setupsimplexswitch( ) {
   textncolor $BoldPurple "upgrade8k : Switching traffic."
   logstate "TrafficSwitchBegin"
   #<CheckTestBed>
   if [ "$mynode" != "$primhost" ];
   then
      echo "Aborted."
      textncolor $BoldRed "Run upgrade8k from ${primhost} only."
      exit $FAIL
   fi
   #<CheckTestBed>
   if [ "$testbed" != "simplex" ];
   then
      echo "upgrade8k: This interface is valid only on a cluster."
      exit $FAIL
   fi
   #</CheckTestBed>

   mylayout=`/unisphere/srx3000/srx/bin/sync8k -q none`
   mypart="`echo $mylayout | awk -F ',' '{ print $1 }'   \
                           | sed -e 's/secondary.*/\u&/' \
                                 -e 's/primary.*/\u&/'   \
                                 -e 's/://g'`"
   logstate "$mypart"

   #<CheckPorts>
   checkSIPports
   #</CheckPorts>

   #<CheckQuietMode>
      if [ -f $LIVEQUIET ];
      then
         export QUIETINSTALL8k=true
      fi
   #</CheckQuietMode>
   if [ "$QUIETINSTALL8k" != "true" ];
   then
      while ( true )
      do
         echo -n "Do you wish to continue (yes/no)? "
         clearstdin
         read answer
         if [ "$answer" = "yes" -o "$answer" = "no" ];
         then
            if [ "$answer" = "no" ];
            then
               echo "Aborted."
               exit $FAIL
            else
               break;
            fi
         fi
         continue
      done
   fi

   touch $LIVESWITCH
   if [ "$HWMIGRATION" = "true" ];
   then
      touch $HWSWITCH
   fi
   logstate "RestartSnort"

   #<RestartSnort>
         systemctl restart IDS.service 1>/dev/null 2>&1 || \
         textncolor $BoldRed "upgrade8k: Failed to restart IDS service"
   #</RestartSnort>
   logstate "TrafficSwitchEnd"
   sync
}

#---------------------------------------------------------------
# function: collectlogs
# args    : None
# description:
#   collect all logs needed for dignosis of upgrade.
#---------------------------------------------------------------

collectlogs( )
{
   textncolor $BoldCyan "upgrade8k: Data collection mode."
   textncolor $BoldCyan "Note: Enter root password if prompted."
   if [ "$testbed" = "cluster" ];
   then
      /usr/bin/trace8k -quiet -dual
      scp $othernode:/log/data-*.tar.gz /log/.
      textncolor $BoldGreen "Consolidating logs under /log/data-$clustername.tar.gz"
      chown srx.${srxgroup}  /log/data-*.tar.gz
      chmod ug+r /log/data-*.tar.gz
      tar -zcvf /log/data-$clustername.tar.gz /log/data-$mynode-*.tar.gz /log/data-$othernode-*.tar.gz
      rm -rf /log/data-$mynode-*.tar.gz /log/data-$othernode-*.tar.gz
      ssh $othernode -o ConnectTimeout=8 " rm -rf /log/data-$mynode-*.tar.gz /log/data-$othernode-*.tar.gz"
      chown srx.${srxgroup}  /log/data-*.tar.gz
      chmod ug+r /log/data-*.tar.gz
   else
      textncolor $BoldGreen "Consolidating logs under /log/data-$clustername.tar.gz"
      /usr/bin/trace8k -quiet
      mv -f /log/data-$mynode-*.tar.gz /log/data-$clustername.tar.gz
      chown srx.${srxgroup}  /log/data-*.tar.gz
   fi  
}

#---------------------------------------------------------------
# function: displaystatus
# args    : None
# description:
#   display the last state for live upgrade.
#---------------------------------------------------------------

displaystatus( )
{
    export LOG8k4TOOLKIT=""
    if [ "$testbed" = "cluster" ];
    then
    {
       scp -o ConnectTimeout=2 $othernode:/repository/upgrade8k-timing /tmp/upgrade8k-timing
       if [ -f /tmp/upgrade8k-timing ];
       then
          chown srx.${srxgroup} /tmp/upgrade8k-timing
          chmod a+rw /tmp/upgrade8k-timing
       fi
       cat /repository/upgrade8k-timing >> /tmp/upgrade8k-timing
    } 
    else
       rm -f /tmp/upgrade8k-timing
       cat /repository/upgrade8k-timing > /tmp/upgrade8k-timing
       chown srx.${srxgroup} /tmp/upgrade8k-timing
       chmod a+rw /tmp/upgrade8k-timing
    fi 2>/dev/null
    cat /tmp/upgrade8k-timing | awk '{ split($3,timex,"/"); print timex[3]"/"timex[1]"/"timex[2]," ",$4,"",$2 }' | sort > /tmp/upgrade8k-timing.sort
    chown srx.${srxgroup} /tmp/upgrade8k-timing /tmp/upgrade8k-timing.sort
    laststate=`cat /tmp/upgrade8k-timing.sort 2>/dev/null | tail -1 | awk '{ print $3 }'`
    timestate=`cat /tmp/upgrade8k-timing.sort 2>/dev/null | tail -1 | awk '{ print $2 }'`

    echo ">Upgrade State"
    if [ "$laststate" != "" ];
    then
       echo " state: $laststate at $timestate"
       if [ "$laststate" = "NoError" ];
       then
          echo "status: completed"
       else
          if [ "$laststate" = "UpgradeReset" -o "$laststate" = "UpgradeResetCmd" ];
          then
             echo "status: failed"
          else
             echo "status: progress"
          fi
       fi
       echo "detail: ${statestr[`statecount ${laststate}`]}"
    else
       echo " state: No upgrade in progress."
       echo "status: idle"
       echo "detail: none."
    fi
    echo ">Upgrade Timing"
    cat /tmp/upgrade8k-timing | awk '{ print $3," ",$4,"",$2 }' | sort |  uniq
}

#---------------------------------------------------------------
# function: statecount
# args    : None
# description:
#   convert string to count.
#---------------------------------------------------------------

statecount( )
{
   case $1 in
      "NoError")
         echo 0
         ;;
      "ActivePrimary")
         echo 2
         ;;
      "ActiveSecondary")
         echo 4
         ;;
      "BringSystemStateTwo")
         echo 6
         ;;
      "BuildLiveInstaller")
         echo 8
         ;;
      "CheckLocalDvdIntegrity")
         echo 10
         ;;
      "CheckRemoteDvdIntegrity")
         echo 12
         ;;
      "CommitBegin")
         echo 14
         ;;
      "CommitEnd")
         echo 16
         ;;
      "ExportClusterData")
         echo 18
         ;;
      "FallbackBegin")
         echo 20
         ;;
      "FallbackBeginAccept")
         echo 22
         ;;
      "FallbackBeginPrompt")
         echo 24
         ;;
      "FallbackEnd")
         echo 26
         ;;
      "HeartbeatCheckBegin")
         echo 28
         ;;
      "HeartbeatCheckEnd")
         echo 30
         ;;
      "InitActivation")
         echo 32
         ;;
      "InitiateActivateFallback")
         echo 34
         ;;
      "InitiateActivateFallbackReboot")
         echo 36
         ;;
      "InitiateFallbackAccept")
         echo 38
         ;;
      "InitiateFallbackRequest")
         echo 40
         ;;
      "InitiatePublisher")
         echo 42
         ;;
      "InstallNodeOne")
         echo 44
         ;;
      "InstallNodeTwo")
         echo 46
         ;;
      "JoinLocalHeartbeat")
         echo 48
         ;;
      "JoinLocalXChannel")
         echo 50
         ;;
      "JoinLocalXchComplete")
         echo 52
         ;;
      "JoinRemoteHeartbeat")
         echo 54
         ;;
      "JoinRemoteXChannel")
         echo 56
         ;;
      "JoinXChannelFailed")
         echo 58
         ;;
      "OpenXChannelSSH")
         echo 60
         ;;
      "OpenXChannelSSHEmpty")
         echo 62
         ;;
      "OpenXChannelSSHFailed")
         echo 64
         ;;
      "ResetBootParms")
         echo 66
         ;;
      "ResetLiveInstaller")
         echo 68
         ;;
      "ResetUpgradeContents")
         echo 70
         ;;
      "RestartSnort")
         echo 72
         ;;
      "SplitXChannelFailed")
         echo 74
         ;;
      "SplitXChannelLazy")
         echo 76
         ;;
      "SplitXChLocalStrict")
         echo 78
         ;;
      "StopLocalHeartbeat")
         echo 80
         ;;
      "SwitchXchRemoteStrict")
         echo 82
         ;;
      "BringSystemStateFour")
         echo 84
         ;;
      "TerminatePublisher")
         echo 86
         ;;
      "TrafficSwitchBegin")
         echo 88
        ;;
      "TrafficSwitchEnd")
         echo 90
         ;;
      "UpgradeHealthCheck")
         echo 92
         ;;
      "UpgradeReset")
         echo 94
         ;;
      "VerifyLocalNodeCfg")
         echo 96
         ;;
      "VerifyRemoteNodeCfg")
         echo 98
         ;;
      "ZenTagComparison")
         echo 100
         ;;
      "InitiateImportNodeOne")
         echo 102
         ;;
      "InitiateImportNodeTwo")
         echo 104
         ;;
      "ImportFailed")
         echo 106
         ;;
      "ImportCompletedNodeOne")
         echo 108
         ;;
      "ImportCompletedNodeTwo")
         echo 110
         ;;
      "InitiateTrafficSwitch")
         echo 112
         ;;
      "ProcessCheckFailed")
         echo 114
         ;;
      "XtreeSreviceDone")
         echo 116
         ;;
      "DataCollect")
         echo 118
         ;;
      "InitOsvUpgrade")
         echo 120
         ;;
      "InstallToolkit")
         echo 122
         ;;
      "InstallToolkitFailed")
         echo 122
         ;;
      "BuildRtpNodeOne")
         echo 124
         ;;
      "BuildRtpNodeTwo")
         echo 126
         ;;
      "BringSystemStateThree")
         echo 128
         ;;
      "LiveUpgradeLocalDone")
         echo 130
         ;;
      "InitiateImportTwo")
         echo 132
         ;;
      "UpgradeResetCmd")
         echo 134
         ;;
      "SetupImage")
         echo 136
         ;;
      "UnknownState")
         echo 200
         ;;
      *)
         echo 200
         ;;
   esac
}

#---------------------------------------------------------------
# function: initerrmapping
# args    : None
# description:
#   all error states logged into upgrade8k-timing, will have a
#   detail description here.
#---------------------------------------------------------------

initerrmapping( )
{
   statestr[`statecount "NoError"`]="Success"
   statestr[`statecount "ActivePrimary"`]="Current node running on primary side."
   statestr[`statecount "ActiveSecondary"`]="Current node running on secondary side."
   statestr[`statecount "BringSystemStateTwo"`]="State change,$primhost will now go to state#2."
   statestr[`statecount "BringSystemStateThree"`]="State change,system will now go to state#3."
   statestr[`statecount "BuildRtpNodeOne"`]="Create RTP on $primhost."
   statestr[`statecount "BuildRtpNodeTwo"`]="Create RTP on $sechost."
   statestr[`statecount "BuildLiveInstaller"`]="Install boot loader being built."
   statestr[`statecount "CheckLocalDvdIntegrity"`]="Dvd integrity checked on $primhost."
   statestr[`statecount "CheckRemoteDvdIntegrity"`]="Dvd integrity checked on $sechost."
   statestr[`statecount "CommitBegin"`]="Node $primhost ready to commit upgrade."
   statestr[`statecount "CommitEnd"`]="Node $primhost finished commiting upgrade."
   statestr[`statecount "ExportClusterData"`]="Data will be exported cluster wide."
   statestr[`statecount "FallbackBegin"`]="Fallback attempted on $primhost."
   statestr[`statecount "FallbackBeginAccept"`]="Accept fallback request on $primhost."
   statestr[`statecount "FallbackBeginPrompt"`]="Waiting for user input to accept fallback."
   statestr[`statecount "FallbackEnd"`]="Fallback actions completed."
   statestr[`statecount "HeartbeatCheckBegin"`]="Checking heartbeat across cluster."
   statestr[`statecount "HeartbeatCheckEnd"`]="Heartbeat stable across cluster."
   statestr[`statecount "InitActivation"`]="Activating current node to join cluster."
   statestr[`statecount "InitiateActivateFallback"`]="Local fallback on $primhost will now be attempted."
   statestr[`statecount "InitiateActivateFallbackReboot"`]="Local node $primhost will now be rebooted."
   statestr[`statecount "InitiateFallbackAccept"`]="User has accepted to fallback."
   statestr[`statecount "InitiateFallbackRequest"`]="User is now prompted to fallback."
   statestr[`statecount "InitiatePublisher"`]="Initiate arp publishing."
   statestr[`statecount "InstallNodeOne"`]="Node $mynode will now be installed."
   statestr[`statecount "InstallNodeTwo"`]="Node $othernode will now be installed."
   statestr[`statecount "XtreeSreviceDone"`]="init service xtree is now done."
   statestr[`statecount "InitiateImportNodeOne"`]="Node $primhost will now import data."
   statestr[`statecount "InitiateImportNodeTwo"`]="Node $sechost will now import data."
   statestr[`statecount "ImportFailed"`]="Could not import data on $mynode."
   statestr[`statecount "ImportCompletedNodeOne"`]="Node $primhost imported data successfully."
   statestr[`statecount "ImportCompletedNodeTwo"`]="Node $sechost imported data successfully."
   statestr[`statecount "InitOsvUpgrade"`]="Initiate upgrade on $primhost."
   statestr[`statecount "InstallToolkit"`]="Toolkit is being installed."
   statestr[`statecount "InstallToolkitFailed"`]="Toolkit could not be installed."
   statestr[`statecount "DataCollect"`]="Initiate data collection of system data."
   statestr[`statecount "InitiateTrafficSwitch"`]="Node $primhost will now attempt traffic switch."
   statestr[`statecount "ProcessCheckFailed"`]="Process check failed on one of the nodes."
   statestr[`statecount "JoinLocalHeartbeat"`]="Node $primhost will now join hearbeat monitoring."
   statestr[`statecount "JoinLocalXChannel"`]="Node $primhost will now join cluster."
   statestr[`statecount "JoinLocalXchComplete"`]="Node $primhost joins the cluster successfully."
   statestr[`statecount "JoinRemoteHeartbeat"`]="Node $sechost will join hearbeat monitoring."
   statestr[`statecount "JoinRemoteXChannel"`]="Node $sechost will now join cluster."
   statestr[`statecount "JoinXChannelFailed"`]="Could not join x-channel."
   statestr[`statecount "OpenXChannelSSH"`]="Both nodes can now communicate over x-channel via ssh."
   statestr[`statecount "OpenXChannelSSHEmpty"`]="No firewall setup to open ssh via x-channel."
   statestr[`statecount "OpenXChannelSSHFailed"`]="Could not open ssh via x-channel."
   statestr[`statecount "ResetBootParms"`]="Fallback image will be altered to boot to state#2."
   statestr[`statecount "ResetLiveInstaller"`]="System will be restored, unable to build installer."
   statestr[`statecount "ResetUpgradeContents"`]="All setup for upgrades will noe be cleaned."
   statestr[`statecount "RestartSnort"`]="Snort monitoring will now be started."
   statestr[`statecount "SplitXChannelFailed"`]="Could not offline $primhost."
   statestr[`statecount "SplitXChannelLazy"`]="Node $primhost will remove itself from x-channel."
   statestr[`statecount "SplitXChLocalStrict"`]="Node $primhost will now be offlined."
   statestr[`statecount "StopLocalHeartbeat"`]="Hearbeat will be stopped on $primhost."
   statestr[`statecount "SwitchXchRemoteStrict"`]="Node $sechost will now be offlined."
   statestr[`statecount "SetupImage"`]="Relocating image for install."
   statestr[`statecount "BringSystemStateFour"`]="System will now come to state#4."
   statestr[`statecount "TerminatePublisher"`]="Arp publishing is not terminated."
   statestr[`statecount "TrafficSwitchBegin"`]="Traffic will be switched to node#${primhost}"
   statestr[`statecount "TrafficSwitchEnd"`]="Traffic switched successfully to node#${primhost}"
   statestr[`statecount "UpgradeHealthCheck"`]="Sanity checks on machines to be upgraded."
   statestr[`statecount "UpgradeReset"`]="Upgrade contents will now be reset."
   statestr[`statecount "UpgradeResetCmd"`]="Forcing an upgrade reset."
   statestr[`statecount "VerifyLocalNodeCfg"`]="Verify node.cfg on $primhost."
   statestr[`statecount "VerifyRemoteNodeCfg"`]="Verify node.cfg on $sechost."
   statestr[`statecount "ZenTagComparison"`]="Compare the target node.cfg tags with source."
   statestr[`statecount "LiveUpgradeLocalDone"`]="Live upgrade done one one node."
   statestr[`statecount "InitiateImportTwo"`]="Import will now be done on $sechost."
   statestr[`statecount "UnknownState"`]="Conversion is unknown."
}

textncolor $BoldRed "calling upgrade8k $@"
ARGLIST="$*"

# Do not interact with auditing when displaying upgrade status 
if [ "$1" = "-s" ]
then
   CHECK_AUDIT=false
else
   CHECK_AUDIT=true
fi

initvars
checksys
     
while [ "$#" -gt "0" ];
do
   case $1 in
      -h)
         usage
	 exit $SUCCESS
	 ;;
      -f)
         FORCE8k=true
         ;;
      -s)
         displaystatus
         exit $SUCCESS
         ;;
      -hw)
         # DO NOT USE IT. This is a depricated option.
         # If you want to do a hardware migration use -hwmigration option instead.
         HWMIGRATION=true
         ;;
      -hwmigration)
         HWMIGRATION=true
         hwmigration
         ;;
      -local)
         LOCALREPO8k=true
         ;;
      -setrepository)
         if [ "$LOCALREPO8k" = "false" ];
         then
            checkremote "-local" "-setrepository"
         fi
         setrepository
	 exit $SUCCESS
	 ;;
      -reconfig)
         RECONFIG8k=true;
         export SYNC8k=true
         RECONFIGARGS="$RECONFIGARGS -reconfig"
	 ;;
      -quiet)
         export QUIETINSTALL8k=true
         RECONFIGARGS="$RECONFIGARGS -quiet"
         ;;
      -nosoliddebug)
         export NOSOLIDDEBUG=true
         RECONFIGARGS="$RECONFIGARGS -nosoliddebug"
         ;;
      -reconfigvapp)
         VAPP8k=true
         RECONFIG8k=true;
         export QUIETINSTALL8k=true
         export SYNC8k=false
         RECONFIGARGS="-reconfigvapp"
	 ;;
      -nfs)
         shift
         NFSARG=$1
         NFSIP="`echo    $NFSARG  | awk -F':' '{ print $1 }'`"   
         NFSPATH="`echo  $NFSARG  | awk -F':' '{ print $2 }'`"
         NFSISO="`echo   $NFSARG  | awk -F':' '{ print $3 }'`"   
         NFSIP=${NFSIP:-${nfsip}}
         NFSPATH=${NFSPATH:-"/export/home/units/nfs"}
         if [ "$NFSARG" = "" -o "$NFSIP" = "" -o "$NFSISO" = "" ];
         then
            textncolor $BoldRed "upgrade8k: Missing information for NFS upgrades."
            exit $SETUPIMAGEFAILED
         fi
         ;;
      -noimport)
         IMPORT=false
         ;;
      -setup)
         REMOTE8kCMD=true
         upgrade
         exit $SUCCESS
         ;;
      -verify)
         MediaHome=/mnt
         #<CheckDev>
             if [ "$LIVE8kUPGRADE" != "true" ];
             then
                echo "upgrade8k: Checking local repository for upgrade contents."
                test -r /repository/upload/node.cfg.primary
                localstatus=$?
                if [ "$testbed" = "cluster" ];
                then
                   ssh $othernode "test -r /repository/upload/node.cfg.secondary" 1>/dev/null 2>&1
                   remotestatus=$?
                   if [ $localstatus -eq 0 -o $remotestatus -eq 0 ];
                   then
                      if [ $localstatus -eq 0 -a $remotestatus -eq 0 ];
                      then
                         LOCALREPO8k=true
                         logstr "   - Will use local repository for upgrade."
                         checkdualmedia
                      else
                         textncolor $BoldRed "upgrade8k: Partial data found in repository."
                         textncolor $BoldRed "upgrade8k: check /repository/upload of both nodes."
                         logstate "UpgradeReset"
                         exit $FAIL
                      fi
                   else
                      logstr "   - Will use dvd media for upgrade."
                   fi
                else
                   echo "upgrade8k: Checking local repository for upgrade contents."
                   test -r /repository/upload/node.cfg.primary
                   localstatus=$?
                   if [ $localstatus -eq 0 ];
                   then
                      LOCALREPO8k=true
                      logstr "   - Will use local repository for upgrade."
                      checkdualmedia
                   else
                      logstr "   - Will use dvd media for upgrade."
                   fi
                fi
             fi
         #</CheckDev>

         checkcontents      /repository/upload
         checkpsintegrity   /repository/upload
         if [ "$LOCALREPO8k" = "false" ];
         then
            mount -o ro /dev/hda $MediaHome 1>/dev/null 2>&1
            mountstatus=$?
            if [ $mountstatus -ne 0 ];
            then
               mount -o ro /dev/sr0 $MediaHome 1>/dev/null 2>&1
               mountstatus=$?
            fi
            if [ $mountstatus -ne 0 ];
            then
               mount -o ro /dev/sr1 $MediaHome 1>/dev/null 2>&1
               mountstatus=$?
            fi
            if [ $mountstatus -eq 0 ];
            then
               MOUNT8kDEV=true
               checkisointegrity  $MediaHome 
               umount $MediaHome 2>/dev/null
               echo "Done."
            else
               textncolor $BoldRed "upgrade8k: Failed to mount dvd($mynode)."
               exit $SETUPIMAGEFAILED
            fi
         else
               checkisointegrity  /repository/upload
         fi
         exit $SUCCESS
         ;;
      -nosync)
         SYNC8k=false
         ;;
      -init)
         INITOSV8k=true
         ;;
      -clean|-reset|-rclean|-rreset)
         rm -f $HWLOCK /img/rootimg/$HWLOCK $HWSWITCH
         #<Check4Remote>
         if [ "$1" = "-clean" -o "$1" = "-rclean" ];
         then
            CLEAN8k=true
         fi
         if [ "$1" = "-rclean" -o "$1" = "-rreset" ];
         then
            REMOTE8kCMD=true
         fi
         #<Check4Remote>
         if [ "$mynode" = "$sechost" -a "$REMOTE8kCMD" != "true" ];
         then
            textncolor $BoldRed "Sorry, Remote upgrades can be run from $primhost only!."
            exit $UNKNOWNINSTTYPE
         fi
         activemode="`cat /img/logimg/${activeimg}/upgrade.lock 2>/dev/null | head -1`"
         passivemode="`cat /img/logimg/${passiveimg}/upgrade.lock 2>/dev/null | head -1`"
         if [ "$activemode" = "OutageFree" ];
         then
            rm -f /img/logimg/${activeimg}/upgrade.lock
         fi
         if [ "$passivemode" = "OutageFree" ];
         then
            rm -f /img/logimg/${passiveimg}/upgrade.lock
         fi
         if [ "$1" = "-reset" -o "$1" = "-rreset" ];
         then
            if [ "$INITOSV8k" = "true" ];
            then
               logstate "InitUpgradeResetCmd"
               if [ -f ${REPOSITORY}/upload/version ]
               then
                  rm -rf ${REPOSITORY}/upload/version
               fi
            else
               logstate "UpgradeResetCmd"
            fi
            echo "Restoring data back to shared repository."
            {
            for idx in `find ${REPOSITORY}/upload -name \*.zip`
            do
               basezip=`basename $idx .zip | sed -e 's/^c-//g'`
               rm -f ${REPOSITORY}/media/patch/${basezip}.*
            done
            mv -f ${REPOSITORY}/media/node.cfg.*     ${REPOSITORY}/upload
            mv -f ${REPOSITORY}/media/response.cfg.* ${REPOSITORY}/upload
            mv -f ${REPOSITORY}/media/patch/*        ${REPOSITORY}/upload
            mv -f ${REPOSITORY}/media/iso/*          ${REPOSITORY}/upload
            mv -f ${REPOSITORY}/media/*.lic          ${REPOSITORY}/upload
            mv -f ${REPOSITORY}/media/export/*.lic   ${REPOSITORY}/upload
            } 2>/dev/null
         else
            echo "Cleaning remote upgrade information in shared repository."
         fi
         if [ "$INITOSV8k" = "true" ];
         then
            AUXARGS="-init"
         else
            AUXARGS=""
         fi
         if [ "$1" = "-clean" ];
         then
            checkremote "$AUXARGS -rclean"
         fi
         if [ "$1" = "-reset" ];
         then
            checkremote "$AUXARGS -rreset"
         fi
         cleanup
         export QUICKRESET8k="true"
         /unisphere/srx3000/srx/bin/activate8k -reset 2>/dev/null
         echo "Done."
         exit $SUCCESS
         ;;
      -live)
         LIVE8kUPGRADE=true
         if [ "$testbed" = "cluster" ];
         then
            setuplive
         else
            setupsimplexlive
         fi
         exit $SUCCESS
         ;;
      -switch)
        if [ "$testbed" = "cluster" ];
        then
           setupswitch
        else
           setupsimplexswitch
        fi
        exit $SUCCESS
        ;;
      -commit)
        if [ "$testbed" = "cluster" ];
        then
           setupcommit
        else
           setupsimplexcommit
        fi
        exit $SUCCESS
        ;;
      -fallback)
        if [ "$testbed" = "cluster" ];
        then
           setupfallback
        else
           setupsimplexfallback
        fi
        exit $SUCCESS
        ;;
      -buildinst)
        buildinstaller "iso"
        exit $SUCCESS
        ;;
      -rbuildliveinst)
        LIVE8kUPGRADE=true
        #<SetLocalRepo>
           if [ "$LOCALREPO8k" = "true" ];
           then
              setrepository
              setupimage
           fi
        #</SetLocalRepo>
        buildinstaller "live"
        exit $SUCCESS
        ;;
      -buildliveinst)
        LIVE8kUPGRADE=true
        if [ "$QUIETINSTALL8k" = "true" ];
        then
           LIVEINSTARGS="-quiet -rbuildliveinst"
        else
           LIVEINSTARGS="-rbuildliveinst"
        fi
        if [ "$LOCALREPO8k" = "true" ];
        then
           LIVEINSTARGS="-local $LIVEINSTARGS"
        fi
        if [ "$HWMIGRATION" = "true" ];
        then
           LIVEINSTARGS="-hw $LIVEINSTARGS"
        fi
        checkremote "$LIVEINSTARGS"
        #<SetLocalRepo>
           if [ "$LOCALREPO8k" = "true" ];
           then
              setrepository
              setupimage
           fi
        #</SetLocalRepo>
        buildinstaller "live"
        exit $SUCCESS
        ;;
      -hook)
        livehook
        exit $SUCCESS
        ;;
      -collect)
        collectlogs
        exit $SUCCESS
        ;;
      -noexport)
        EXPORT=false
        tar -ztvf $USEREXPORT/patch/export.tar 1>/dev/null 2>&1
        if [ $? -eq 0 ];
        then
           if [ "$testbed" = "cluster" ];
           then
              ssh $othernode "tar -ztvf $USEREXPORT/patch/export.tar" 1>/dev/null 2>&1
              if [ $? -eq 0 ];
              then
                 IMPORT=true
              else
                 IMPORT=false
              fi
           else
              IMPORT=true
           fi
        else
           IMPORT=false
        fi
        if [ "$IMPORT" = "true" ];
        then
           echo "upgrade8k: Export data detected. Will use this."
        else
           echo "upgrade8k: No Export data detected."
        fi
        ;;
      *)
         echo "Unknown option passed."
         usage
         exit $FAIL
         ;;
   esac
   shift
done

upgrade
