#!/bin/bash

# -------------------------------------------------------
# file   : prepare8k.sh
# purpose: Installation script to install fallback image.
# author : Vittal.S
#
# usage  : prepare8k
#
# modifications:
# 03-05-08  Initial Creation .
# -------------------------------------------------------
#testing the ci
### Constants

DBA="DBA"
DBA_PASSWDFILE="/opt/solid/RtpDb/dba.secrets"
RTP_USER_40="RTP_USER_40"
RTP_USER_40_PASSWDFILE="/unisphere/srx3000/srx/.rtp_user_40.secrets"
OSVUSER="OSVUSER"
OSVUSER_PASSWDFILE="/unisphere/srx3000/srx/.osvuser.secrets"

_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"

if [ -e /usr/sbin/iptables ]
then
IPTABLESPATH=/usr/sbin/
fi

### Include files
source ${COMMON8K} || exit 1
if [[ -f "${UPGRADEDIAGINC}" ]]; then
   source "${UPGRADEDIAGINC}"
else
   srxctrl() { /unisphere/srx3000/srx/startup/srxctrl "${@}"; }
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

adaptkeyboard()
{
   # yast keyboard summary writes on stderr
   current_keyboard=$(yast keyboard summary 2>&1 | awk ' { print $NF } ')
   nodecfg_kbd=$(cfgread keyboard_layout)
   if [ "$nodecfg_kbd" != "$current_keyboard" ]
   then
      if osv_version.sh --major compare sys ge V11
      then
	yast keyboard set layout="$nodecfg_kbd"
      fi
   fi
}

### Functions

#snmpV3restore is to restore the /var/lib/net-snmp/snmpd.conf and /usr/share/snmp/snmpd.conf
snmpV3restore()
{
   systemctl status snmpd.service >> $LOGFILE
   systemctl stop snmpd.service

   #SNMP had a implementation in some previous versions and adds the users in /usr/share/snmp/snmpd.conf, but now has different and /usr/share/snmp/snmpd.conf doesnt't exist
   #so we should cover all cases to deliver the functionality of SNMP users
   if [ -s "${EXPORTDIR}/usr/share/snmp/snmpd.conf" ]; then #Upgrade from version with old SNMP functionality 
      if [ -f /usr/share/snmp/snmpd.conf ]; then   # to version with old SNMP functionality
         cp "${EXPORTDIR}/usr/share/snmp/snmpd.conf" /usr/share/snmp/snmpd.conf
      elif [ -f /etc/snmp/snmpd.conf ]; then  # to version with new SNMP functionallity so transfer the users from /usr/share/snmp/snmpd.conf to /etc/snmp/snmpd.conf
         grep "^rouser \|^rwuser " "${EXPORTDIR}/usr/share/snmp/snmpd.conf" >> /etc/snmp/snmpd.conf
      fi
   elif [ -f "${EXPORTDIR}/etc/snmp/snmpd.conf" ]; then  #Upgrade from version with new SNMP functionality 
      cp "${EXPORTDIR}/etc/snmp/snmpd.conf" /etc/snmp/snmpd.conf
   fi

   if [ -f "${EXPORTDIR}/var/lib/net-snmp/snmpd.conf" ];
   then
      cp "${EXPORTDIR}/var/lib/net-snmp/snmpd.conf" /var/lib/net-snmp/snmpd.conf
   fi
   # rm -rf ${EXPORTDIR}/snmpV3safe
   logstr "snmpV3restore is finished"
   systemctl start snmpd.service
}

cloudlinkRestore()
{
   systemctl status cld.service >> $LOGFILE
   if [ -f ${EXPORTDIR}/opt/cloudlink/cld/var/lib/cld/cld.json ]; then
        systemctl stop cld.service
        cp -a ${EXPORTDIR}/opt/cloudlink/cld/var/lib/cld/cld.json /opt/cloudlink/cld/var/lib/cld/cld.json
        systemctl start cld.service
   fi
   logstr "cloudlinkRestore finished"
}


#<FRN2782>
# ----------------------------------------------------------
# function: logstr
# description:
#   logs string to logfile.
# ----------------------------------------------------------

logstr( )
{
   str="$*"

   if [ "$LOG8k4TOOLKIT" != "" -a -w "$LOG8k4TOOLKIT" ];
   then
      echo "`date`: $str" 1>>$LOGFILE 2>/dev/null
   else
      echo "`date`: $str"
   fi
}

# ----------------------------------------------------------
# function: quietread
# description:
#   if interactive is true reads input. Else sets the input 
#   as first arg.
# ----------------------------------------------------------

quietread( )
{
   if [ "$INTERACTIVE8k" = "true" ];
   then
      read answer
   else
      answer=$1
   fi
   echo $answer
}

# ----------------------------------------------------------
# function: nzecho
# description:
#   echo a message only it the nzvar is defined.
# ----------------------------------------------------------

nzecho( )
{
  nzvar=$1
  message="$2"
  if [ ! -z $nzvar ];
  then
     echo "$message"
  fi
}

# ----------------------------------------------------------------
# function: rssh
# args    : none
# description:
#   Make sure  to execure command for partner only in regular mode.
# ----------------------------------------------------------------

rssh( )
{
   if [ "$RECOVER8k" = "false" -a "$LIVE8kUPGRADE" = "false" ];
   then
      ssh $* 2>/dev/null
   else
      logstr "   - Skipping ssh to partner"
   fi
}

rscp( )
{
   if [ "$RECOVER8k" = "false" -a "$LIVE8kUPGRADE" = "false" ];
   then
      scp $* 2>/dev/null
   else
      logstr "   - Skipping scp to partner"
   fi
}

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

cleanarpcache( )
{
      #<ClearARP's>
      for arpidx in `arp -an | grep "incomplete" | awk '{print $2}' |  sed -e 's/(//g' -e 's/)//g'`
      do
          logstr "   - Removing arp cache for $arpidx"
          kver=`uname -r`
          arp -d $arpidx
          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: mkramdisk
# args    : None
# description:
#   make ramdisk if it does not exist. There are two possibilities.
#      - (a) We are doing a fresh install, we do not enter here.
#      - (b) We are upgrading a running system. This call will
#            create ramdisk on running system.
# ----------------------------------------------------------------

mkramdisk( )
{
   mount | grep -q "/dev/ram0"
   if [ $? -ne 0 ];
   then

      logstr "Setting up ramdisk."
      if [ ! -b /dev/ram0 ];
      then
         mknod /dev/ram0 b 1 0
      fi
	umount /dev/ram0 1>/dev/null 2>&1
	mkfs.ext2 -q -F /dev/ram0
      if [ $? -ne 0 ];
      then
         logstr "Sorry. Cannot make ramdisk."
         logstr "This is a error i cannot explain. Contact support for more information."
         exit $FAIL
      fi
      mount /dev/ram0 $RAMDISK
      if [ $? -ne 0 ];
      then
         logstr "Sorry. Cannot mount ramdisk."
         logstr "This is a error i cannot explain. Contact support for more information."
         exit $FAIL
      fi
      mkdir -p $RAMDISK/tmp/disk

   else
     mount | grep "/dev/ram0" | grep -q $RAMDISK
     if [ $? -ne 0 ];
     then
        logstr "Well. Looks like a user mounted ramdisk. Umount and try again."
        exit $FAIL
     fi

   fi

}

# ----------------------------------------------------------------
# function: fumount
# args    : none
# description:
# ----------------------------------------------------------------

fumount( )
{
   umdir=$1
   lsof $umdir | awk '{ print $2 }' | xargs kill -9 1>/dev/null 2>&1
   umount $umdir
}

umountall( )
{
   fumount $MediaHome
   fumount $DISKHOME/cdr
   fumount $DISKHOME/enterprise
   fumount $DISKHOME/global
   fumount $DISKHOME/home
   fumount $DISKHOME/log
   fumount $DISKHOME/opt
   fumount $DISKHOME/software
   fumount $DISKHOME/tmp
   fumount $DISKHOME/tpa
   fumount $DISKHOME/unisphere
   fumount $DISKHOME/var
   fumount $DISKHOME/mnt
   fumount $DISKHOME/sys
   fumount $DISKHOME/dev

   cat $DISKHOME/etc/fstab | grep rootimg
   if [ $? -eq 0 ];
   then
      fumount $DISKHOME/$IMGDIR/cdrimg
      fumount $DISKHOME/$IMGDIR/enterpriseimg
      fumount $DISKHOME/$IMGDIR/globalimg
      fumount $DISKHOME/$IMGDIR/homeimg
      fumount $DISKHOME/$IMGDIR/logimg
      fumount $DISKHOME/$IMGDIR/optimg
      fumount $DISKHOME/$IMGDIR/softwareimg
      fumount $DISKHOME/$IMGDIR/tmpimg
      fumount $DISKHOME/$IMGDIR/tpaimg
      fumount $DISKHOME/$IMGDIR/unisphereimg
      fumount $DISKHOME/$IMGDIR/varimg
      fumount $DISKHOME/$IMGDIR/rootimg
   fi
   umount $RAMDISK
   rm -f $DISKHOME/etc/mtab
   umount $DISKHOME

} 1>/dev/null 2>&1

buildSrxSystemDependentParm( )
{    
    if osv_version.sh --major compare sys ge V7; 
    then
         echo "[${_SELF_}]: Rebuilding SrxSystemDependent.parm for target system."
         /etc/hiq8000/config/bin/dependent_alias_configuration.sh upgrade
         echo "[${_SELF_}]: Rebuilding zASolutionProfile.parm for target system."
         /etc/hiq8000/config/bin/parm_tcn_configuration.sh upgrade
    fi
}

# ---------------------------------------------------------------
# function: trapnexit
# args    : None
# description:
#   when we exit we should unount filesystems we mounted. Plus
#   do additional clean up here.
# ---------------------------------------------------------------

trapnexit( ) {
   setmode $Norm
   umountall
  
   rm -f $CFG8k

   #Restart the sshd on active partition.

   ${RCDIR}/rtp_sshd stop
   ${RCDIR}/rtp_sshd start
   if [ $? -ne 0 ];
   then
      logstr "Failed to start RTP sshd ..."
      exit $FAIL
   fi

   ${RCDIR}/sshd stop
   ${RCDIR}/sshd start
   if [ $? -ne 0 ];
   then
      logstr "Failed to start sshd ..."
      exit $FAIL
   fi
} 2>/dev/null

# -------------------------------------------------------
# function: cleanexit
# args    : None
#   resets invalid access and exists.
# -------------------------------------------------------

cleanexit( )
{
   rm -f $CFG8k
   pam_tally --quiet --reset 1>/dev/null 2>&1
}

# -------------------------------------------------------
# function: remotestate
# args    : None
#   returns the current srxctrl state for partner. if in
#   live upgrade mode the remote note will not be used.
# -------------------------------------------------------

remotestate( )
{
  if [ "$LIVE8kUPGRADE" = "true" ];
  then
     echo nc
  else
     echo $1
  fi
}

# -------------------------------------------------------
# function: getarraynafovar
# args    : None
# description:
#   parses node.cfg for a specific parameter.
# -------------------------------------------------------
getarraynafovar( ) {
   valid=0
   invalid=2
   cfgfilesrc="${1}"
   cfgfiledest="${2}"
   cfgarg="${3}"

   logdebug "[getarraynafovar] Arguments \$1[${1}], \$2[${2}], \$3[${3}]"

   cfgarg=${cfgarg/+/}
   cfgsrcresone="`cat $cfgfilesrc | grep -v '^#'| grep "$cfgarg[ ]*:"      \
                                  | awk -F':' '{ print $2 }' | awk '{ print $4 }'`"
   cfgdestresone="`cat $cfgfiledest | grep -v '^#'| grep "$cfgarg[ ]*:"    \
                                  | awk -F':' '{ print $2 }' | awk '{ print $4 }'`"
   cfgsrcrestwo="`cat $cfgfilesrc | grep -v '^#'| grep "$cfgarg[ ]*:"      \
                                  | awk -F':' '{ print $2 }' | awk '{ print $5 }'`"
   cfgdestrestwo="`cat $cfgfiledest | grep -v '^#'| grep "$cfgarg[ ]*:"    \
                                  | awk -F':' '{ print $2 }' | awk '{ print $5 }'`"
   if [ "$cfgsrcresone" != "" ]
   then
      elemnodecfg[$count]="${cfgarg}"
      srcnodecfg[$count]="${cfgsrcresone}"
      destnodecfg[$count]="${cfgdestresone}"
   else
      logdebug "[getarraynafovar] Found invalid configuration variable [#${count}, ${cfgarg}, source value=${cfgsrcresone}, destination value=${cfgdestresone}]"

      return $invalid
   fi

   count=$(expr $count + 1)

   if [ "$cfgsrcrestwo" != "" ]
   then
      elemnodecfg[$count]="${cfgarg}"
      srcnodecfg[$count]="${cfgsrcrestwo}"
      destnodecfg[$count]="${cfgdestrestwo}"
   else
      logdebug "[getarraynafovar] Found invalid configuration variable [#${count}, ${cfgarg}, source value=${cfgsrcrestwo}, destination value=${cfgdestrestwo}]"

      return $invalid
   fi

   count=$(expr $count + 1)

   logdebug "[getarraynafovar] Found valid configuration variables [#${count}, ${cfgarg}, source value=${cfgfilesrc}, destination value=${cfgfiledest}]"

   return $valid
}

# -------------------------------------------------------
# function: getarraycfgvar
# args    : None
# description:
#   parses node.cfg for a specific parameter.
# -------------------------------------------------------
getarraycfgvar( ) {
   valid=0
   invalid=2
   cfgfilesrc=$1
   cfgfiledest=$2
   cfgarg=$3

   logdebug "[getarraycfgvar] Arguments \$1[${1}], \$2[${2}], \$3[${3}]"

   specialarg="`echo ${cfgarg:0:1}`"
   cfgarg=${cfgarg/+/}

   # manual parsing for special arg, fcfgread for others so we can also get the IPv6 ones
   if [ "${specialarg}"  = "+" ]
   then
      cfgsrcres="`cat $cfgfilesrc | grep -v '^#'| grep "^[ ]*$cfgarg[ ]*:"    \
                            | awk -F':' '{ print $2 }' | sed -e 's/[ \t]*//g'`"
      cfgdestres="`cat $cfgfiledest | grep -v '^#'| grep "^[ ]*$cfgarg[ ]*:"  \
                            | awk -F':' '{ print $2 }' | sed -e 's/[ \t]*//g'`"
   else
      cfgsrcres="`fcfgread ${cfgfilesrc} $cfgarg`"
      cfgdestres="`fcfgread ${cfgfiledest} $cfgarg`"
   fi
   special=false
   specialold=${cfgsrcres}
   specialnew=${cfgdestres}
   if [ "$cfgsrcres"  != "" -a "$cfgsrcres"  != "0.0.0.0" -a "$cfgsrcres"  != "0.0.0.0/0" -a \
        "$cfgdestres" != "" -a "$cfgdestres" != "0.0.0.0" -a "$cfgdestres" != "0.0.0.0/0" ];
   then
      elemnodecfg[$count]="${cfgarg}"

      if [ "$specialarg" != "+" ];
      then
         srcnodecfg[$count]="${cfgsrcres}"
         destnodecfg[$count]="${cfgdestres}"
         nodecfgflag[$count]="false"
         special=false
      else
         srcnodecfg[$count]="'${cfgsrcres}'"
         destnodecfg[$count]="'${cfgdestres}'"
         nodecfgflag[$count]="true"
         special=true
      fi

      logdebug "[getarraycfgvar] Found valid configuration variable [#${count}, ${cfgarg}, special=${specialarg}${special}, source value=${cfgsrcres}, destination value=${cfgdestres}]"

      return $valid
   else
      logdebug "[getarraycfgvar] Found invalid configuration variable [#${count}, ${cfgarg}, special=${specialarg}${special}, source value=${cfgsrcres}, destination value=${cfgdestres}]"

      return $invalid
   fi
}

# ---------------------------------------------------------------
# function: setup
# args    : None
# description:
# ---------------------------------------------------------------

setup( ) {
   logstr "function: setup is called"
   #[0]. Kill Ez-ip if its running on active system
   {
      pushd $IFWDIR/bin 1>/dev/null 2>&1
      isSNMPv3Lost "setup" "before asclient line:472"
      $IFWDIR/bin/asclient -e killAll 1>/dev/null 2>&1
      isSNMPv3Lost "setup" "after asclient line:474"
      popd 1>/dev/null
      pgrep -f ascripts 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         logstr "EZ  -IP is running on the host system."
         logstr "Please terminate it before upgrade."
         exit $EZIPON
      fi
   }

   #[1]. Stop sshd on the running system

   ${RCDIR}/rtp_sshd stop
   ${RCDIR}/sshd stop

   #[2]. Setup the image onto fallback partition.

   $MediaHome/image/setup

}

mountdvd( ) {

   #<FRN2661-ImageIsoOnFS>
   if [ "$ISOPATH" = "" ];
   then

   while ( true )
   do

   #[1]. Make sure we have the imaging Dvd.
   umount $DVDDIR 2>/dev/null
   mount -o ro /dev/cdrom $DVDDIR

   if [ $? -ne 0 ];
   then
          logstr "-------------------------------------------------------"
          logstr "Dvd rebuild option choosen ..."
          logstr "Insert the Composite 8k imaging disk used for install."
          logstr "This cd/dvd is used for install if the system were to be installed via dvd."
          logstr "We will use this disk to build a bootable iso image."
          logstr "-------------------------------------------------------"
          echo -n "Press enter when done ..."
          answer="`quietread yes`"
          continue
   else
      echo -n "Found a disk.Will check it : "
      if [ -f $DVDDIR/image/deltasig ];
      then
         logstr "ok"
      else
         logstr "failed"
         logstr "Sorry. The dvd you have is not a Composite 8k imaging disk..."
         umount $DVDDIR
         eject 2>/dev/null
         continue
      fi
   fi
   break;

  done

  else
    if ! mount -t iso9660 -o loop ${ISOPATH} $MediaHome
    then
       logstr "Sorry, The iso image in ${ISOPATH} cannot be mounted."
       exit $IMAGEISONOTFOUND
    fi
  fi
  #</FRN2661-ImageIsoOnFS>
}

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

checksys( ) {

   if [ $USER -ne 0 ];
   then
       logstr "You  must be root to run this script."
       exit $UIDMISMATCH
   fi

   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
      logstr "Looks like you are on non imaged disk."
      logstr "This is not supported. Good luck."
      exit $IMGDISKNOTSUPPORTED
   fi
   if  [ $primstatus -eq 0 -a $secstatus -eq 0 ];
   then
      logstr "Look, you have both the active and fallback partitions mounted."
      logstr "This is strange.Cannot proceed with such a configuration."
      exit $STRANGMOUNTPOINTS
   fi

   #<CheckLoadLocked>
      if [ ! -f /log/upgrade.lock ];
      then
         logstr "Current Load is not locked. Lock it with ${_SELF_} -lock and try again."
         exit $CURRENTLOADUNLOCKED
      fi
   #</CheckLoadLocked>
   

   #<CheckRootImg>
   mount | grep -q "${ROOTIMGDIR}/"
   if [ $? -eq 0 ];
   then
      logstr "Check the following mounts:-"
      mount | grep "${ROOTIMGDIR}/"
      exit $EXTRAMOUNTDETECTECTED
   fi
   #</CheckRootImg>

   #<CheckDualLock>
   if [ -f /img/logimg/primary/upgrade.lock -a -f /img/logimg/secondary/upgrade.lock ];
   then
      logstr "Check the upgrade locks on your image. Both partitions are locked."
      exit $DUALLOCKDETECTED
   fi
   #</CheckDualLock>

   if [ -d "$RAMDISK" ];
   then
      ramdiskfiles="`ls -A $RAMDISK`"
      if [ "$ramdiskfiles" != "" ];
      then
         logstr "Well, Check $RAMDISK - Its not empty."
         exit $RAMDISKNOTFREE
      fi
   fi

   logstr "Checking if $RAMDISK is mounted."
   _mount | grep "$RAMDISK"
   if [ $? -ne 0 ];
   then
      rm -rf $RAMDISK
   else
      logstr "Please unmount the following dirs ..."
      _mount | grep "$RAMDISK"
      exit $RAMDISKNOTFREE
   fi
   mkdir -p $MediaHome $USBMEDIADIR $DVDDIR $RAMDISK
   umount $RAMDISK 2>/dev/null
}

# ----------------------------------------------------------------
# function: getnafo
# args    : none
# description:
#   computes nafo ip addresses admin,signaling and billing.
# ----------------------------------------------------------------

getnafo( ) {
   cfgvar="`cfgread $1`"
   eval ${2}="`echo ${cfgvar} | awk '{ print $4 }'`"
   eval ${3}="`echo ${cfgvar} | awk '{ print $5 }'`"
}

# ----------------------------------------------------------------
# function: getallnafo
# args    : none
# description:
#   computes all nafo ip addresses admin,signaling and billing.
# ----------------------------------------------------------------

getallnafo( ) {
   cfgvar="`cat $1| grep \"^[ \t]*${2}\" | awk -F ':' '{ print $2 }'`"
   eval prim${3}ip="`echo ${cfgvar} | awk '{ print $4  }'`"
   eval prim${3}nm="`echo ${cfgvar} | awk '{ print $6  }'`"
   eval prim${3}sn="`echo ${cfgvar} | awk '{ print $7  }'`"
   eval prim${3}br="`echo ${cfgvar} | awk '{ print $8  }'`"
   eval prim${3}if="`echo ${cfgvar} | awk '{ print $2  }'`"

   eval sec${3}ip="`echo ${cfgvar} | awk '{ print $5  }'`"
   eval sec${3}nm="`echo ${cfgvar} | awk '{ print $9  }'`"
   eval sec${3}sn="`echo ${cfgvar} | awk '{ print $10 }'`"
   eval sec${3}br="`echo ${cfgvar} | awk '{ print $11 }'`"
   eval sec${3}if="`echo ${cfgvar} | awk '{ print $3  }'`"
}

# ----------------------------------------------------------------
# function: defaultlicense
# args    : none
# description:
#   we setup license table to default with no violations.
# ----------------------------------------------------------------

defaultlicense( )
{
su - srx -c "$solsql 'tcp 16760' dba $(getDbaPassword) << EOF
delete from LICENSE_MGMT_DATA_T;
commit work;
EOF"
} 1>>$LOGFILE 2>&1

# ---------------------------------------------------------------
# function: initvars
# args    : None
# description:
# ---------------------------------------------------------------

initvars( ) {
   umask 022
   stty intr undef 1>/dev/null 2>&1
   IMGDIR=/img
   ROOTIMGDIR=/img/rootimg
   IFWDIR=/opt/unisphere/srx3000/ifw
   DVDDIR=/media/cdrom
   RAMDISK=/ramdisk
   DISKHOME=${RAMDISK}/tmp/disk
   RCDIR=/etc/rc.d
   USBMEDIADIR=/media/usb
   APPSDIR=/enterprise
   SRCRULES=/tmp/srcrules
   TARGETRULES=/tmp/targetrules
   BoldGreen="\033[1;32m"
   BoldBlue="\033[1;34m"
   BoldCyan="\033[1;36m"
   BoldPurple="\033[1;35m"
   BoldWhite="\033[1;37m"
   BoldRed="\033[1;31m"
   UnderLine="\033[4m"
   Magenta="\033[1;47m"
   Yellow="\033[1;33m"
   Norm="\033[0m"
   USER=`id -u`
   DBSCRDIR=/opt/unisphere/srx3000/mmgr/job/bin/backup_restore
   DBCRYPT=/unisphere/srx3000/callp/bin/db_crypt
   LOGFILE=/log/prepare8k.log
   DETAILEDLOGFILE=/log/detailed.log
   EXPORTDIR=/software/export
   EXPORTBKDIR=/software/toolkit
   EXPORTFILE=/software/export.tar
   SOLIDHOME=/home/solid
   LOGSOLIDHOME=/log
   SOLIDDBHOME=/home/solid/RtpDb
   IMPORTPASSWD=true
   IMPORTHOSTS=false
   CUSTOMSECURITY=true
   CLUSTERIPXCHANGE=false
   NOAPPS=false
   NOAPPSINDB=false
   LOCAL4USB=false
   CHECK4USB=false
   INTERACTIVE8k=true
   LOCKSIDE=""
   SOLINI=/var/RtpDb/solid.ini
   RECOVER8k=false
   CHECK4CLSTATUS=false
   LIVE8kUPGRADE=false
   HW=false
   LIC_BACKUP_DIR=/opt/unisphere/srx3000/cla_inst/backup/
   OSV_EMERGENCY_MODE=`cfgread osv_emergency_mode`
   PSAP912_CONFDIR=/unisphere/srx3000/srx/psap912_scripts
   PSAP912_EXPORTDIR=${EXPORTDIR}/${PSAP912_CONFDIR}
   PSAP912_EXPORTCMD="psap912.sh -export"
   PSAP912_IMPORTCMD="psap912.sh -import"

   export MediaHome=${MediaHome:=/media/cdrom}
   export InstallRunningSys="true"
   SUCCESS=0
   FAIL=2
   EXTRAMOUNTDETECTECTED=3
   EZIPON=4
   RAMDISKNOTFREE=5
   IMAGEISONOTFOUND=6
   ROOTPARTNOT4IMAGE=7
   MISSINGCFGDIR=8
   MISSINGISO=9
   DELTARECOMPOSEFAILED=10
   DUALLOCKDETECTED=11
   UIDMISMATCH=12
   IMGDISKNOTSUPPORTED=13
   STRANGMOUNTPOINTS=14
   CURRENTLOADUNLOCKED=15
   DBRESTOREFAILED=16
   DBEXPORTFAILED=17
   NOSPACEONDEVICE=18
   MAGICCHECKFAILED=19
   NONIMAGEDSYS=20
   NOTIMPORTABLE=21
   DBCHECKFAILED=22
   DBCONVERTFAILED=23
   DBSWITCHFAILED=24
   SCHEMAUPDATEFAILED=25
   MEMBERSHIPUNKNOWN=26
   CIPDISCONFAILED=27
   CIPCONFAILED=28
   ARPDISABLEFAILED=29
   ARPENABLEFAILED=30
   CHAINCANNOTBEFLUSHED=31
   REMOTEOPTFAILED=32
   NODENAMEMISMATCH=33
   MISSINGMIGRATIONFILES=34
   DBMIGRATIONFAILED=35
   NOUSBSTICK=36
   NOEXPORTONDEVICE=37
   CLUSTERDOWN=38
   INVALIDPROFILE=39
   CREATERTPFAILED=40
   HEARTBEATFAILURE=41
   DBBACKUPFAILED=42
   CHECKEXPAPP=43
   UNINSTALLAPPSFAIL=44
   SYMSTFAILED=45
   licenses_found=0
   uc_licenses_found=0
   UC_DB_EXPORT=false

   rpm -q UNSPbase  1>/dev/null 2>&1
   if [ $? -eq 0 ];
   then
      hipath8k=true
      APPSDIR=/enterprise
      mkdir -p /log
      touch $LOGFILE
      chmod 777 $LOGFILE
      touch $DETAILEDLOGFILE
      chmod 777 $DETAILEDLOGFILE
      {
         echo "////////////////////////////////// - /////////////////////////////////////"
         echo "Upgrade `date`: ${_SELF_} $ARGLIST." 
         echo "////////////////////////////////// - /////////////////////////////////////"
      } >> $LOGFILE
      rpm -qi UNSPmigration 1>>$LOGFILE 2>&1
      textncolor $BoldCyan "Toolkit Version : `rpm -aq | grep UNSPmigration | tail -1`"
      hwid="`cfgread hardware_platform_id`"
      solution="`cfgread solution`"
      buildid="`cfgread srx_build_id`"
      solutionprofile="${hwid}${solution}"
      mapprofile $solutionprofile
      if [ "$profile" = "unknown" ];
      then
         textncolor $BoldRed "Unknown profile in node.cfg."
         exit $INVALIDPROFILE
      fi
   else
      mkdir -p /log
      hipath8k=false
      APPSDIR=/opt/siemens
   fi

   if osv_version.sh --major compare sys ge V4; 
   then
      echo "$ARGLIST" | egrep -q "\-fallback|\-dist"
      if [ $? -ne 0 ];
      then
         ulimit -n 4096
      fi
   fi

   steroid4solid=false
   rm -f /tmp/responsefile.gen.txt

   pam_tally --quiet --reset  1>/dev/null 2>&1

   SOLBINDIR=/opt/solid/bin
   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

   #<CheckPasswdValidity>
      for actidx in root solid srx
      do
         chage -l $actidx 1>/dev/null 2>&1
         if [ $? -eq 0 ];  
         then
            echo "   - Checking $actidx password for expiry."
            inactive="`chage -l $actidx | grep \"^Inactive\" | awk -F':' '{ print $2 }' | sed -e 's/[ \t]*//g'`"
            expire="`chage -l $actidx   | grep \"Password Expires\"  | \
                                          awk   -F':' '{ print $2 }' | \
                                          sed -e 's/^[ \t]*//g' -e 's/,/ /g'`"
            if [ "$inactive" != "" -a "$inactive" != "99999" -a "$expire" != "Never" ];
            then
               lastchange=`grep "^$actidx:" /etc/shadow | cut -d: -f3`
               secsepoch=$(date +%s)
               secsperday=`expr 60 \* 60 \* 24`
               daysinepoch=`expr $secsepoch / $secsperday`
               passwordage=`expr $daysinepoch - $lastchange`
               maxdays=`grep "^$actidx:" /etc/shadow | cut -d: -f5`
               if [ $maxdays -le $passwordage ];
               then
                  textncolor $BoldRed "[${_SELF_}]: Password has expired for $actidx on `uname -n`. Fix it."
                  textncolor $BoldRed "Expiry date: $expire."
                  textncolor $BoldRed "Hint: On both nodes run as user root 'chage -m 0 -M 99999 ${actidx}'."
                  exit $FAIL
               fi
            fi
         fi
      done
   #</CheckPasswdValidity>

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

# ---------------------------------------------------------------
# function: prepsys
# args    : None
# description:
#   checks for processes that are not running in the 8k.
# ---------------------------------------------------------------
checkprocs( ) 
{
   if [ "$mynode" = "$primhost" ];
   then

   #<CheckNotRunningProcs>
      if [ "$mynode" = "$primhost" ];
      then
         othernode=$sechost
      else
         othernode=$primhost
      fi
      textncolor $BoldCyan "Checking for processes that did not start."
      setmode $BoldGreen
      logstr "Note: Depending on system configuration some processes may take longer to start."
      logstr "      The list below is the status as of now."
      logstr "$mynode :-"
      failedprocs=`su - srx -c "/opt/SMAW/SMAWrtp/bin/RtpNmListProcesses -a 2>/dev/null | \
                                grep CE_01 2>/dev/null" | grep RTP_NM_NOTRUNNING       |  \
                                awk '{ print $3 }' | grep -v $mynode`
      if [ "$failedprocs" = "" ];
      then
         pgrep RtpNm 1>/dev/null 2>&1
         if [ $? -eq 0 ];
         then
            logstr "   Ok."
         else
            logstr "   RtpNodeManager is not up!."
            failedprocs="RtpNm"
         fi
      fi

      if [ "$failedprocs" != "" ];
      then
         setmode $BoldRed
     
         for idx in $failedprocs
         do
            logstr "   - $idx"
         done
      fi
      if [ "$testbed" = "cluster" ];
      then
         setmode $BoldGreen
         logstr "$othernode :-"
         failedprocs=`su - srx -c "/opt/SMAW/SMAWrtp/bin/RtpNmListProcesses -a 2>/dev/null | \
                                   grep CE_02 2>/dev/null" | grep RTP_NM_NOTRUNNING       |  \
                                   awk '{ print $3 }' | grep -v $othernode`
         if [ "$failedprocs" = "" ];
         then
            rssh ${othernode} -o ConnectTimeout=8 "pgrep RtpNm" 1>/dev/null 2>&1
            if [ $? -eq 0 ];
            then
               logstr "   Ok."
            else
               logstr "   RtpNodeManager is not up!."
               failedprocs="RtpNm"
            fi
         fi
         if [ "$failedprocs" != "" ];
         then
            setmode $BoldRed
            for idx in $failedprocs
            do
               logstr "   - $idx"
            done
         fi
      fi
      setmode $Norm
      
   #</CheckNotRunningProcs>

   fi
}

# ---------------------------------------------------------------
# function: prepsys
# args    : None
# description:
#   checks is the system is ready to be upgraded. Brings it to
#   state#2.
# ---------------------------------------------------------------

prepsys( ) { 

   #<CheckPreconditions>
      checksys
   #</CheckPreconditions>


   logstr "Bringing system to State#2.`date`"
   sleep 20
   /unisphere/srx3000/srx/startup/srxctrl 2 nc 1>/dev/null 2>&1
   if [ $? -ne 0 ];
   then
      logstr "Sorry, Cannot proceed unless system is at State#2."
      exit $FAIL
   fi
   if [ -f /etc/init.d/symphoniad -f -a "X$(isOSEE)X" = "XfalseX" ];
   then
      logstr "[*] Stopping symphonia applications."
      checkappstatus stop local
   fi
   trap 'trapnexit' EXIT
}

# ---------------------------------------------------------------
# function: getactiveinfo
# args    : None
# description:
# ---------------------------------------------------------------

getactiveinfo( )
{
   stty intr undef 1>/dev/null 2>&1
   trap 'cleanexit' EXIT

   #<DisplayCritical>
   warning=false
   setmode $UnderLine
   textncolor "Disk Usage : `uname -n`"
   setmode $Norm
   setmode $BoldGreen
   for devidx in `df -k -P  | grep "^/dev/sda"| awk '{ print $1 }'`
   do
      total=`df -k -P $devidx | grep "^/dev/sda" | awk '{ print $2 }'`
      used=`df -k -P $devidx | grep "^/dev/sda" | awk '{ print $3 }'`
      percent=`echo "$total $used 100" | awk '{ printf( "%d", $2 * $3 / $1 ) }'`
      if [ $percent -gt 90 ];
      then
         warning=true
         setmode $BoldRed
         df -h -P | grep "^${devidx}"
         setmode $BoldGreen
      else
         df -h -P | grep "^${devidx}"
      fi
   done | grep "^/dev/"
   setmode $Norm
   if [ "$warning" = "true" ];
   then
      echo "[${_SELF_}]: Warning near disk limit. Check your disk usage." 
      sleep 8
   fi

   totalswap=`cat /proc/swaps 2>/dev/null| grep "/dev/sda1" | awk '{ print $3 }'` 
   usedswap=`cat /proc/swaps 2>/dev/null | grep "/dev/sda1" | awk '{ print $4 }'`
  
   if [ "$totalswap" = "" -o "$totalswap" -le 0 ];
   then
      logstr "Swap Usage: unknown"
   else
      percentswap=$[usedswap*100/totalswap]
      cat /proc/meminfo 2>/dev/null | grep "^MemTotal" 
      logstr "Swap Usage: ${percentswap}%."
      if [ "$percentswap" -ge 10 -a "$percentswap" -le 20 ];
      then
          logstr "   - Warning(minor) : Small amount of swap usage detected."
          sleep 8
      fi
      if [ "$percentswap" -gt 20 -a "$percentswap" -le 40 ];
      then
          logstr "   - Warning(major) : Unusual amount of swap usage detected."
          sleep 8
      fi
      if [ "$percentswap" -gt 40 ];
      then
          logstr "   - Warning(critical) : Dangerous amount of swap usage detected."
          sleep 8
      fi
   fi
   #</DisplayCritical>


   #<CheckImagedSystem>
      cat /etc/fstab | grep "^/dev/sda" | grep -q "/img/rootimg"
      status=$?
      if [ $status -eq 0 ];
      then
          imagedsys=true
      else
          imagedsys=false
      fi
      if [ $status -ne 0 ];
      then
         singleimaged=true
      else
         singleimaged=false
      fi
   #</CheckImagedSystem>

   #<GetActiveInfo>
      mynode="`uname -n`"
      echo                 "//////////////////////////////////"
      textncolor $BoldCyan "Current Active image<$mynode>:"
      echo                 "//////////////////////////////////"
      sync8k -q none
      if [ $? -ne 0 ];
      then
         exit $FAIL
      fi
      activeinfo="`sync8k -q none`"
      activenotrail=${activeinfo%,*}
      activeimg=${activenotrail#*:}
      passiveimg=${activeinfo#*Fallback:}
   #</GetActiveInfo>

   #<GetUpgradeMode>
      upgrademode="`cat /img/logimg/${passiveimg}/upgrade.lock 2>/dev/null`"
      if [ "$upgrademode" = "" ];
      then
         ${IPTABLESPATH}iptables -nL firewall 1>/dev/null 2>&1
         if [ $? -eq 0 ];
         then
            upgrademode="OutageFree"
         else
            upgrademode="Outage"
         fi 
      fi
      
      logdebug "Upgrade mode: [${upgrademode}]"
   #</GetUpgradeMode>

   #<GetNodeCfgInfo>
      MASTERCFG8k=/etc/hiq8000/node.cfg
      CFG8k=/etc/hiq8000/node.cfg.prepare8k

      getnafo   nafo0  primadmin secadmin
      getnafo   nafo1  primsig   secsig
      getnafo   nafo2  primbill  secbill

      #<AdjustShiftingNames>
         buildid="`pkgparam UNSPbase PSTAMP 2>/dev/null | awk '{print $1}'`" 
         logstr "   - Processing for current build $buildid."
         latestps="`rpm -aq | grep UNSPps[0-9] | sort -nr | head -1 | sed -e s/-.*//g`"
         latesteps="`rpm -aq | grep UNSPps[0-9]*E | sort -nr | head -1 | sed -e s/-.*//g`"
         if [ "$latestps" \< "$latesteps" ];
         then
            latestps=$latesteps
         fi
      
         cp -f -p $MASTERCFG8k $CFG8k
      #<AdjustShiftingNames>

      getcfgvar $CFG8k test_bed testbed
      getcfgvar $CFG8k cf_type  cftype
      getcfgvar $CFG8k node_1_name primhost
      getcfgvar $CFG8k node_2_name sechost
      getcfgvar $CFG8k node_1_ip   primip
      getcfgvar $CFG8k node_2_ip   secip
      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
         getcfgvar $CFG8k cip_netmask primcipnm
         getcfgvar $CFG8k cip2_netmask seccipnm
      else
         export primcip="`echo $nafoxch   | awk '{ print $4 }'`"
         export seccip="`echo $nafoxch    | awk '{ print $5 }'`"
         export primcipnm="`echo $nafoxch | awk '{ print $6 }'`"
         export seccipnm="`echo $nafoxch  | awk '{ print $9 }'`"
      fi
      getcfgvar $CFG8k installation_mode instmode
      getcfgvar $CFG8k node_separation nodesep

      #<CheckCluster>
         if [ "$testbed" = "cluster" ];
         then
             logstr "   - Admin ip's: $primadmin/$secadmin"
             textncolor $BoldCyan "Cluster state"
             echo "-------------"

             recoveron=`echo "$ARGLIST" | grep "\-recover "`
             if osv_version.sh --major compare sys lt V5; 
             then
                cftool -n
                if [ $? -ne 0 ];
                then
                   if [ "${recoveron}" = "" -a "$upgrademode" != "OutageFree" ];
                   then
                      textncolor $BoldCyan "[${_SELF_}]: Sorry, the cluster is not fully up."
                      exit $CLUSTERDOWN
                   fi
                fi
             else
               primclstatus="`clstatus $primhost`"
               secclstatus="`clstatus $sechost`"
               osinfo="`uname -o`"
               {
                  echo "Node    Number State       Os      Cpu"
                  echo "$primhost 1      $primclstatus          $osinfo   EM64T"
                  echo "$sechost  2      $secclstatus          $osinfo   EM64T"
               } | awk '{ printf "%-16s%-8s%-8s%-12s%-8s\n", $1,$2,$3,$4,$5 }'
               if [ "$primclstatus" != "active" -o "$secclstatus" != "active" ];
               then
                   if [ "${recoveron}" = "" -a "$upgrademode" != "OutageFree" ];
                   then
                      textncolor $BoldCyan "[${_SELF_}]: Sorry, the cluster is not fully up."
                      exit $CLUSTERDOWN
                   fi
               fi
             fi
         else
             logstr "   - Admin ip: $primadmin"
         fi
      #</CheckCluster>

      #<SelectNmForL3>
      if [ "$cftype" != "3" ];
      then
         primcipnm=$primcipnm
         seccipnm=$primcipnm
      else
         primcipnm=$primcipnm
         seccipnm=$seccipnm
      fi
      #</SelectNmForL3>

      if [ "$testbed" = "cluster" ];
      then
         magicsum="`echo $testbed-$primhost-$sechost-$primip-$secip-$primcip-$seccip | md5sum | awk '{ print $1 }'`"
      else
         magicsum="`echo $testbed-$primhost-$primip | md5sum | awk '{ print $1 }'`"
      fi

      local osv_release="/etc/osv-release";
      if [ -f "$osv_release" ]; 
      then 
         source "$osv_release"
         loadversion="V${OSV_VERSION_MAJOR}R${OSV_VERSION_MINOR}.${OSV_VERSION_PATCH}.${OSV_VERSION_HOTFIX}"
      else
         logwarning "[${BASH_SOURCE[1]}:${BASH_LINENO[0]}] File osv-release was not found!"
         loadpkg="`rpm -aq --dbpath  /var/lib/rpm | grep UNSPbase  2>/dev/null`" 
         loadversion="`rpm -qi --dbpath /var/lib/rpm $loadpkg | grep Version | awk '{ print $3 }' 2>/dev/null`"
      fi
      patchversion="`rpm -aq --dbpath /var/lib/rpm | grep UNSPps[0-9][0-9][0-9][0-9]* \
                                                   | sort | tail -1 | sed -e 's/-.*//' 2>/dev/null`"
      dateofexport="`date`"
   #</GetNodeCfgInfo>
 
   #<FileList>
      restorelist="\
       /img/optimg/${passiveimg}:/img/optimg/${activeimg}:/opt:/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm             \
       /img/optimg/${passiveimg}:/img/optimg/${activeimg}:/opt:/SMAW/SMAWrtp/cust_conf/HiqAlarmFilters.tcn             \
       /img/unisphereimg/${passiveimg}:/img/unisphereimg/${activeimg}:/unisphere:/srx3000/callp/etc/digitmap.database  \
       /img/rootimg:/:/:/etc/resolv.conf                    \
       /img/rootimg:/:/:/etc/host.conf                      \
       /img/rootimg:/:/:/etc/motd                           \
       /img/rootimg:/:/:/etc/ntp.conf                       \
       /img/rootimg:/:/:/etc/ntp.keys                       \
       /img/rootimg:/:/:/etc/ntp.conf.cluster               \
       /img/rootimg:/:/:/etc/security/access.conf           \
       /img/rootimg:/:/:/etc/init.d/etherset                \
       /img/rootimg:/:/:/root/wd_timeout                    \
       /img/rootimg:/:/:/etc/rsyslog.d/0_osv_forward.conf   \
       /img/rootimg:/:/:/usr/share/snmp/snmpd.conf          \
       /img/varimg/${passiveimg}:/img/varimg/${activeimg}:/var:/lib/net-snmp/snmpd.conf                                 \
       /img/optimg/${passiveimg}:/img/optimg/${activeimg}:/opt:/cloudlink/cld/var/lib/cld/cld.json                      \
       /img/rootimg:/:/:/etc/sysconfig/proxy-osv                                                                        \
                 "

      # List of files to export. The RTP parameter files that need to preserve RTP parameter values in <BlackHole>
      # should be exported here in order to workin mergertpparms.
      # List of tickets concerning this logic:
      # OSV-2455: Preserve CDR delivery method to FTP or SFTP, RTP parm file: /opt/SMAW/SMAWrtp/cust_conf/SrxUsc.parm
      
      savelist="                                              \
       /etc/hosts                                             \
       /etc/passwd                                            \
       /etc/shadow                                            \
       /etc/group                                             \
       /etc/security/access.conf                              \
       /etc/hiq8000/node.cfg                                  \
       /etc/hiq8000/routes.cfg                                \
       /etc/hiq8000/fqdn.cfg                                  \
       /etc/hiq8000/version                                   \
       /etc/sysconfig                                         \
       /etc/spp_packetrate.conf                               \
       /etc/racoon/RACOON.conf                                \
       /etc/rules                                             \
       /etc/sec                                               \
       /etc/snort.conf                                        \
       /etc/snortsam.conf                                     \
       /etc/ssh/ssh_host*                                     \
       /etc/snmp/agt/snmpd.cnf                                \
       /etc/snmp/agt/naa.cnf                                  \
       /etc/snmp/snmpd.conf                                   \
       /etc/iproute2/rt_tables                                \
       /root/.ssh                                             \
       /seckeys                                               \
       /unisphere/srx3000/srx/.ssh                            \
       /unisphere/srx3000/callp/etc/prtt/PrttReader.cfg       \
       /home/solid/.ssh                                       \
       /opt/solid/RtpDb/dba.secrets                           \
       /opt/unisphere/srx3000/cla/license                     \
       /opt/SMAW/SMAWrtp/cust_conf/SrxUsc.tcn                 \
       /enterprise/servicetools/install/conf/responsefile.txt \
       /enterprise/common/conf/response.properties            \
       /etc/opt/SMAW/SMAWsf/rcsd.cfg                          \
       /etc/opt/SMAW/SMAWsf/SA_die.cfg                        \
       /etc/opt/SMAW/SMAWsf/SA_snmp.cfg                       \
       /etc/opt/SMAW/SMAWsf/SA_ipmi.cfg                       \
       /etc/opt/SMAW/SMAWhaext/sa_down.cfg                    \
       /etc/opt/SMAW/SMAWhaext/sa_ipmi.cfg                    \
       /etc/opt/SMAW/SMAWhaext/sa_ipmi.${primhost}.PWD        \
       /etc/opt/SMAW/SMAWhaext/sa_ipmi.${sechost}.PWD         \
       /opt/siemens/openbranch/var/mngmt                      \
       /opt/SMAW/SMAWrtp/cust_conf/SrxMain.parm               \
       /opt/SMAW/SMAWrtp/cust_conf/SrxSip.parm                \
       /opt/SMAW/SMAWrtp/cust_conf/SrxMobileClient.parm       \
       /opt/SMAW/SMAWrtp/cust_conf/SrxUsc.parm                \
       /enterprise/clm/ApacheTomcat/ClmSettings.xml           \
       /opt/licenses/clm/ApacheTomcat/ClmSettings.xml         \
       /repository/config                                     \
       /repository/upgrade8k-details                          \
       /repository/upgrade8k-timing                           \
       /usr/local/ssl                                         \
       /var/RtpDb/solid.ini                                   \
       /usr/share/snmp/snmpd.conf                             \
       /var/lib/net-snmp/snmpd.conf                           \
       /opt/cloudlink/cld/var/lib/cld/cld.json                \
       /etc/sysconfig/proxy-osv                               \
               "

      parameter_files=(/etc/ssh/sshd_config                   \
       /etc/pam.d/sshd                                        \
       /etc/pam.d/common-auth                                 \
       /etc/pam_pkcs11/pam_pkcs11.conf                        \
       /etc/pam.d/common-password                             \
      )
   #</FileList>


}

getactiveplatinfo( ) {
   CFG8k=/etc/hiq8000/node.cfg
   getcfgvar $CFG8k test_bed testbed
   getcfgvar $CFG8k node_1_name primhost
   getcfgvar $CFG8k node_2_name sechost
   getcfgvar $CFG8k node_1_ip   primip
   getcfgvar $CFG8k node_2_ip   secip

   #<CheckImagedSystem>
      cat /etc/fstab | grep "^/dev/sda" | grep -q "/img/rootimg"
      status=$?
      if [ $status -eq 0 ];
      then
          imagedsys=true
      else
          imagedsys=false
      fi
      if [ $status -ne 0 ];
      then
         singleimaged=true
      else
         singleimaged=false
      fi
   #</CheckImagedSystem>
}

# ---------------------------------------------------------------
# function: getrouteinfo
# args    : None
# description:
#   saves system routing info for current image. The idea is if
#   the route should be comparable when looked at device level.
# ---------------------------------------------------------------

getrouteinfo( )
{
      type=$1
      ROUTEINFO=${EXPORTDIR}/${type}routeinfo
      mkdir -p ${ROUTEINFO}
      route -n > ${ROUTEINFO}/route.out
      for devidx in eth0 eth1 eth2 eth3 eth4 eth5 eth6 eth7 bond0 bond1 bond2 bond3 cip0 cip1 cip2 cip3
      do
         ifconfig $devidx 1>/dev/null 2>&1
         if [ $? -eq 0 ];   
         then
            ip address show dev $devidx | sed -e "s/^[0-9]*:[ \t]*//g" > ${ROUTEINFO}/${devidx}.addr
            ip route show dev $devidx   > ${ROUTEINFO}/${devidx}.route
         fi
      done
      sync
}

# ---------------------------------------------------------------
# function: preserve_custom_rtp_param
# args    : $1 name of rtp parameter
#           $2 rtp parm file with the default value
# description:
#   Sometimes it is useful to preserve the default RTP params
#   of the source system to ensure that target system will remain compatible.
#   The default value will be preserved only if there is no customer specific entry.
# ---------------------------------------------------------------

preserve_custom_rtp_param( )
{

   local rtp_modified_params="/opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm"

   local rtp_param="$1"
   local rtp_config="$2"

   [ -n "${rtp_param}" ] || \
   { logstr "Unspecified RTP parameter"; return 1; }

   [ -f "${rtp_config}" ] || \
   { logstr "Not found RTP configuration file: ${rtp_config}"; return 1; }

   # The customer uses the default param
   if ! grep -q "^${rtp_param}" "${rtp_modified_params}";
   then

      logstr "Preserving RTP parameter ${rtp_param} ..."

      local rtp_record=$(su - srx -c "RtpCfgShow -r ${rtp_param}") || \
      { logstr "Failed to get RTP parameter ${rtp_param}"; return 1; }

      local rtp_value=$(echo "${rtp_record}" | grep "^Value" | awk -F':' '{print $2}' | sed -e 's/^[ \t]*//')

      local rtp_entry=$(grep -w "^${rtp_param}" "${rtp_config}" | awk -F'=' '{print $1}')

      [[ -n "${rtp_value}" && -n "${rtp_entry}" ]] || \
      { logstr "Failed to preserve RTP parameter ${rtp_param}"; return 1; }

      # Create the new record
      echo "${rtp_entry} = ${rtp_value}" >>${rtp_modified_params}
   fi
}

# ---------------------------------------------------------------
# function: savesysdata
# args    : None
# description:
#   saves system data of current active image. 
# ---------------------------------------------------------------

savesysdata( ) {
   
   if [ "$LIVE8kUPGRADEEXP" = "true" ];
   then
      remoteopt=${*:-"-liveexp -save"}
   else
      remoteopt=${*:-"-save"}
      # export initiated by upgrade8k, but it is no live
      if [ "${NON_OUTAGE_FREE_UPGRADE_EXPORT}" = "true" ]
      then
         remoteopt="-noliveexp ${remoteopt}"
      fi
   fi

   checkremote $remoteopt

   touch /log/upgrade.lock
   if [ "$LIVE8kUPGRADEEXP" = "true" ];
   then
      echo "OutageFree" > /log/upgrade.lock
      setkey -D | egrep -q "esp|ah"
      if [ $? -eq 0 ];
      then
          echo "setkey -D" > /log/setkey.info
      else
         rm -f /log/setkey.info
      fi
   else
      rm -rf /seckeys
      echo "Outage" > /log/upgrade.lock
   fi

   #<SaveSysInfo>
      mkdir -p ${EXPORTDIR}
      if [ -f /sys/class/net/eth0/address ];
      then
         cat /sys/class/net/eth0/address > ${EXPORTDIR}/eth0Mac
         ethtool -P eth0 | awk '{print $3}' 2>/dev/null > ${EXPORTDIR}/eth0Mac_permanent
      fi
      if [ -f /log/setkey.info ];
      then
         cp -f /log/setkey.info ${EXPORTDIR}/.
      fi
      if [ "${NON_OUTAGE_FREE_UPGRADE_EXPORT}" = "true" ]
      then
         touch ${EXPORTDIR}/outage_upgrade_export
         logstr "Outage free upgrade initiated by upgrade8k"
      fi
   #</SaveSysInfo>

   #<SaveLinkInfo>
      rm -rf   ${EXPORTDIR}/link
      mkdir -p ${EXPORTDIR}/link
      logstr "   - Note: Your switch in front of OSV($mynode) must support these speeds."
      for idx in eth0 eth1 eth2 eth3 eth4 eth5 eth6 eth7
      do
         ifconfig $idx 1>/dev/null 2>&1
         if [ $? -eq 0 ];
         then
            ethtool $idx > ${EXPORTDIR}/link/${idx} 2>/dev/null
            speed="`ethtool $idx 2>/dev/null | egrep "Speed:" | head -1`"
            linkdetected="`ethtool $idx 2>/dev/null | egrep "Link detected:" | head -1`"
            logstr "   - $idx:$speed"
            if [ "$linkdetected" = "Link detected: no" ];
            then
               logstr "   - $idx:No link"
            fi
         fi
      done
   #</SaveLinkInfo>

   #<SaveRoutes>
      getrouteinfo src
   #</SaveRoutes>

   #<SaveFiles>
      chown srx.$srxgroup ${EXPORTDIR}
      echo $magicsum > ${EXPORTDIR}/magic
      echo $loadversion  > ${EXPORTDIR}/loadversion
      echo $patchversion > ${EXPORTDIR}/patchversion
      echo $dateofexport > ${EXPORTDIR}/dateofexport
      textncolor $BoldCyan "[${_SELF_}]: Generating zModifiedParms on <$mynode>."
      rm -f /opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm.sav*
      su - srx -c "/opt/SMAW/SMAWrtp/update/S102_update_parameters RTP_RUPG_INSTALL_DONE" >>$LOGFILE 2>&1
      status=$?
      rm -f /opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm.sav*
      #<DontTrustS102>
      if [ $status -ne 0 -o ! -f /opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm ];
      then
         logstr "[${_SELF_}]: Sorry, cannot generate zModifiedParms."
         logstr "[${_SELF_}]: This is not a toolkit bug, just your system is not in consistent state."
         logstr "     Hint:Run RapidStat, see if it detects any inconsistency."
         exit $DBBACKUPFAILED
      fi
      #</DontTrustS102>

      #<CompatiblityParameters>
         # OSV-18634: Preserve default TLS version
         preserve_custom_rtp_param "SSL/TLSVersion" "/opt/SMAW/SMAWrtp/cust_conf/SrxSSL.parm"
      #</CompatiblityParameters>

      textncolor $BoldCyan "[${_SELF_}]: Generating Event filters on <$mynode>."
      su - srx -c "/opt/SMAW/SMAWrtp/update/S104_PreserveRtpEvtFilters RTP_RUPG_INSTALL_DONE" >>$LOGFILE 2>&1
      if [ $? -ne 0 ];
      then
         logstr "[${_SELF_}]: Sorry, cannot generate event filters."
         exit $DBBACKUPFAILED
      fi

      #<SupportOldCustomers>
         lhs="Srx/Xla/maxE164PrefixTblSize"
         rhs=`su - srx -c "RtpCfgShow -r $lhs" 2>/dev/null | grep ^Value | awk -F ':' '{print $NF}'`
         if [ $? -eq 0 -a "$rhs" != "" ];
         then
            echo "$lhs customer string = $rhs" >> /opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm
         fi

         lhs="Srx/Sip/AuthEnabled"
         rhs=`su - srx -c "RtpCfgShow -r $lhs" 2>/dev/null | grep ^Value | awk -F ':' '{print $NF}'`
         if [ $? -eq 0 -a "$rhs" != "" ];
         then
            echo "$lhs customer boolean = $rhs" >> /opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm
         fi
      #<SupportOldCustomers>

      #<SupportCustomAccts>
         cat /etc/passwd | awk -F':' '{ print $1 }' > /tmp/cust.users
         for custidx in `cat /tmp/cust.users`
         do
            custidxhome=`cat /etc/passwd | grep "^${custidx}:" |  awk -F':' '{ print $6 }'`
            custidxmode=`stat -c %a $custidxhome 2>/dev/null`
            custidxmode=${custidxmode:-700}
            ls -ld $custidxhome 2>/dev/null | \
                   awk -v user=$custidx -v home=$custidxhome -v mode=$custidxmode '{ print user":"home":"mode":"$3":"$4 }'
         done > ${EXPORTDIR}/accounts
      #</SupportCustomAccts>

      #<SupportCerts>
         exportcerts
      #</SupportCerts>
      
      #<Copy audit rules>
      if osv_version.sh --major compare sys ge V9; 
      then
         cp -p --parents /etc/audit/audit.rules ${EXPORTDIR}/
      fi
      #</Copy audit rules>
            
      textncolor $BoldCyan "[${_SELF_}]: Creating transaction log of rtp parameters."
      su - srx -c "RtpCfgShow -o ${EXPORTDIR}/rtpparms" 1>/dev/null 2>>$LOGFILE
      #RtpCfgShow does not return error code if it is unable to write to file so we must make sure#
      if [ $? -ne 0 ] || [ ! -f "${EXPORTDIR}/rtpparms" ] || [ ! -s "${EXPORTDIR}/rtpparms" ];
      then
         logstr "[${_SELF_}]: Fatal error in creating rtpparms file."
         sync
         exit $FAIL
      fi
   #</SaveFiles>

   #<SaveDb>
      if [ "$mynode" != "$primhost" -a "$mynode" != "$sechost" ];
      then
         logstr "[${_SELF_}]: Sorry, Check your node.cfg. It has a node name mismatch."
         exit $NODENAMEMISMATCH
      fi
      if [ "$RECOVER8k" = "true" ];
      then
         touch ${EXPORTDIR}/recover
      fi
      if [ "$LIVE8kUPGRADEEXP" = "false" ];
      then
         touch ${EXPORTDIR}/liveupgrade
      fi
      if [ "$mynode" = "$primhost" -o "$RECOVER8k" = "true" ];
      then
         echo "primary8k"  > ${EXPORTDIR}/nodemembership
         textncolor $BoldCyan "[${_SELF_}]: Db backup started."
         pushd $DBSCRDIR 1>/dev/null
         $DBSCRDIR/backup.sh all >> $LOGFILE 2>&1
         if [ $? -ne 0 ];
         then
            #in the case that the db fails sleep 10 minutes and try one more time - fix for OSV-7015
            logstr "[${_SELF_}]: DB backup failed. Trying again in 10 minutes..."
            sleep 600
            logstr "[${_SELF_}]: Retrying to take DB backup..."
            $DBSCRDIR/backup.sh all >> $LOGFILE 2>&1
            
            if [ $? -ne 0 ];
            then
                logstr "[${_SELF_}]: Db backup failed for the second time. Exiting..."
                exit $DBBACKUPFAILED
            fi
         fi
         popd 1>/dev/null
         textncolor $BoldCyan "[${_SELF_}]: Db backup done."
      else
         echo "secondary8k"  > ${EXPORTDIR}/nodemembership
      fi
   #</SaveDb>

   #<SavePSAP912>
   # Check if we are in PSAP mode, if not return
   if [ "${OSV_EMERGENCY_MODE}" = "PSAP" ];
   then
     logstr "[${_SELF_}]: PSAP912: OSV in PSAP mode. Trying to export files."
     if [ -d ${PSAP912_CONFDIR} ];
     then
       logstr "[${_SELF_}]: PSAP912: module configuration files found. Running the export utility."
       su - srx -c "cd ${PSAP912_CONFDIR}; ${PSAP912_CONFDIR}/${PSAP912_EXPORTCMD}" 1>>$LOGFILE 2>&1
       logstr "[${_SELF_}]: PSAP912: Saving configuration files"
       rsync -azR ${PSAP912_CONFDIR} ${EXPORTDIR} 1>>$LOGFILE 2>&1
     else
       logstr "[${_SELF_}]: PSAP-912 module configuration files not found in ${PSAP912_CONFDIR}."
     fi
   else # Not PSAP
     logstr "[${_SELF_}]: OSV not in PSAP mode."
   fi
   #</SavePSAP912>
}

# ---------------------------------------------------------------
# function: restoremigration
# args    : None
# description:
#   restore migration files.
# ---------------------------------------------------------------

restoremigration( )
{
   if [ -f /var/opt/image/dbmigration.tar ];
   then
      textncolor $BoldCyan "[${_SELF_}]: Restoring migration files."
      mkdir -p /unisphere/srx3000/srx/dbscripts/dbmigration
      pushd /software 1>/dev/null 2>&1
      tar -zxvf /var/opt/image/dbmigration.tar
      if [ $? -ne 0 ];
      then
         logstr "[${_SELF_}]: Sorry, cannot restore migration files."
         exit $DBMIGRATIONFAILED
      fi
      cp -p /software/dbmigration/* /unisphere/srx3000/srx/dbscripts/dbmigration
      rm -rf /software/dbmigration
      popd 1>/dev/null 2>&1
   else
      logstr "Sorry, Cannot find migration files."
      exit $MISSINGMIGRATIONFILES
   fi
}

# ---------------------------------------------------------------
# function: checkmigration
# args    : None
# description:
#     checks if migations status is valid, else exits.
# ---------------------------------------------------------------

checkmigration( )
{
   status=$1
   if [ $status -ne 0 ];
   then
       logstr "[${_SELF_}]: Failed to upgrade schema."
       #<Steroid4Solid>
         solidperfclean
       #</Steroid4Solid>
       exit $SCHEMAUPDATEFAILED
   fi
}


# ---------------------------------------------------------------
# function: handleUpgradeVx
# args    : None
# description:
#    handles any upgrades and migrations.
# ---------------------------------------------------------------


handleUpgradeVx( )
{
   DBMIGRATIONDIR=/unisphere/srx3000/srx/dbscripts/dbmigration
   su - srx -c "cd $DBMIGRATIONDIR;${DBMIGRATIONDIR}/dbExecuter.sh auto"
   checkmigration $?
} 1>>$LOGFILE 2>&1

# ---------------------------------------------------------------
# function: handleincrloadupdate
# args    : None
# description:
#   runs incremental updates by executing all schema changes for
#   internal loads
# ---------------------------------------------------------------

handleincrloadupdate( )
{
   DBMIGRATIONDIR=/unisphere/srx3000/srx/dbscripts/dbmigration
   intload=${fbloadversion##*ALL.}
   logstr "   - Running incremental load updates from : ${intload}"
   su - srx -c "cd $DBMIGRATIONDIR;${DBMIGRATIONDIR}/dbExecuter.sh I ${intload}"
}

# ---------------------------------------------------------------
# function: handleincrupdate
# args    : None
# description:
#   runs incremental updates by executing all schema changes for
#   current release.
# ---------------------------------------------------------------

handleincrupdate( )
{
   handleUpgradeVx
} 1>>$LOGFILE 2>&1 


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

handleversions( )
{
   skipimport=false
   handletype="handleUpgradeVx"
   tomajor="`echo $loadversion | sed -e 's/\.[0-9][0-9].ALL.*//'`"
   frommajor="`echo $fbloadversion | sed -e 's/\.[0-9][0-9].ALL.*//'`"
   logstr "   - Will execute database upgrades ${fbloadversion} to ${loadversion}."
}

# ---------------------------------------------------------------
# function: dropalarms
# args    : None
# description:
#   dropping alrms from older release.
# ---------------------------------------------------------------

dropalarms( )
{
   textncolor $BoldCyan "Dropping alrams from source system."
   DROPALARMS=/tmp/dropalarms
   {
      echo "set catalog RTPDB;"
      echo "delete from RTP_ARM_ALARM_LIST;"
      echo "set catalog OPENSOA;"
      echo "delete from SYMALARM;"
      echo "commit work;"
   } > $DROPALARMS
   su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $DROPALARMS" 1>/dev/null 2>&1
}


# ---------------------------------------------------------------
# function: shutdownsolid
# args    : None
# description:
#   shuts down solid.
# ---------------------------------------------------------------

shutdownsolid( )
{
   su - solid -c "RtpSolid -A"
   echo -n "Waiting for solid to shutdown ..."
   ps -ef f | grep -i solid | grep -qv grep
   status=$?
   while [ $status -eq 0 ];
   do
      echo -n "."
      ps -ef f | grep -i solid | grep -qv grep
      status=$?
      sleep 1
   done
   logstr ""
}

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

switchsolid( )
{
        local XTESTBED=$(cfgread test_bed)
        statusFile="/var/RtpDb/solidStatus"
	if [ "$XTESTBED" = "cluster" ]
	then
	    su - srx -c "RtpSolid -l" > $statusFile
	    ACTIVECNT=$(grep "PRIMARY ACTIVE\|SECONDARY ACTIVE" ${statusFile} | wc -l)
	    if [ $ACTIVECNT -ne 2 ]
	    then
	       	# Sleep for 30 seconds to let solid synchronize
               	sleep 30
	    fi
        fi
		
		

        mynode=$1
        primhost=$(cfgread node_1_name)
        sechost=$(cfgread node_2_name)

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

        textncolor $BoldCyan "Check if Solid should be switched..."
		
	local xstart=0
	local xend=15
	local xcontinue=1

        while [ $xstart -le $xend ] && [ $xcontinue -eq 1 ]
        do
                su - solid -c "RtpSolid -l" > ${statusFile}

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

                        grep '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"

                                # 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
				su - srx -c "RtpSolid -l" > ${statusFile}
				grep 'PRIMARY\|STANDALONE' ${statusFile} | grep -q $mynode
				if [ $? -eq 0 ]
				then
				    textncolor $BoldCyan "${mynode} is PRIMARY or STANDALONE, Solid DB switched..."
				    xcontinue=0
				fi
                        fi
		else
                        textncolor $BoldCyan "${mynode} is PRIMARY or STANDALONE, Solid DB switched..."
			xcontinue=0
                   
                fi
		if [ $xcontinue -eq 1 ]
		then
		   sleep 8
	        fi
		xstart=$((xstart+1))
        done

	su - srx -c "RtpSolid -l" > ${statusFile}
	grep 'PRIMARY\|STANDALONE' ${statusFile} | grep -q $mynode
	if [ $? -ne 0 ]
	then
	   rm -f ${statusFile}
	   textncolor $BoldCyan "${_SELF_}: Sorry cannot switch db state."
	   exit $DBSWITCHFAILED
	fi

        rm -f ${statusFile}
}

# ---------------------------------------------------------------
# function: recomputepsinfo
# args    : None
# description:
#   Recomputes the RTP parms for psinfo
# ---------------------------------------------------------------

recomputepsinfo( )
{
 #<RecomputePsInfo>
     ZMODIFIED=/opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm
     HIQALARMTCN="/opt/SMAW/SMAWrtp/cust_conf/HiqAlarmFilters.tcn"
     cat $ZMODIFIED | grep -v 'Srx/Main/NewSoftwareVersion' | grep -v 'Srx/Main/OldSoftwareVersion' > ${ZMODIFIED}.new
     cp  ${ZMODIFIED}.new $ZMODIFIED
     rm -f ${ZMODIFIED}.new
	 if osv_version.sh --major compare sys ge V11;
     then
         loadlabel=$(/unisphere/srx3000/srx/version/sysversion --pretty 2>/dev/null)
         if [ "$loadlabel" = "none" ];
         then 
            logwarning "[${BASH_SOURCE[1]}:${BASH_LINENO[0]}] File osv-release was not found!"
         fi
     else
         loadlabel=$(/unisphere/srx3000/srx/version/pkgversion -ps | sed '/^$/d' | tail -1 | awk '{print $1}')
         if [ "$loadlabel" = "none" ];
         then
            loadlabel="$(pkgparam UNSPbase PSTAMP 2>/dev/null | awk -F'.' '{ printf "%s%s%d", $1,"R",$2 }')" 
         fi
     fi
     {
        echo "Srx/Main/NewSoftwareVersion customer string = $loadlabel"
        echo "Srx/Main/OldSoftwareVersion customer string = $loadlabel"
     } >> $ZMODIFIED
     logstr "   - Updating version $loadlabel"
    if osv_version.sh --major compare sys ge V4; 
    then
       chown srx.rtpgrp $ZMODIFIED $HIQALARMTCN
    fi
  #</RecomputePsInfo>
}

# ---------------------------------------------------------------
# function: importsyspfrules
# args    : None
# description:
# ---------------------------------------------------------------

importsyspfrules( )
{
  if osv_version.sh --major compare sys ge V4; 
  then
     textncolor $BoldCyan "Importing system defined packet filter rules."
     export ExportSecure8k=${SOLIDHOME}/migratesecure8k
     rm -rf    $ExportSecure8k
     mkdir -p  $ExportSecure8k
     chmod 777 $ExportSecure8k
     su - solid -c "cd ${ExportSecure8k}; $solexp 'tcp 16760' dba $(getDbaPassword) PACKET_FILTERING_RULE_T" 1>/dev/null 2>&1
     
     cp ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat $TARGETRULES
     > ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat
     customsecrules $SRCRULES $TARGETRULES ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat

     extraBuildid=`/sbin/cfgread "# VERSION" |awk {'print $1'}`	

     su - solid -c "cd ${ExportSecure8k}; $solload -L ${LOGSOLIDHOME}/solload.log -b 1000 \
                   -x nointegrity 'tcp 16760' dba $(getDbaPassword) DBA_PACKET_FILTERING_RULE_T.ctr" 1>>$LOGFILE 2>&1
#CQ00333301 :load now the ipv6 rules
#if [ "$extraBuildid" \> "08.00" ]
#then
    #recreate the init pfr rules for ipv6
#/etc/init.d/srx_security start ipv6
#   #The previous command should create /unisphere/srx3000/callp/etc/sec/initFilterRulesV6.sql
#su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) /unisphere/srx3000/callp/etc/sec/initFilterRulesV6.sql"
#fi


  fi

  rm -rf $ExportSecure8k
}

# ---------------------------------------------------------------
# function: importsurv
# args    : None
# description:
#    imprts survivability data.
# ---------------------------------------------------------------

importsurv( )
{
  #Check rsa data
  grep -q rsa_0_ip ${EXPORTDIR}/etc/hiq8000/node.cfg
  if [ $? -ne 0 ];
  then
     getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  rsa_1_ip exprsaprimip
     getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  rsa_2_ip exprsasecip
  else
     getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  rsa_0_ip exprsaprimip
     getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  rsa_1_ip exprsasecip
  fi
  getcfgvar /etc/hiq8000/node.cfg              rsa_1_ip rsaprimip
  getcfgvar /etc/hiq8000/node.cfg              rsa_2_ip rsasecip
  logstr "   - Source Remote Admin Info "
  logstr "        Node#1 Address: $exprsaprimip"
  logstr "        Node#2 Address: $exprsasecip"
  logstr "   - Target Remote Admin Info "
  logstr "        Node#1 Address: $rsaprimip"
  logstr "        Node#2 Address: $rsasecip"

  getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  survival_authority expsurvauth
  getcfgvar /etc/hiq8000/node.cfg              survival_authority survauth
  logstr "   - Survival authority in source release : $expsurvauth."
  logstr "   - Survival authority in target release : $survauth."
  if [ "$rsaprimip" = "$exprsaprimip" -a "$rsasecip" = "$exprsasecip" ];
  then
     if [ "$survauth" = "" -o "$survauth" = "0.0.0.0" ];
     then
        textncolor $BoldPurple "No survival authority configured in target release."
     fi
     #[1]. Import the SA_ipmi data.
     mkdir -p /etc/opt/SMAW/SMAWsf
     if [ -f ${EXPORTDIR}/etc/opt/SMAW/SMAWsf/SA_ipmi.cfg ];
     then
        if osv_version.sh --major compare sys ge V4; 
        then
           {
              echo "TestLocalStatus" 
              echo "useCycle"       
           }  > /etc/opt/SMAW/SMAWsf/SA_ipmi.cfg
        fi
        if osv_version.sh --major compare sys ge V5; 
        then
           echo "retryPonCnt 2" >> /etc/opt/SMAW/SMAWsf/SA_ipmi.cfg
        fi
        cat ${EXPORTDIR}/etc/opt/SMAW/SMAWsf/SA_ipmi.cfg |                       \
            egrep -v "^[ \t]*TestLocalStatus|^[ \t]*retryPonCnt|^[ \t]*useCycle" \
            >> /etc/opt/SMAW/SMAWsf/SA_ipmi.cfg
        if osv_version.sh --major compare sys ge V5; 
        then
           cp /etc/opt/SMAW/SMAWsf/SA_ipmi.cfg /etc/opt/SMAW/SMAWhaext/sa_ipmi.cfg
           rm -rf /etc/opt/SMAW/SMAWsf
        fi
        
     fi
     if [ -f ${EXPORTDIR}/etc/opt/SMAW/SMAWhaext/sa_ipmi.cfg ];
     then
        cp ${EXPORTDIR}/etc/opt/SMAW/SMAWhaext/sa_ipmi.cfg /etc/opt/SMAW/SMAWhaext/sa_ipmi.cfg
        getcfgvar /etc/hiq8000/node.cfg hw_platform hw_platform
        getcfgvar /etc/hiq8000/node.cfg node_1_name cfgprimhost
        getcfgvar /etc/hiq8000/node.cfg node_2_name cfgsechost
        if [ "$hw_platform" = "SR530" ] || [ "$hw_platform" = "SR630" ] || [ "$hw_platform" = "SR630V3" ] || [ "$hw_platform" = "Generic" ]
        then
           sa_ipmi_num_args=$(grep "^$cfgprimhost" /etc/opt/SMAW/SMAWhaext/sa_ipmi.cfg | awk '{print NF}')
           if [ "${sa_ipmi_num_args}" -eq 3 ]
           then
              logstr "Adding <IPMI2.0> parameter to sa_ipmi.cfg"
              sed -i -e "/^$cfgprimhost/s/$/ IPMI2.0/"             \
                     -e "/^$cfgsechost/s/$/ IPMI2.0/"              \
                     /etc/opt/SMAW/SMAWhaext/sa_ipmi.cfg ||        \
              logstr "Failed to add <IPMI2.0> parameter to sa_ipmi.cfg"
           fi
        else
           if [ "${sa_ipmi_num_args}" -eq 4 ]
           then
              logstr "Removing <IPMI2.0> parameter from sa_ipmi.cfg"
              sed -i -e "/^$cfgprimhost/s/ IPMI2.0//g"                 \
                     -e "/^$cfgsechost/s/ IPMI2.0//g"                  \
                     /etc/opt/SMAW/SMAWhaext/sa_ipmi.cfg ||            \
              logstr "Failed to remove <IPMI2.0> parameter from sa_ipmi.cfg"
           fi
        fi
     fi
     if osv_version.sh --major compare "$expbuildid" lt V7 && osv_version.sh --major compare sys ge V7;
     then
        saipmi=/etc/opt/SMAW/SMAWhaext/sa_ipmi.cfg
        saipmiprimpwd=/etc/opt/SMAW/SMAWhaext/sa_ipmi.${primhost}.PWD
        saipmisecpwd=/etc/opt/SMAW/SMAWhaext/sa_ipmi.${sechost}.PWD
        primnodeinf="`cat  $saipmi               | \
                      egrep \"^$primhost[ \t]\"  | \
                      head -1`"
        primnodeuid="`echo $primnodeinf          | \
                      awk '{ print $2 }'         | \
                      awk -F ':' '{ print $2 }'`"
        primnodepas="`echo $primnodeinf          | \
                      awk '{ print $2 }'         | \
                      awk -F ':' '{ print $3 }'`"
        secnodeinf="` cat  $saipmi               | \
                      egrep \"^$sechost[ \t]\"   | \
                      head -1`"
        secnodeuid="` echo $secnodeinf           | \
                      awk '{ print $2 }'         | \
                      awk -F ':' '{ print $2 }'`"
        secnodepas="` echo $secnodeinf           | \
                      awk '{ print $2 }'         | \
                      awk -F ':' '{ print $3 }'`"
        
        if [ "$primnodepas" != "" -o "$secnodepas" != "" ];
        then
           {
              cat $saipmi | egrep -v "^${primhost}|^${sechost}"
              echo $primnodepas | sed  -e 's/\\/\\\\/g' -e 's/\//\\\//g' > /tmp/normprimnodepas
              echo $secnodepas  | sed  -e 's/\\/\\\\/g' -e 's/\//\\\//g' > /tmp/normsecnodepas
              normprimnodepas="`cat /tmp/normprimnodepas`"
              normsecnodepas="`cat /tmp/normsecnodepas`"
              echo $primnodeinf | sed -e "s/:$normprimnodepas[ \t]/:DUMMY /"
              if [ "$testbed" = "cluster" ];
              then
                 echo $secnodeinf  | sed -e "s/:$normsecnodepas[ \t]/:DUMMY /"
              fi
              rm -f /tmp/normprimnodepas /tmp/normsecnodepas
           } > ${saipmi}.new
           cp ${saipmi}.new ${saipmi}
           rm -f ${saipmi}.new /tmp/ipmipass*
           logstr "   - Encrypting $primhost ipmi password."
           {
              $DBCRYPT enc /tmp/ipmipass.PWD "$primnodepas"
              cp /tmp/ipmipass.PWD $saipmiprimpwd
              rm -f /tmp/ipmipass*
           } 1>>$LOGFILE 2>&1
           if [ "$testbed" = "cluster" ];
           then
              logstr "   - Encrypting $sechost ipmi password."
              {
                 $DBCRYPT enc /tmp/ipmipass.PWD "$secnodepas"
                 cp /tmp/ipmipass.PWD $saipmisecpwd
                 rm -f /tmp/ipmipass*
              } 1>>$LOGFILE 2>&1
           fi
           egrep -q "^encryptedPassword" ${saipmi}
           if [ $? -ne 0 ];
           then
              cat ${saipmi}        | \
              egrep -v "^useCycle" | \
              sed -e "s/TestLocalStatus/TestLocalStatus\\nencryptedPassword true\\nuseCycle/" \
              > ${saipmi}.new
              cp  ${saipmi}.new ${saipmi}
              rm -f ${saipmi}.new 
           fi
        else
           logstr "   - Strange ipmi configuration."
        fi
     else
        if osv_version.sh --major compare sys ge V7; 
        then
           logstr "   - Handling Encrypted passwords for $buildid."
           saipmiprimpwd=/etc/opt/SMAW/SMAWhaext/sa_ipmi.${primhost}.PWD
           saipmisecpwd=/etc/opt/SMAW/SMAWhaext/sa_ipmi.${sechost}.PWD
           if [ -f ${EXPORTDIR}/${saipmiprimpwd} ];
           then
              logstr "   - Copying `basename $saipmiprimpwd`"
              cp ${EXPORTDIR}/${saipmiprimpwd} ${saipmiprimpwd}
           else
              logstr "   - Skipping ${EXPORTDIR}/${saipmiprimpwd}."
           fi 
           if [ -f ${EXPORTDIR}/${saipmisecpwd} ];
           then
              logstr "   - Copying `basename $saipmisecpwd`"
              cp ${EXPORTDIR}/${saipmisecpwd} ${saipmisecpwd}
           else
              logstr "   - Skipping ${EXPORTDIR}/${saipmisecpwd}."
           fi 
        fi
     fi
  else
     logstr "   - Skipping ipmi encryption."
  fi
  

  #[2]. Now import SA_die.
  if [ "$survauth" = "$expsurvauth" ];
  then
     if osv_version.sh --major compare sys ge V4; 
     then
        communitystr="`grep \"^[ \t]*community-string[ \t]\" \
                    ${EXPORTDIR}/etc/opt/SMAW/SMAWsf/SA_die.cfg 2>/dev/null| head -1 | awk '{ print $2 }'`"
        if [ "$communitystr" != "" -a -f /etc/opt/SMAW/SMAWsf/SaQuery.cfg ];
        then
           logstr "   - SA_die.cfg configuration : community string $communitystr imported."
           cat /etc/opt/SMAW/SMAWsf/SaQuery.cfg | sed -e "s/^community-string.*/community-string $communitystr/" \
               > /etc/opt/SMAW/SMAWsf/SaQuery.cfg.new
           cp /etc/opt/SMAW/SMAWsf/SaQuery.cfg.new /etc/opt/SMAW/SMAWsf/SaQuery.cfg
           rm -f /etc/opt/SMAW/SMAWsf/SaQuery.cfg.new
        fi
     else
        cp ${EXPORTDIR}/etc/opt/SMAW/SMAWsf/SA_die.cfg /etc/opt/SMAW/SMAWsf/SA_die.cfg
     fi
  else
        logstr "   - Skipping survival authority configuration."
  fi

  #[3]. Now import the SA_snmp.cfg
  #if osv_version.sh --major compare sys ge V4; 
  #then
  #   logstr "  if osv_version.sh --major compare sys ge V4  succeeded line 3245 "
  #   logstr "   - Skipping SA_snmp.cfg import."
  #else
     cp ${EXPORTDIR}/etc/opt/SMAW/SMAWsf/SA_snmp.cfg /etc/opt/SMAW/SMAWsf/SA_snmp.cfg
     cp ${EXPORTDIR}/etc/opt/SMAW/SMAWsf/SA_snmp.cfg /etc/test_SA_snmp.cfg
     logstr "  cp ${EXPORTDIR}/etc/opt/SMAW/SMAWsf/SA_snmp.cfg /etc/opt/SMAW/SMAWsf/SA_snmp.cfg SA_snmp.cfg imported"
  #fi

  reconfigureimm

} 2>/dev/null

# ---------------------------------------------------------------
# function: importsbc
# args    : None
# description:
#   imports sbc data.
# ---------------------------------------------------------------

importsbc( )
{
   SbcXmlDir=/opt/siemens/openbranch/var/mngmt
   if osv_version.sh --major compare sys ge V4 && [ "$SYSIMPORT" = "true" ] && [ -d ${EXPORTDIR}/${SbcXmlDir} ];
   then
      logstr "   - Importing Session Border Controller settings."
      rm -f ${SbcXmlDir}/*.xml
      cp ${EXPORTDIR}/${SbcXmlDir}/*.xml ${SbcXmlDir}/. 
      chmod 660 ${SbcXmlDir}/*.xml
      chown root.www ${SbcXmlDir}/*.xml
   fi
} 2>/dev/null

# ---------------------------------------------------------------
# function: importsrcroutes
# args    : None
# description:
#   imports source based routing data for V4 only. For V5 & higher
#   hope the node.cfg is correct.
# ---------------------------------------------------------------

importsrcroutes( )
{
   pushd /etc/init.d 1>/dev/null 
      grep "^route_data" ${EXPORTDIR}/etc/hiq8000/routes.cfg 2>/dev/null
      srcroutestatus=$?
      if [ -f ${EXPORTDIR}/etc/hiq8000/routes.cfg -a $srcroutestatus -eq 0 -a "$nwmatch" = "true" ];
      then
         logstr "   - Detected source based routes. Networks match."
         cp ${EXPORTDIR}/etc/hiq8000/routes.cfg /etc/hiq8000/routes.cfg 
         if osv_version.sh --major compare sys ge V4 && osv_version.sh --major compare sys lt V5;
         then
            sleep 8
            if [ "$testbed" != "simplex" ];
            then
                  textncolor $BoldCyan "Stopping shutdown agent on local node."
                  sdtool -e
                  if [ $? -ne 0 ];
                  then
                     textncolor $BoldRed "Could not stop shutdown agent."
                     exit $HEARTBEATFAILURE
                  fi
                  textncolor $BoldCyan "Stopping shutdown agent on remote node($othernode)."
                  rssh $othernode "sdtool -e"
                  if [ $? -ne 0 ];
                  then
                     textncolor $BoldRed "Could not stop shutdown agent."
                     exit $HEARTBEATFAILURE
                  fi
            fi
            /etc/init.d/route_table update
            /etc/init.d/default_route start
            if [ "$testbed" != "simplex" ];
            then
                  textncolor $BoldCyan "Starting shutdown agent on local node."
                  sdtool -b
                  if [ $? -ne 0 ];
                  then
                     textncolor $BoldRed "Could not start shutdown agent."
                     exit $HEARTBEATFAILURE
                  fi
                  textncolor $BoldCyan "Starting shutdown agent on remote node($othernode)."
                  rssh $othernode "sdtool -b"
                  if [ $? -ne 0 ];
                  then
                     textncolor $BoldRed "Could not start shutdown agent."
                     exit $HEARTBEATFAILURE
                  fi
            fi
         fi
      else
         logstr "   - Will use source based routes from target, if any."
      fi
   popd 1>/dev/null
} 1>>$LOGFILE 2>&1

# ---------------------------------------------------------------
# function: importcerts
# args    : None
# description:
#   imports tls certificates. These are user configurable.
# ---------------------------------------------------------------

buildtrusted( ) {

     cat << EOF > /repository/splitcerts
#!/usr/local/bin/perl
use File::Path qw(rmtree);
use FileHandle;
my \$certs=\$ARGV[0];
my \$hash=\$ARGV[1];
my \$certfile=\$ARGV[2];
my \$SUBCERTFILE = FileHandle->new;
my \$count=0;
my \$block=0;

mkdir \$certs;
open CERTFILE, "<\$certfile";
open HASHFILE, ">\$hash" || die;
while (<CERTFILE>) {
   if ( /-----BEGIN[ \ta-zA-Z]* CERTIFICATE-----/ ) {
      open SUBCERTFILE, ">\$certs/\$count" || die;
      print SUBCERTFILE \$_;
      \$block=1;
   } elsif ( /-----END[ \ta-zA-Z]* CERTIFICATE-----/ ) {
      print SUBCERTFILE \$_;
      close SUBCERTFILE;
      my \$sslhash=\`openssl x509 -in \$certs/\$count -hash -noout 2>/dev/null\`;
      print HASHFILE "\$sslhash";
      \$block=0;
      \$count++;
   } elsif ( \$block ) {
      print SUBCERTFILE \$_;
   }
}
close CERTFILE;
close HASHFILE;
rmtree(\$certs);
EOF
     chmod 755 /repository/splitcerts
     certslist=${EXPORTDIR}/certs
     for idx in "
        SSL/MutualAuth/Client/CertificatesPath:SSL/MutualAuth/Client/SupportedCertificates         \
        SSL/MutualAuth/Server/CertificatesPath:SSL/MutualAuth/Server/SupportedCertificates         \
        SSL/EndPoint/Server/CertificatesPath:SSL/EndPoint/Server/SupportedCertificates             \
        SSL/CSTAMutualAuth/Server/CertificatesPath:SSL/CSTAMutualAuth/Server/SupportedCertificates \
        SSL/Soap/Server/CertificatesPath:SSL/Soap/Server/SupportedCertificates                     \
    "
    do
       rtpcertpath=`echo $idx | awk -F ':' '{ print $1 }'`
       rtpcertfile=`echo $idx | awk -F ':' '{ print $2 }'`

       # Extract RTP parameter
       certpath=`cat $certslist | egrep "^$rtpcertpath" | awk -F'=' '{ print $2 }' | sed -e "s/[ \t]*//g"`
       if [ "$certpath" = "" ];
       then
          continue
       fi
       certfile=`cat $certslist | egrep "^$rtpcertfile" | awk -F'=' '{ print $2 }' | sed -e "s/[ \t]*//g"`
       if [ "$certfile" = "" ];
       then
          certfile="trustedCAstore.pem"
          touch $certpath/$certfile
          # enter certfile into RTP variable SSL/MutualAuth/Client/SupportedCertificates as e.g.
          echo "$rtpcertfile customer string   = trustedCAstore.pem"
       fi
       echo "$certpath:$certfile"
    done | sort | uniq > /tmp/certs.postprocess
    
    for idx in `cat /tmp/certs.postprocess`
    do
       certpath=`echo $idx | awk -F ':' '{ print $1 }'`
       certfile=`echo $idx | awk -F ':' '{ print $2 }'`

       # gather all the known hashes from certfile to /tmp/certs.hash.
       # carefull many certificates here - break them to many and run
       # openssl hash command.
       
       /repository/splitcerts /tmp/cert-ify /tmp/certs.hash $certfile

       for certidx in `find $certpath -type l` 
       do
          linkhash=`openssl x509 -in $certidx -hash -noout 2>/dev/null`
          if [ "$linkhash" != "" ];
          then
            grep -q linkhash /tmp/certs.hash
            if [ $? -ne 0 ];
            then
               logstr "   - Concatenating hash $linkhash."
               cat $certidx >> $certpath/$certfile
            fi
          fi
       done
   done
   rm -f /repository/splitcerts /tmp/certs.postprocess /tmp/certs.hash

   # Enabled for JITC
   if [ -f "/usr/local/lib64/ossl-modules/fips.so" ];
   then
      #For OSV-22665(OSV-21827)
      openssl-3 fipsinstall -out /usr/local/ssl/fipsmodule.cnf -module /usr/local/lib64/ossl-modules/fips.so
   fi
}

importcerts( )
{
     TlsCertsPath=/usr/local/ssl
     logstr "   - Restoring tls certificates."

     certslist=${EXPORTDIR}/certs
     if [ -f $certslist ];
     then
        nonstdcount=`cat $certslist | grep -v $TlsCertsPath | grep -v "^[ \t]*$" |  wc -l`
     else
        nonstdcount=0
     fi
     if [ $nonstdcount -eq 0 ];
     then
        echo "   - User namaged tls certificates found in standard path."
     else
        echo "   - User namaged tls certificates found in non standard path."
        pushd ${EXPORTDIR}
        for certsidx in `cat $certslist | egrep -v "^$TlsCertsPath" 2>/dev/null | sort | uniq`
        do
           cp -p --parents ./$certsidx/. /
        done
        popd
     fi
     for certsidx in `cat $certslist 2>/dev/null | sort | uniq`
     do
           if [ "$certsidx" != "" -a -d ${EXPORTDIR}/$certsidx ];
           then
              logstr "   - Importing from $certsidx"
              if [ ! -d $certsidx ];
              then
                 pushd ${EXPORTDIR} 1>/dev/null 2>&1
                 cp -p --parents ./$certsidx/. /. 2>/dev/null
                 popd 1>/dev/null 2>&1
              fi
              cp -r -p ${EXPORTDIR}/$certsidx/* $certsidx 
           fi
     done
     if osv_version.sh --major compare sys ge V4; 
     then
           chown -R srx.rtpgrp $TlsCertsPath
     fi
     if [ -d ${EXPORTDIR}/usr/local/ssl/osrootca ];
     then
        rm -rf /usr/local/ssl/osrootca 2>/dev/null
        cp -R -p ${EXPORTDIR}/usr/local/ssl/osrootca /usr/local/ssl/.
     fi

     #if [ "$buildid" \> "V8" ];
     #then
     #   buildtrusted
     #fi
} 

#' ---------------------------------------------------------------
# function: exportcerts
# args    : None
# description:
#   exports tls certificates. These are user configurable.
#   Detects the configured rtp parms and exports them.
# ---------------------------------------------------------------

exportcerts( )
{

  TlsCertsPath=/usr/local/ssl
  logstr "   - Exporting tls certificates."
  certsparms="                                       \
     Srx/ttud/KeysPath                               \
     Srx/ttud/CertificatesPath                       \
     SSL/MutualAuth/Client/KeysPath                  \
     SSL/MutualAuth/Client/CertificatesPath          \
     SSL/MutualAuth/Client/DHPath                    \
     SSL/MutualAuth/Server/KeysPath                  \
     SSL/MutualAuth/Server/CertificatesPath          \
     SSL/MutualAuth/Server/DHPath                    \
     SSL/EndPoint/Server/KeysPath                    \
     SSL/EndPoint/Server/CertificatesPath            \
     SSL/EndPoint/Server/DHPath                      \
     SSL/CSTAMutualAuth/Server/KeysPath              \
     SSL/CSTAMutualAuth/Server/CertificatesPath      \
     SSL/CSTAMutualAuth/Server/DHPath                \
     SSL/Soap/Server/KeysPath                        \
     SSL/Soap/Server/CertificatesPath                \
     Srx/CDM/CertificateStore                        \
     Srx/CDM/PublicCertificateStore                  \
     Srx/CDM/CertificateKeystore                     \
     SSL/AnsMutualAuth/TrustedCAStorePath            \
     SSL/AnsMutualAuth/OSV/KeysPath                  \
  "
  # Creating a unique file in EXPORTDIR using date and pid
  CBDATE=`date +%Y%m%d`
  CPID=$$
  certslist=${EXPORTDIR}/certs_${CBDATE}_${CPID}

  for certsidx in $certsparms
  do
     grep -q "$certsidx" /opt/SMAW/SMAWrtp/cust_conf/*.parm
     if [ $? -eq 0 ];
     then
        rhs=`su - srx -c "RtpCfgShow -r $certsidx 2>/dev/null" | grep ^Value | awk -F ':' '{print $NF}'`
        echo $rhs | sed -e 's/;/\n/g'
     fi
  done  | sort | uniq > $certslist

  for certsidx in `cat $certslist 2>/dev/null`
  do
     if [ "$certsidx" != "" -a -d $certsidx ];
     then
        find $certsidx -maxdepth 1 -mindepth 1 -type f -size -64k -name \* -exec cp -p --parents {} ${EXPORTDIR} \; 
     fi
  done
 
  mv $certslist ${EXPORTDIR}/certs
 
} 
# ---------------------------------------------------------------
# function: exportKeyTool
# args    : None
# description:
#   In v7/V8/V9 source release export the keystore /enterprise/HiPathCA/distribution/.keystore
#

function exportKeyTool( )
{
   if osv_version.sh --major compare sys ge V7 && [ -f /enterprise/HiPathCA/distribution/.keystore ];
   then
      logstr " Exporting /enterprise/HiPathCA/distribution/.keystore"
      cp -p --parents /enterprise/HiPathCA/distribution/.keystore ${EXPORTDIR}
   fi

}

# ---------------------------------------------------------------
# function: importrtt
# args    : None
# description:
#   rtt process will auto convert older configuration to new one.
# ---------------------------------------------------------------

importrtt( )
{
   RTTCFG=/unisphere/srx3000/callp/etc/prtt/PrttReader.cfg
   if osv_version.sh --major compare sys ge V6 && [ -f ${EXPORTDIR}/${RTTCFG} ];
   then
      cp -p ${EXPORTDIR}/${RTTCFG} ${RTTCFG}.upgrade
      chown srx.$srxgroup ${RTTCFG}.upgrade
      chmod 640 ${RTTCFG}.upgrade
   fi
}

fixappsschema( ) {
   solfile=$1
   
   oneLineScriptToBeMoved=$(grep "CREATE VIEW VIEWXPR" "$solfile")
   anchorScript=$(grep "CREATE VIEW UMS.HORIZONTAL" "$solfile")
   if [ "$anchorScript" != "" ]
   then
      grep -v "$oneLineScriptToBeMoved" "$solfile" | \
      sed  "s/$anchorScript/$oneLineScriptToBeMoved\\n\\n&/" > ${solfile}.new
      cp -f ${solfile}.new $solfile
      rm -f ${solfile}.new
   else
      logstr "   WARNING :  UC schema issue."
   fi
  
}

# ---------------------------------------------------------------
# function: importroles
# args    : None
# description:
#    imports rtp data of users and roles.
# ---------------------------------------------------------------

importroles( )
{
   if [ -f ${EXPORTDIR}/rtproles -a -f ${EXPORTDIR}/admusers ];
   then
      logstr "   - Importing users and roles."
      #[1]. Get current version
      su - solid -c "$solsql -a -e \"select RTP_TABLE_NAME,RTP_CURR_SUFFIX from RTP_TABLE_MGMT\" \"tcp 16760\" dba $(getDbaPassword)" 1>${EXPORTDIR}/rtptablemgmt 2>&1
      rtprolesuffix="`grep RTP_ADM_ROLES ${EXPORTDIR}/rtptablemgmt | awk '{ print $2 }'`"
      admuserssuffix="`grep RTP_ADM_USERS ${EXPORTDIR}/rtptablemgmt | awk '{ print $2 }'`"
      #[2]. Export roles
      su - solid -c "$solexp -o  /tmp/rtproles 'tcp 16760' dba $(getDbaPassword) RTP_ADM_ROLES${rtprolesuffix}" 1>/dev/null 2>&1
      if [ $? -ne 0 ];
      then
         logstr "   - Skipping rtproles import."
         return
      fi
      #[3]. Export users
      su - solid -c "$solexp -o  /tmp/admusers 'tcp 16760' dba $(getDbaPassword) RTP_ADM_USERS${rtprolesuffix}" 1>/dev/null 2>&1
      if [ $? -ne 0 ];
      then
         logstr "   - Skipping rtpuser import."
         return
      fi
      #[4].Compare data
      cat /tmp/rtproles         | awk -F',' '{ print $1 }' > /tmp/rtproles.new
      cat /tmp/admusers         | awk -F',' '{ print $1 }' > /tmp/admusers.new
      
      #[5]. Exclude roles.
      ignorecount=0
      for usridx in `cat /tmp/rtproles.new`
      do
         if [ $ignorecount -eq 0 ];
         then
            ignorelst="$usridx"
         else
            ignorelst="$ignorelst|$usridx"
         fi
         ignorecount=`expr $ignorecount + 1`
      done
      cat ${EXPORTDIR}/rtproles | egrep -v "$ignorelst" > /tmp/rtproles.usr

      {
         echo "Current Roles"
         echo "-------------"
         cat /tmp/rtproles 
         echo "New Roles"
         echo "---------"
         cat /tmp/rtproles.usr
      } 1>>$LOGFILE 2>&1
      
      cp -f /tmp/rtproles.usr /tmp/rtproles
      su - solid -c "cd /tmp; $solload -L ${LOGSOLIDHOME}/solload.log -b 1000 \
                      -x nointegrity 'tcp 16760' dba $(getDbaPassword) rtproles.ctr" 1>>$LOGFILE 2>&1

      #[5]. Exclude users.
      ignorecount=0
      for usridx in `cat /tmp/admusers.new`
      do
         if [ $ignorecount -eq 0 ];
         then
            ignorelst="$usridx"
         else
            ignorelst="$ignorelst|$usridx"
         fi
         ignorecount=`expr $ignorecount + 1`
      done
      cat ${EXPORTDIR}/admusers | egrep -v "$ignorelst" > /tmp/admusers.usr

      {
         echo "Current Users"
         echo "-------------"
         cat /tmp/admusers
         echo "New Users"
         echo "---------"
         cat /tmp/admusers.usr
      } 1>>$LOGFILE 2>&1

      cp -f /tmp/admusers.usr /tmp/admusers
      su - solid -c "cd /tmp; $solload -L ${LOGSOLIDHOME}/solload.log -b 1000 \
                      -x nointegrity 'tcp 16760' dba $(getDbaPassword) admusers.ctr" 1>>$LOGFILE 2>&1

   fi
}

# ---------------------------------------------------------------
# function: importpasswds
# args    : None
# description:
#    import all the passwords.
#    add all user accounts whoose uid does not exist.
# ---------------------------------------------------------------

importpasswds( )
{
   passwd=/etc/passwd
   uids=/tmp/uids
   uaccts=/tmp/uaccts
   
   cfgelem=$1
   rm -f $uids $uaccts 
   logstr "   - Restoring passwords."
   #</FindCurUsers>
   {
      cat $passwd | cut -d':' -f1 | sort | uniq |  grep -v "^$"
   } > ${uids}.old
   #</FindCurUsers>
   
   #<FindNewUsers>
   {
      cat ${cfgelem} | cut -d':' -f1 | sort | uniq |  grep -v "^$"
   } > ${uids}.new
   #<FindNewUsers>

   #<FindDelta>
   comm -3 ${uids}.old ${uids}.new > ${uids}.relevent
   count=0
   for relidx in `cat ${uids}.relevent`
   do 
      cat ${cfgelem} | awk -v  idvar=$relidx  -F':' '{ if ( $1 == idvar ) print $0 }'  >> $passwd
      cat ${cfgelem} | awk -v  idvar=$relidx  -F':' '{ if ( $1 == idvar ) print $1 }'  >> $uaccts
      count=$(( $count + 1 ))
   done 
   logstr "   - Added #${count} new users from customers configuration."
   #</FindDelta>

   #<ObsoleteAccts>
   # only for simplex, can cause issues on GEO cluster
   if [ "$testbed" = "simplex" ];
   then
      # ==================OSV-15571================
      # the version which should be the last to have
      #  =========user systemd-bus-proxy===========
      # ================V9R3.33.2==================
      version_number_error=93332
      # =======get the current osv version========== 
      var=$(/unisphere/srx3000/srx/version/sysversion --pretty 2>/dev/null)
      if [ "$var" = "none" ];
      then 
         logwarning "[${BASH_SOURCE[1]}:${BASH_LINENO[0]}] File osv-release was not found!"
      fi
      # parse the version in order to get only the numbers"
      fields=(${var//\./ })
      field0=(${fields[0]//\R/ })
      #                             VX          RX          .X          .X
      version_number_current="${field0[0]:1}${field0[1]}${fields[1]}${fields[2]}"

      if [ $((version_number_current)) -gt ${version_number_error} ]
      then
          userdel -f "systemd-bus-proxy"
      fi
   fi
   # =========================================
   # =========================================
   # on JITC systems and on OSV V11 the ftpsecure must not be removed
   DOD_ENABLED=$(cfgread dod_enabled)
   EXTRA="ftpsecure"
   if [ "$DOD_ENABLED" = "yes" ] || [ "$DOD_ENABLED" = "Yes" ]
   then
       EXTRA=""
   fi
   if osv_version.sh --major compare sys ge V11
   then
      EXTRA=""
   fi
   for _u in $EXTRA rtp99 hispa
   do
      # Try unmap users from selinux, or fallback if not supported
      # may check first if users exist ???
      userdel -f -r -Z "${_u}" || userdel -f -r "${_u}"
   done >>"${LOGFILE}" 2>&1
   #</ObsoleteAccts>

   rm -f ${uids}.old ${uids}.new  
}

# ---------------------------------------------------------------
# function: importhomes
# args    : None
# description:
#   imports custom homes.
# ---------------------------------------------------------------

importhomes( )
{
   uids=/tmp/uids
   for relidx in `cat ${uids}.relevent`
   do 
      relidxinfo="`cat  ${EXPORTDIR}/accounts 2>/dev/null | grep \"^${relidx}:\" | head -1`"
      relidxhome="`echo $relidxinfo | awk -F':' '{ print $2 }'`"
      relidxmode="`echo $relidxinfo | awk -F':' '{ print $3 }'`"
      relidxown="`echo $relidxinfo  | awk -F':' '{ print $4 }'`"
      relidxgrp="`echo $relidxinfo  | awk -F':' '{ print $5 }'`"
      if [ "$relidxhome" != "" ];
      then
         logstr "   - Creating custom home $relidxhome."
         mkdir -p $relidxhome
         chmod $relidxmode $relidxhome
         chown ${relidxown}:${relidxgrp} $relidxhome
      fi 2>/dev/null
   done 
   chown solid.dba $SOLIDHOME
   rm -f ${uids}.relevent
}

# ---------------------------------------------------------------
# function: importgroups
# args    : None
# description:
#    import all the groups.
#    add all groups whoose uid does not exist.
# ---------------------------------------------------------------

importgroups( )
{
   group=/etc/group
   uids=/tmp/uids
   
   cfgelem=$1
   rm -f ${uids}.old ${uids}.new
   logstr "   - Restoring groups."
   #</FindCurUsers>
   {
      cat $group | cut -d':' -f3 | sort | uniq |  grep -v "^$"
   } > ${uids}.old
   #</FindCurUsers>
   
   #<FindNewUsers>
   {
      cat ${cfgelem} | cut -d':' -f3 | sort | uniq |  grep -v "^$"
   } > ${uids}.new
   #<FindNewUsers>

   #<FindDelta>
   comm -3 ${uids}.old ${uids}.new > ${uids}.grprelevent
   count=0
   for relidx in `cat ${uids}.grprelevent`
   do 
      nextgroup=`cat ${cfgelem} | awk -v  idvar=$relidx  -F':' '{ if ( $3 == idvar ) print $0 }' | awk -F ':' '{ print $1 }'`
      grep -q "^${nextgroup}:" $group
      if [ $? -ne 0 ];
      then
         cat ${cfgelem} | awk -v  idvar=$relidx  -F':' '{ if ( $3 == idvar ) print $0 }'  >> $group
         count=$(( $count + 1 ))
      else
         logstr "   - Adjusting group information for $nextgroup."
         newgroupid=`cat $group | grep "^${nextgroup}:" | awk -F ':' '{ print $3 }'`
         if [ "$relidx" != "" -a "$nextgroup" != "" ];
         then
            find ${EXPORTDIR} -group $relidx -exec chgrp $nextgroup {} \;
         fi 2>/dev/null
      fi
   done 
   grep -q "^sym:" /etc/passwd
   if [ $? -eq 0 ];
   then
         cat /etc/group | awk -F':' ' {                                   \
                             for( idx=1; idx<=NF; idx++ ) {               \
                               if ( ( $1 == "rtpgrp" ) && ( idx == 4 ) )  \
                                  printf("sym,%s",$idx);                  \
                               else {                                     \
                                  if ( idx != 4 )                         \
                                     printf("%s:",$idx);                  \
                                  else                                    \
                                     printf("%s",$idx);                   \
                               }                                          \
                             }                                            \
                             printf("\n");                                \
                           }'                                             \
                         > /etc/group.sym
         cat /etc/group.sym | sed -e 's/,sym//2g' -e 's/sym,//2g' > /etc/group
         rm -f /etc/group.sym
   fi
   logstr "   - Added #${count} new groups from customers configuration."
   #</FindDelta>
}

# ---------------------------------------------------------------
# function: importshadow
# args    : None
# description:
#    import all the groups.
#    add all shadow whoose uid does not exist.
# ---------------------------------------------------------------

importshadow( )
{
   shadow=/etc/shadow
   uaccts=/tmp/uaccts

   cfgelem=$1
   logstr "   - Restoring shadow."
   if [ -f $uaccts ];
   then
      #<FindShadow>
         for shadowidx in `cat $uaccts`
         do
            cat ${cfgelem} | awk -v  idvar=$shadowidx  -F':' '{ if ( $1 == idvar ) print $0 }'
         done >> $shadow
      #<FindShadow>
   fi

   if [ "$IMPORTPASSWD" = "true" ];
   then
      #<ImportPasswords>
      logstr "   - Importing older passwords."
      rm -f ${shadow}.preserve
      for shadowidx in `cat $shadow | awk -F':' '{print $1 }'`
      do
         oldshadow="`grep \"^[ \t]*$shadowidx:\" $cfgelem`"
         if [ "$oldshadow" = "" ];
         then
            oldshadow="`grep \"^[ \t]*$shadowidx:\" $shadow`"
         fi
         if [ "$oldshadow" != "" ];
         then
            echo $oldshadow >> ${shadow}.preserve
         fi
      done

      cp ${shadow}.preserve ${shadow}
      rm -f ${shadow}.preserve
      #</ImportPasswords>
   fi
   fulldate=$(date +%F)
   {
      chage -E -1 sym
      for passidx in `cat /etc/passwd | awk -F':' '{ print $1 }'`
      do
         chage -d $fulldate $passidx
         chage -l $passidx
      done 
   } 1>>$LOGFILE 2>&1

}

# ---------------------------------------------------------------
# function: importfileparam
# args    : None
# description:
#    import some parameters from the files that sould be changed with package uptates
#    if files don'e exist in target system or source system, does nothing
# 
#  it uses parameter_files list, that has all of the files that need to only preserve some parameters
# ---------------------------------------------------------------
 
importfileparam ( ){

   for file in "${parameter_files[@]}"
   do

      tmp_filename="$EXPORTDIR""$file"
      
      filename=$(echo "$file" | sed "s/.*\///")

      if [[ -f $file && -f $tmp_filename ]]; then

         logstr "[${_SELF_}]: Importing $file parameters from $tmp_filename."

         #<developer's logic>
         # ---------configuration of sshd--------
         if [ $filename = "sshd" ];
         then
            # ----------pam_pkcs11.so-------------
            pam_pkcs11_tmp=$(grep "pam_pkcs11.so" $tmp_filename)
            if [ $? -eq 0 ];then
               pam_pkcs11=$(grep "pam_pkcs11.so" $file)
               sed -i "s/$pam_pkcs11/$pam_pkcs11_tmp/g" "$file"
            fi
         fi
         # ---------configuration of sshd_config--------
         if [ $filename = "sshd_config" ];
         then
            # ----------AuthorizedKeysCommand-----------
            Authorized_tmp=$(grep -w "AuthorizedKeysCommand" $tmp_filename)
            if [ $? -eq 0 ];then
               Authorized=$(grep -w "AuthorizedKeysCommand" $file)
               sed -i "s/$Authorized/$Authorized_tmp/g" "$file"
            fi
            # ----------AuthorizedKeysCommandUser-----------
            Authorized_user_tmp=$(grep "AuthorizedKeysCommandUser" $tmp_filename)
            if [ $? -eq 0 ];then
               Authorized_user=$(grep "AuthorizedKeysCommandUser" $file)
               sed -i "s/$Authorized_user/$Authorized_user_tmp/g" "$file"
            fi
            # --------------------ciphers-------------------
            Ciphers_tmp=$(grep "Ciphers" $tmp_filename | head -n 2 | tail -n 1)
            if [ "$Ciphers_tmp" != "" ];then
               Ciphers=$(grep "Ciphers" $file  | head -n 2 | tail -n 1)
               sed -i "s/$Ciphers/$Ciphers_tmp/g" "$file"
            fi
            # -----------------------macs----------------------
            MACs_tmp=$(grep "MACs" $tmp_filename)
            if [ $? -eq 0 ];then
               MACs=$(grep "MACs" $file)
               sed -i "s/$MACs/$MACs_tmp/g" "$file"
            fi
            # -----------------ssh banner-----------------------
            Banner_tmp=$(grep "^Banner" $tmp_filename)
            if [ $? -eq 0 ];then
               Banner=$(grep "^Banner" $file)
               Banner_tmp="${Banner_tmp//\//\\\/}"
               Banner=$(grep "^Banner" $file)
               if [ $? -eq 0 ];then
                  Banner="${Banner//\//\\\/}"
                  sed -i "s/$Banner/$Banner_tmp/g" "$file"
               else
                  Banner=$(grep "#Banner" $file)
                  sed -i "/$Banner/a\
                     $Banner_tmp/" "$file"
               fi
            fi
         fi
         # ---------configuration of pam_pkcs11.conf--------
         if [ $filename = "pam_pkcs11.conf" ];
         then
            # ---------cert_policy------------
            cert_policy_tmp=$(grep "cert_policy" $tmp_filename | head -n 2 | tail -n 1)
            if [ "$cert_policy_tmp" != "" ];then
               cert_policy=$(grep "cert_policy" $file | head -n 2 | tail -n 1)
               sed -i "s/$cert_policy/$cert_policy_tmp/g" "$file"
            fi
            # ---------use_mappers------------
            use_mappers_tmp=$(grep "use_mappers" $tmp_filename)
            if [ $? -eq 0 ];then
               use_mappers=$(grep "use_mappers" $file)
               sed -i "s/$use_mappers/$use_mappers_tmp/g" "$file"
            fi
            # ------------filter--------------
            filter_tmp=$(grep "filter =" $tmp_filename)
            if [ $? -eq 0 ];then
               filter=$(grep "filter =" $file)
               sed -i "s/$filter/$filter_tmp/g" "$file"
            fi
            # ---------------ssl---------------
            ssl_tmp=$(grep "ssl =" $tmp_filename)
            if [ $? -eq 0 ];then
               ssl=$(grep "ssl =" $file)
               sed -i "s/$ssl/$ssl_tmp/g" "$file"
            fi
            # -----------tls_cacertfile-------
            tls_cacertfile_tmp=$(grep "tls_cacertfile" $tmp_filename)
            if [ $? -eq 0 ];then
               tls_cacertfile=$(grep "tls_cacertfile" $file)
               sed -i "s/$tls_cacertfile/$tls_cacertfile_tmp/g" "$file"
            fi
            # -----------tls_cacertdir------------
            tls_cacertdir_tmp=$(grep "tls_cacertdir" $tmp_filename)
            if [ $? -eq 0 ];then
               tls_cacertdir=$(grep "tls_cacertdir" $file)
               tls_cacertdir_tmp="${tls_cacertdir_tmp//\//\\\/}" #this is because the tls cacertdir is probably a path
               tls_cacertdir="${tls_cacertdir//\//\\\/}"
               sed -i "s/$tls_cacertdir/$tls_cacertdir_tmp/g" "$file"
            fi
            # ------------tls_checkpeer------------
            tls_checkpeer_tmp=$(grep "tls_checkpeer" $tmp_filename)
            if [ $? -eq 0 ];then
               tls_checkpeer=$(grep "tls_checkpeer" $file)
               sed -i "s/${tls_checkpeer}/${tls_checkpeer_tmp}/g" "$file"
            fi
            # ----------uid_attribute=-----------
            uid_attribute_tmp=$(grep "uid_attribute" $tmp_filename)
            if [ $? -eq 0 ];then
               uid_attribute=$(grep "uid_attribute" $file)
               sed -i "s/${uid_attribute}/${uid_attribute_tmp}/g" "$file"
            fi
         fi
          # ---------configuration of common-auth--------
         if [ $filename = "common-auth" ];
         then
            # ----------pam_pkcs11.so-------------
            pam_pkcs11_tmp=$(grep "pam_pkcs11.so" $tmp_filename)
            if [ $? -eq 0 ];then
               pam_pkcs11=$(grep "pam_pkcs11.so" $file)
               sed -i "s/$pam_pkcs11/$pam_pkcs11_tmp/g" "$file"
            fi
         fi
         # --------configuration of common-password--------
         if [ $filename = "common-password" ];
         then
            # ----------pam_cracklib.so-------------
            pam_cracklib_tmp=$(grep "pam_cracklib.so" $tmp_filename)
            if [ $? -eq 0 ];then
               pam_cracklib=$(grep "pam_cracklib.so" $file)
               sed -i "s/$pam_cracklib/$pam_cracklib_tmp/g" "$file"
            fi
         fi
         #</developer's logic>
         
      else
         logstr "[${_SELF_}]: $file was not found, skipping restoration."
      fi

   done
}

# ---------------------------------------------------------------
# function: importsshdconfig
# args    : None
# description:
#   import previous sshd configuration and store it for further usage.
# ---------------------------------------------------------------

# this functionality is replaced by function importfileparam
# the export function is handled by sshdconfig_add_ciphers_macs
# since this is not a simple export, but it adds ciphers and macs to it

# importsshdconfig( )
# {
#    sshd_config_file="/etc/ssh/sshd_config"
#    if [ -f ${EXPORTDIR}/${sshd_config_file} ]
#    then
#       mv ${EXPORTDIR}/${sshd_config_file} ${sshd_config_file}.old
#    fi
# }

# ---------------------------------------------------------------
# function IPvalidator()
# args: IPV4 or IPV6 string
# description
# returns 0 if valid IP address detected
# returns 1 when there is an invalid IP address given
# called by importtrusted
# ---------------------------------------------------------------

function IPvalidator()
{
   IPRETX=1
   if [ "$1" != "" ]
   then
      MY_IP_V6=$(echo "$1" | grep ":" | wc -l)
      if [ $MY_IP_V6 -ne 0 ]
      then
	 #MASK out non hex characters
	 MYINV=$(echo "$1" | tr -d ":0123456789abcdefABCDEF")
	 if [ "$MYINV" = "" ]
	 then
           IPRETX=0
         fi
      else
        #check for IP V4
        DOTCNT=$(echo "$1" | tr -c -d "." | wc -m)
        if [ $DOTCNT -eq 3 ]
        then
           # set PARTCOUNTER 
           IPVALIDPART=0
	   # set ERROR count
	   ERRORCNT=0
	   # take the 4 parts of the IPV4
           IPV4P1=$(echo "$1" | cut -d "." -f1)
           IPV4P2=$(echo "$1" | cut -d "." -f2)
           IPV4P3=$(echo "$1" | cut -d "." -f3)
           IPV4P4=$(echo "$1" | cut -d "." -f4)
	   #check if each part is not empty
	   if [ "IPV4P1" = "" ] || [ "$IPV4P2" = "" ] || [ "$IPV4P3" = "" ] || [ "$IPV4P4" = "" ]
	   then
              ERRORCNT=1
	   fi
	   # check if only allowed values, include also the dot, since it is the separator
	   MYDIGIT=$(echo "$1" | tr -d ".0123456789")
	   if [ "$MYDIGIT" != "" ]
           then
               ERRORCNT=$((ERRORCNT+1))
	   fi
	   if [ $ERRORCNT -eq 0 ]
	   then
             #check ranges [0 - 255], except for first part
	     # first part of IPV4 must be greater than 0
             if [ $IPV4P1 -gt 0 ] && [ $IPV4P1 -le 255 ]
             then
                IPVALIDPART=$((IPVALIDPART+1))
             fi
             if [ $IPV4P2 -ge 0 ] && [ $IPV4P2 -le 255 ]
             then
                 IPVALIDPART=$((IPVALIDPART+1)) 
             fi
             if [ $IPV4P3 -ge 0 ] && [ $IPV4P3 -le 255 ]
             then
                IPVALIDPART=$((IPVALIDPART+1))
             fi
             if [ $IPV4P4 -ge 0 ] && [ $IPV4P4 -le 255 ]
             then
                IPVALIDPART=$((IPVALIDPART+1))
             fi
             # now the IPVALIDPART must be 4 since we have 4 IP V4 parts
             # only if a part of the IP was valid then counter is incremented
             if [ $IPVALIDPART -eq 4 ]
             then
                IPRETX=0
             fi
          fi #ERRORCNT
       fi # num of dots
     fi #IP V6
   fi  # if input not empty

   return $IPRETX
}


# ---------------------------------------------------------------
# function: importtrusted
# args    : None
# description:
#    import all the trusted hosts.
# ---------------------------------------------------------------

importtrusted( )
{
   if osv_version.sh compare "$tomajor" lt V8; 
   then
      Rules4Host=/etc/rules/hiq8000.rules
      sidiprule="sid:5000007"
      sidstunrule="sid:5000010"
      sidstunrule2="sid:5000010"
      fblockdurationdest=5
      fratethresholddest=3
      fkeepaliveblockdest=3
      fkeepalivethresholddest=5
   else
      Rules4Host=/etc/rules/osv.rules
      sidiprule="rate_filter.*sig_id 5000100"
      sidstunrule="rate_filter.*sig_id 5000600"
      sidstunrule2="rate_filter.*sig_id 5000700"
      fblockdurationdest=7
      fratethresholddest=4
      fkeepalivethresholddest=7
      fkeepaliveblockdest=4
   fi
   if osv_version.sh compare "$frommajor" lt V8; 
   then
      ExpRules4Host=/etc/rules/hiq8000.rules
      expsidiprule="sid:5000007"
      expsidstunrule="sid:5000010"
      expsidstunrule2="sid:5000010"
      fblockdurationsrc=5
      fratethresholdsrc=3
      fkeepaliveblocksrc=3
      fkeepalivethresholdsrc=5
   else
      ExpRules4Host=/etc/rules/osv.rules
      expsidiprule="rate_filter.*sig_id 5000100"
      expsidstunrule="rate_filter.*sig_id 5000600"
      expsidstunrule2="rate_filter.*sig_id 5000700"
      fblockdurationsrc=7
      fratethresholdsrc=4
      fkeepalivethresholdsrc=7
      fkeepaliveblocksrc=4
   fi
   sidevstunrule2="event_filter.*sig_id 5000600"
   sidevstunrule3="event_filter.*sig_id 5000700"
   sideviprule2="event_filter.*sig_id 5000100"
   
   HiqRules=/tmp/hiqrules
   cat $Rules4Host 2>/dev/null | grep -P "^[ \t]*var WHITELIST"       |                                   \
                sed -e 's/.*\[//g' -e 's/\].*//g' | sed -e 's/,/\n/g' | grep -v "^$" > ${HiqRules}.new
   cat ${EXPORTDIR}/$ExpRules4Host 2>/dev/null | grep -P "^[ \t]*var WHITELIST"      |                    \
                sed -e 's/.*\[//g' -e 's/\].*//g' | sed -e 's/,/\n/g' | grep -v "^$"          |           \
                egrep -v "127.0.0.1|ncs_ip_alias|sip_ip_alias|sip_ipv6_alias|bond_partner|bond_node|oam_ip_alias|bond_bms|bond_udp|csta_ip_alias|cluster_node|cluster_partner|misc_|link_local|link_remote|lsm_ip_alias|dns_server|ntp_server|snmp_server|sis_server|superuser_ip" \
                > ${HiqRules}.old
   #<AddMiscHost>
      misccount=0
      while [ $misccount -le 64 ];
      do
         nextmisc=`cfgread misc_count${misccount}`
         if [ "$nextmisc" != "" ];
         then
            echo $nextmisc >> ${HiqRules}.new
         fi
         misccount=$[misccount+1]
      done
   #</AddMiscHost>
   #<V3.0Trusted>
      if [ -f ${EXPORTDIR}/etc/spp_packetrate.conf ];
      then
         cat ${EXPORTDIR}/etc/spp_packetrate.conf | grep ExemptHosts | sed -e 's/[a-zA-Z{}=" ]*//g' |     \
             sed -e 's/,/\n/g' | grep -v "^$" |                                                           \
             egrep -v "127.0.0.1|ncs_ip_alias|sip_ip_alias|sip_ipv6_alias|bond_partner|bond_node|oam_ip_alias|bond_bms|bond_udp|csta_ip_alias"
      fi >> ${HiqRules}.old
   #</V3.0Trusted>

   cp ${HiqRules}.new $HiqRules
   for  hiqruleidx in `cat ${HiqRules}.old`
   do
      grep -q -P "^[ \t]*${hiqruleidx}[ \t]*$" $HiqRules 
      if [ $? -ne 0 ];
      then
         echo "$hiqruleidx" | egrep -q "^[0-9]|:"
         if [ $? -eq 0 ];
         then
            egrep -q "^${hiqruleidx}$" $HiqRules
            if [ $? -ne 0 ];
            then
			   # check if valid IP address either IPV4 or IPV6
			   IPvalidator "$hiqruleidx"
			   if [ $? -eq 0 ]
			   then
                               logstr "   - Adding trusted $hiqruleidx"
                               echo $hiqruleidx >> $HiqRules
			   else
			       logstr "   - rejected  $hiqruleidx  -- Reason: invalid IP address"
			   fi
            fi
         fi
      else
         logstr "   - Skipping snort rule for $hiqruleidx"
      fi
   done

   newhiqruleslst='var WHITELIST ['
   hiqrulecount=0
   for hiqruleidx in `cat $HiqRules`
   do
      if [ $hiqrulecount -eq 0 ];
      then
         newhiqruleslst+="${hiqruleidx}"
      else
         newhiqruleslst+=",$hiqruleidx"
      fi
      hiqrulecount=`expr $hiqrulecount + 1`
   done

   newhiqruleslst="`echo ${newhiqruleslst} | sed -e 's/\//%/g'`"
   newhiqruleslst+=']'
   logstr "   - update : $newhiqruleslst" 

   #</DosMgmt>
      blockdurationdest="`cat $Rules4Host 2>/dev/null      |       \
                                   egrep \"$sidiprule\"    | cut -d\",\" -f$fblockdurationdest | sed -e 's/;)//g'`"
      ratethresholddest="`cat $Rules4Host 2>/dev/null      |       \
                                   egrep \"$sidiprule\"    | cut -d\",\" -f$fratethresholddest | sed -e 's/;)//g'`"
      keepaliveblockdest="`cat $Rules4Host 2>/dev/null     |      \
                                   egrep \"$sidstunrule\"  | cut -d\",\" -f$fkeepaliveblockdest| sed -e 's/;)//g'`"
      keepalivethresholddest="`cat $Rules4Host 2>/dev/null |  \
                                   egrep \"$sidstunrule\"  | cut -d\",\" -f$fkeepalivethresholddest | sed -e 's/;)//g'`"
      if [ -f ${EXPORTDIR}/etc/spp_packetrate.conf ];
      then
         blockdurationsrc="`cat ${EXPORTDIR}/etc/spp_packetrate.conf 2>/dev/null |       \
                                   grep \"^BlockDuration\" | awk -F'=' '{ print $2 }'`"
         ratethresholdsrc="`cat ${EXPORTDIR}/etc/spp_packetrate.conf 2>/dev/null | \
                                   grep \"^RateThreshold\" | awk -F'=' '{ print $2 }'`"
         keepaliveblocksrc="$keepaliveblockdest"
         keepalivethresholdsrc="$keepalivethresholddest"
         if [ "$blockdurationsrc" != "" ];
         then
            blockdurationsrc="$blockdurationsrc seconds"
         else
            blockdurationsrc="$blockdurationdest"
         fi
         if [ "$ratethresholdsrc" != "" ];
         then
            ratethresholdsrc="count $ratethresholdsrc"
         else
            ratethresholdsrc="$ratethresholddest"
         fi
      else
         blockdurationsrc="`cat ${EXPORTDIR}/$ExpRules4Host 2>/dev/null |       \
                                   egrep \"$expsidiprule\"   | cut -d\",\" -f$fblockdurationsrc  | sed -e 's/;)//g'`"
         ratethresholdsrc="`cat ${EXPORTDIR}/$ExpRules4Host 2>/dev/null |       \
                                   egrep \"$expsidiprule\"   | cut -d\",\" -f$fratethresholdsrc  | sed -e 's/;)//g'`"
         keepaliveblocksrc="`cat ${EXPORTDIR}/$ExpRules4Host 2>/dev/null |      \
                                   egrep \"$expsidstunrule\" | cut -d\",\" -f$fkeepaliveblocksrc | sed -e 's/;)//g'`"
         keepalivethresholdsrc="`cat ${EXPORTDIR}/$ExpRules4Host 2>/dev/null |  \
                                   egrep \"$expsidstunrule2\" | cut -d\",\" -f$fkeepalivethresholdsrc | sed -e 's/;)//g'`"
         if [ "$blockdurationsrc" = "" ];
         then
            blockdurationsrc="$blockdurationdest"
         fi
         if [ "$ratethresholdsrc" = "" ];
         then
            ratethresholdsrc="$ratethresholddest"
         fi
         if [ "$keepaliveblocksrc" = "" ];
         then
            keepaliveblocksrc="$keepaliveblockdest"
         fi
         if [ "$keepalivethresholdsrc" = "" ];
         then
            keepalivethresholdsrc="$keepalivethresholddest"
         fi
      fi
   #</DosMgmt>

   #<FixThrSyntaxV8>
      if osv_version.sh --major compare sys ge V8; 
      then
         ratethresholdsrcnorm=`echo $ratethresholdsrc   | sed -e 's/[a-zA-Z \t]*//g'`
         blockdurationsrcnorm=`echo $blockdurationsrc   | sed -e 's/[a-zA-Z \t]*//g'`
         exprpfesecsrc="seconds $blockdurationsrcnorm"
         exprpfecountsrc="count `expr $ratethresholdsrcnorm \* $blockdurationsrcnorm`"

         keepaliveblocksrcnorm=`echo $keepaliveblocksrc         | sed -e 's/[a-zA-Z \t]*//g'`
         keepalivethresholdsrcnorm=`echo $keepalivethresholdsrc | sed -e 's/[a-zA-Z \t]*//g'`
         exprsfesecsrc="seconds $keepalivethresholdsrcnorm"
         exprsfecountsrc="count `expr $keepaliveblocksrcnorm \* $keepalivethresholdsrcnorm`"

         ratethresholddestnorm=`echo $ratethresholddest | sed -e 's/[a-zA-Z \t]*//g'`
         blockdurationdestnorm=`echo $blockdurationdest | sed -e 's/[a-zA-Z \t]*//g'`
         exprpfesecdest="seconds $blockdurationdestnorm"
         exprpfecountdest="count `expr $ratethresholddestnorm \* $blockdurationdestnorm`"

         keepaliveblockdestnorm=`echo $keepaliveblockdest         | sed -e 's/[a-zA-Z \t]*//g'`
         keepalivethresholddestnorm=`echo $keepalivethresholddest | sed -e 's/[a-zA-Z \t]*//g'`
         exprsfesecdest="seconds $keepalivethresholddestnorm"
         exprsfecountdest="count `expr $keepaliveblockdestnorm \* $keepalivethresholddestnorm`"

         blockdurationsrc="`echo $blockdurationsrc|sed -e 's/[ \t]seconds//g' -e 's/timeout[ \t]//g' -e 's/^/timeout /'`"
         keepalivethresholdsrc="`echo $keepalivethresholdsrc|sed -e 's/[ \t]seconds//g' -e 's/timeout[ \t]//g' -e 's/^/timeout /'`"
         blockdurationdest="`echo $blockdurationdest|sed -e 's/[ \t]seconds//g' -e 's/timeout[ \t]//g' -e 's/^/timeout /'`"
         keepalivethresholddest="`echo $keepalivethresholddest|sed -e 's/[ \t]seconds//g' -e 's/timeout[ \t]//g' -e 's/^/timeout /'`"
      fi
   #</FixThrSyntaxV8>

   logstr "   - > snort import."
   logstr "   - blockdurationsrc($blockdurationsrc), blockdurationdest($blockdurationdest)."
   logstr "   - ratethresholdsrc($ratethresholdsrc), ratethresholddest($ratethresholddest)."
   logstr "   - keepaliveblocksrc($keepaliveblocksrc), keepaliveblockdest($keepaliveblockdest)."
   logstr "   - keepalivethresholdsrc($keepalivethresholdsrc), keepalivethresholddest($keepalivethresholddest)."

   cat $Rules4Host | sed -e "s/var[ \t]*WHITELIST.*/$newhiqruleslst/"                           \
                         -e "/$sidiprule/s/$blockdurationdest/$blockdurationsrc/"               \
                         -e "/$sidiprule/s/$ratethresholddest/$ratethresholdsrc/"               \
                         -e "/$sidstunrule/s/$keepaliveblockdest/$keepaliveblocksrc/"           \
                         -e "/$sidstunrule/s/$keepalivethresholddest/$keepalivethresholdsrc/"   \
                         -e "/$sidstunrule2/s/$keepaliveblockdest/$keepaliveblocksrc/"          \
                         -e "/$sidstunrule2/s/$keepalivethresholddest/$keepalivethresholdsrc/"  \
                         -e "/$sidevstunrule2/s/$exprsfesecdest/$exprsfesecsrc/"                \
                         -e "/$sidevstunrule2/s/$exprsfecountdest/$exprsfecountsrc/"            \
                         -e "/$sidevstunrule3/s/$exprsfesecdest/$exprsfesecsrc/"              \
                         -e "/$sidevstunrule3/s/$exprsfecountdest/$exprsfecountsrc/"          \
                         -e "/$sideviprule2/s/$exprpfesecdest/$exprpfesecsrc/"                  \
                         -e "/$sideviprule2/s/$exprpfecountdest/$exprpfecountsrc/"              \
                         -e "/var WHITELIST/s/%/\//g"                                           \
        > ${Rules4Host}.new
   cp ${Rules4Host}.new $Rules4Host
   cp -f -p ${Rules4Host} ${Rules4Host}.import
   rm -f ${Rules4Host}.new
}

# ---------------------------------------------------------------
# function: importdns
# args    : None
# description:
#    import all the dns configurations.
# ---------------------------------------------------------------

importdns( )
{
   logstr "function: importdns is called"
   if [ "$SYSIMPORT" = "true" -a                          \
        -x /unisphere/srx3000/callp/bin/buildDNSconfig -a \
        -f ${EXPORTDIR}/etc/hiq8000/fqdn.cfg ];
   then
       logstr "   - Building dns configuration."
       cp -p ${EXPORTDIR}/etc/hiq8000/fqdn.cfg /etc/hiq8000/fqdn.cfg
       /unisphere/srx3000/callp/bin/buildDNSconfig 1>>$LOGFILE 2>&1
       if [ $? -eq 0 ];
       then
          logstr "      - Success."
       else
          logstr "      - Failed."
       fi
   fi
}

# ---------------------------------------------------------------
# function: importhosts
# args    : None
# description:
#    import all the hosts.
# ---------------------------------------------------------------

importhosts( )
{
   logstr "function: importhosts is called"
   custhost=$1
   custcfg=$2
   oldmethod=true
   curcfg=/etc/hiq8000/node.cfg

 if osv_version.sh --major compare sys ge V8; 
      then
	logstr "   - Rebuilding hosts."
	if [ -e /etc/hiq8000/config/bin/hosts_configuration.sh ]
		then
		oldmethod=false
		/etc/hiq8000/config/bin/hosts_configuration.sh $custcfg $custhost /tmp/hosts.new >/dev/null 2>&1
		cp /tmp/hosts.new /etc/hosts
	        rm /tmp/hosts.new
		else
		oldmethod=true
		logstr "   - hosts_configuration does not exist, so I will use old method."
		fi
      fi
	
	
if [ "$oldmethod" == "true" ]
then

   usrlst="license_server     \
           billing_server     \
           billing_client     \
           csta_server        \
           smc_server         \
           ssc_server         \
           pmc_server         \
           snmp_server        \
           ntp_server         \
           name_server        \
           default_router     \
           static_route       \
           dos_whitelist      \
           misc_host"
   ignorelst=""
   ignorecount=0
   for usridx in $usrlst
   do
      if [ $ignorecount -eq 0 ];
      then
         ignorelst="$usridx"
      else
         ignorelst="$ignorelst|$usridx"
      fi
      ignorecount=`expr $ignorecount + 1`
   done
   cat $custcfg | egrep -v "$ignorelst" > ${custcfg}.sys
   custcfg=${custcfg}.sys
   cat $curcfg  | egrep -v "$ignorelst" > ${curcfg}.sys
   curcfg=${curcfg}.sys

   logstr "   - Restoring hosts."
   if [ ! -f /tmp/hosts -o ! -f $custcfg ];
   then
       textncolor $BoldRed "Skipping host adjustment. node.cfg not found."
       return
   fi

   fixedhosts="          \
      localhost          \
      ipv6-localhost     \
      ipv6-localnet      \
      ipv6-mcastprefix   \
      ipv6-allnodes      \
      ipv6-allrouters    \
      ipv6-allhosts      \
      rtp_com            \
      sip_ip_alias       \
      sip_ipv6_alias     \
      ncs_ip_alias       \
      rtp_ip_eth         \
      bond_udp_alias     \
      bond_partner_udp   \
      bond_node_alias    \
      csta_ip_alias      \
      bond_partner_alias \
      mgcp_ip_alias      \
      oam_ip_alias       \
      tgcp_ip_alias      \
    "
    parsedips=$(perl -lp0777e'$_=join"\n",/!?[\d.]+(?:\/\d+)?/g' $custcfg); 
    parsedipshost=$(perl -lp0777e'$_=join"\n",/!?[\d.]+(?:\/\d+)?/g' $curcfg); 
    knownhosts=""
    hostcmd=""
    count=0
    for hostidx in $fixedhosts
    do
       if [ $count -eq 0 ];
       then
          hostcmd="grep -v \"^[ \t]*#\" | grep -v \"^[ \t]*$\" | grep -v \"[ \t]*$hostidx\""
       else 
          hostcmd="${hostcmd} | grep -v -P \"[ \t]*$hostidx\""
       fi
       count=`expr $count + 1`
    done 
    for hostidx in $parsedips $parsedipshost
    do
        echo $hostidx | egrep -q "[0-9]+.[0-9]+.[0-9]+.[0-9]+"
        if [ $? -eq 0 ];
        then
           hostcmd="${hostcmd} | grep -v -P \"^[ \t]*$hostidx[ \t]\""
        fi
    done 
    cat << EOF >/tmp/newhosts
cat $custhost | $hostcmd
status=\$?
exit \$status
EOF
    chmod 755 /tmp/newhosts
    /tmp/newhosts > /tmp/newhosts.lst
    if [ $? -eq 0 ];
    then
       newips=`cat /tmp/newhosts.lst | awk '{ print $1 }' | sort | uniq` 
       for newipidx in $newips
       do
          grep -q -P "^[ \t]*${newipidx}[ \t]" /etc/hosts
          if [ $? -ne 0 ];
          then
             logstr "   - Adding $newipidx to hosts."
             grep -P "^[ \t]*${newipidx}[ \t]" /tmp/newhosts.lst >> /etc/hosts
          fi
       done
    fi
    #<ImportDnsSrv>
       dnsalias="            \
          sipsm1_vip         \
          sipsm2_vip         \
          sipsm3_vip         \
          sipsm4_vip         \
          sipsm1_vip_2       \
          sipsm2_vip_2       \
          sipsm3_vip_2       \
          sipsm4_vip_2       \
          sipsm1_vipV6       \
          sipsm2_vipV6       \
          sipsm3_vipV6       \
          sipsm4_vipV6       \
          cstasm1_vip        \
          cstasm2_vip        \
          cstasm1_vip_2      \
          cstasm2_vip_2      \
          ccm05_1_vip        \
          ccm05_2_vip        \
	  survival_authority \
        "
        for dnsidx in $dnsalias
        do
           getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  $dnsidx nextdns
           if [ "$nextdns" != "" -a "$nextdns" != "0.0.0.0" ];
           then
              egrep -w "$nextdns" $custhost
           fi
        done | egrep -v "sip_ip_alias|sip_ipv6_alias|csta_ip_alias|ncs_ip_alias|mgcp_ip_alias|lsm_ip_alias|rtp_|bond_|omni_" | sort | uniq > /tmp/auxhosts
        if [ "$Migrate8k" = "true" ];
        then
           cat /tmp/auxhosts | $execcmd $auxcmd >> /etc/hosts
        else
           cat /tmp/auxhosts >> /etc/hosts
        fi
    #</ImportDnsSrv>

    #<IgnoreDiscardedAlias>
       cat /etc/hosts  | egrep -v "h323_gk01_ip_alias|h323_gk02_ip_alias" > /etc/hosts.new
       cp /etc/hosts.new /etc/hosts
       rm -f /etc/hosts.new
    #</IgnoreDiscardedAlias>


    rm -f /tmp/newhosts /tmp/newhosts.lst

	fi #end if old way of importing hosts 
}

# ---------------------------------------------------------------
# function: importaccessconf
# args: None
# description:
#	Handle the imported /etc/security/access.conf coming from the
#	source system.
# ---------------------------------------------------------------
importaccessconf( ) {
   logstr "function: importaccessconf is called"
    if osv_version.sh --major compare sys ge V4; 
    then
       superuserip="`cfgread superuserip`"
       accessconf=/etc/security/access.conf
       #<NoSuperUserIp>
       if [ "$superuserip" = "0.0.0.0" ]
       then
          superuserip=""
       fi
       #</NoSuperUserIp>
       cat $accessconf | uniq |                                                                          \
            sed -e 's/:root[ \t]*srx:ALL[ \t]* EXCEPT[ \t]*LOCAL/:root srx:ALL EXCEPT /g'                \
                -e 's/:root[ \t]*:ALL[ \t]* EXCEPT[ \t]*LOCAL/:root:ALL EXCEPT /g'                       \
                -e 's/:srx[ \t]*:ALL[ \t]* EXCEPT[ \t]*LOCAL/:srx:ALL EXCEPT /g'                         \
                -e "s/${superuserip} / /g"                                                               \
                -e 's/dba / /'                                                                           \
                -e 's/oracle //'                                                                         \
                -e "s/localhost//g"                                                                      \
                -e "s/:root[ \t]*srx:ALL[ \t]* EXCEPT[ \t]/:root srx:ALL EXCEPT LOCAL ${superuserip} localhost /g" \
                -e "s/:root[ \t]*:ALL[ \t]* EXCEPT[ \t]/:root:ALL EXCEPT LOCAL ${superuserip} localhost /g"        \
                -e "s/:srx[ \t]*:ALL[ \t]* EXCEPT[ \t]/:srx:ALL EXCEPT LOCAL ${superuserip} localhost /g"          \
                -e "s/${primhost} /${primhost} ${primhost}_cip0 /g"                                      \
                -e "s/${sechost} /${sechost} ${sechost}_cip0 /g"                                         \
                -e "s/$primhost //2g"                                                                    \
                -e "s/$sechost //2g"                                                                     \
                -e "s/${primhost}_cip0 //2g"                                                             \
                -e "s/${sechost}_cip0 //2g"                                                              \
                -e "s/solid[ \t]*:/rtp solid:/"                                                          \
                -e "/rtp solid:/s/rtp //2g"                                                              \
                -e "/+:srx:ALL EXCEPT /d"                                                                \
                -e "s/console //g"                                                                       \
                -e "s/tty1 //g"                                                                          \
                -e "s/tty2 //g"                                                                          \
                -e "s/tty3 //g"                                                                          \
                -e "s/tty4 //g"                                                                          \
                -e "s/tty5 //g"                                                                          \
                -e "s/tty6 //g"                                                                          \
       > ${accessconf}.new
       cp  ${accessconf}.new $accessconf
       rm -f ${accessconf}.new
    fi

    if osv_version.sh --major compare sys ge V7; 
    then
       egrep -q "^-:solid:.*cluster_partner_alias.*" $accessconf
       if [ $? -ne 0 ]; 
       then
          logstr "   - Adding solid security restrictions to access.conf"
          echo "-:solid:ALL EXCEPT LOCAL cluster_partner_alias" >> $accessconf
       fi
       cat $accessconf | sed -e "s/-:rtp solid:/-:rtp:/g" > ${accessconf}.new
       cp  ${accessconf}.new $accessconf
       rm -f ${accessconf}.new
    fi

    # OSV-2435: In case of importing to an OSEE V9 or above system, add the static
    # CMP IPv4 to the allowed hosts for remote login as user 'srx'
    if osv_version.sh --major compare sys ge V9 && [ "X$(isOSEE)X" = "XtrueX" ];
    then
        loginfo "Allowing user 'srx' remote login from CMP/Assistant"
        local allowed_user='srx'
        local cmp_oseelan_ipv4="10.82.53.233"
        /usr/local/bin/osv_install_security -adduseraccesshost "${allowed_user}" "${cmp_oseelan_ipv4}"
    fi
}

# ---------------------------------------------------------------
# function: importmssettings
# args    : None
# description:
#    imports media server settings.
# ---------------------------------------------------------------

importmssettings( )
{
   logstr "function: importmssettings is called"
   PROVIDERS=/enterprise/mediaserver/application_host/providers
   XMLLIST="                                                        \
      ${PROVIDERS}/mgcp/mgcp.xml                                    \
      ${PROVIDERS}/sip-connectivity/sip-connectivity.xml            \
      ${PROVIDERS}/streaming-mps/streaming-mps.xml                  \
      ${PROVIDERS}/mediagateway/mediagateway.component.xml          \
      ${PROVIDERS}/sip-connectivity/sip-connectivity.component.xml  \
      ${PROVIDERS}/streaming-mps/streaming.component.xml            \
      ${PROVIDERS}/streaming-mps/mfw.component.xml                  \
      ${PROVIDERS}/streaming-mps/mps.component.xm                   \
   "
   
   #<GetNafo0Ip>
   if [ "$mynode" = "$primhost" ];
   then
     nafoupip="`cfgread nafo1 | awk '{ print $4 }'`" 
     expnafoupip="`fcfgread ${EXPORTDIR}/etc/hiq8000/node.cfg nafo1| awk '{ print $4 }'`"
   else
     nafoupip="`cfgread nafo1 | awk '{ print $5 }'`" 
     expnafoupip="`fcfgread ${EXPORTDIR}/etc/hiq8000/node.cfg nafo1| awk '{ print $5 }'`"
   fi
   #</GetNafo0Ip>

   for msidx in $XMLLIST
   do
      if [ -f $msidx ];
      then
         logstr "   - Importing data for `basename $msidx`."
         cat $msidx | sed -e s/"bond_udp_alias"/"$nafoupip"/g -e s/\"$expnafoupip\"/\"$nafoupip\"/g > ${msidx}.new
         cp -f ${msidx}.new ${msidx}
         rm -f ${msidx}.new
         for smidx in sipsm1_vip sipsm2_vip sipsm3_vip sipsm4_vip cstasm1_vip cstasm2_vip
         do
            srcip="`fcfgread ${EXPORTDIR}/etc/hiq8000/node.cfg ${smidx}`"
            destip="`cfgread ${smidx}`"
            if [ "$srcip" != "" -a "$destip" != "" ];
            then
               cat $msidx | sed  -e s/\"$srcip\"/\"$destip\"/g > ${msidx}.new
               cp -f ${msidx}.new ${msidx}
               rm -f ${msidx}.new
            fi
         done
      fi
   done
}


# ---------------------------------------------------------------
# function: customsecrules
# args    : None
# description:
#    imports custom security rules. detects predefined security
#    rules from all versions and removes them.
# ---------------------------------------------------------------

customsecrules( )
{
   logdebug "Function customsecrules called"
   textncolor $BoldCyan "Detecting custom packet filter rules."
   
   local srcsecfile=$1
   local targetsecfile=$2
   local secfile=$3
   
   lastsecidx="`cat $targetsecfile  | awk -F',' '{ print $1 }' | sed -e \"s/'//g\" -e 's/\.//g' | sort -n | tail -1`"
   lastsecidx=${lastsecidx:-1}
   lastsecidx=`expr $lastsecidx + 1`
   
   #<RulesFromTargets>
      rm -f /log/custom.rules
      rulesrc=/tmp/rules.src
      ruletarget=/tmp/rules.target
      ruleverify=/tmp/rules.verify
      ruleadd=/tmp/rules.add
      rulelog=/log/custom.rules

      # IPv6 dynamically added PFRs 
      local skip_src_ipv6_dyn_bill="System_ICMP_BILL_IPv6|System_SSH_BILL_IPv6|System_Local_Init_TCP_Bill_IPv6|System_Local_Init_UDP_Bill_IPv6|System_BILL_IPv6"
      local skip_src_ipv6_mgmt="System_ICMP_NODE_IPv6|System_SSH_Node_IPv6|System_Local_Init_TCP_Node_IPv6|System_Local_Init_UDP_Node_IPv6"

      local skip_src_ip6_sig="System_ENUM_DNS_IPv6|System_DUMMY_SIP_CONNECTION_V6_TCP_1|System_DUMMY_SIP_CONNECTION_V6_TCP_1_P2|\
System_DUMMY_SIP_CONNECTION_V6_TCP_2|System_DUMMY_SIP_CONNECTION_V6_TCP_2_P2|System_DUMMY_SIP_CONNECTION_V6_UDP_1|System_DUMMY_SIP_CONNECTION_V6_UDP_1_P2|\
System_DUMMY_SIP_CONNECTION_V6_UDP_2|System_DUMMY_SIP_CONNECTION_V6_UDP_2_P2|System_NCS_IPV6_UDP_1|System_NCS_IPV6_UDP_2|System_SIP_IPV6_MTLS_1|\
System_SIP_IPV6_MTLS_2|System_SIP_IPV6_MTLS_3|System_SIP_IPV6_MTLS_4|System_SIP_IPV6_TCP_1|System_SIP_IPV6_TCP_2|System_SIP_IPV6_TCP_3|\
System_SIP_IPV6_TCP_4|System_SIP_IPV6_TCP_Local_Init_1|System_SIP_IPV6_TCP_Local_Init_2|System_SIP_IPV6_TCP_Local_Init_3|System_SIP_IPV6_TCP_Local_Init_4|\
System_SIP_IPV6_TLS_1|System_SIP_IPV6_TLS_2|System_SIP_IPV6_TLS_3|System_SIP_IPV6_TLS_4|System_SIP_IPV6_UDP_1|System_SIP_IPV6_UDP_2|System_SIP_IPV6_UDP_3|\
System_SIP_IPV6_UDP_4"

      # Skip importing the IPv6 PFRs on migration, but let it for Upgrades.
      # For migration srcsecfile is the one coming from the source system and targetsecfile the one after the fresh image installation
      # For upgrades it is the opposite
      local skip_src_rules=""                                    
      if [ "$Migrate8k" = "true" ]
      then
         skip_src_rules="Misc_Host_|System_Misc_Host_|${skip_src_ipv6_dyn_bill}|${skip_src_ipv6_mgmt}|${skip_src_ip6_sig}"
      else
         skip_src_rules="Misc_Host_|System_Misc_Host_"
      fi 

      # Skip rules for DNS zone transfer endpoints coming from a previous OSEE V8 system
      if [ "X$(isOSEE)X" = "XtrueX" ]
      then
          skip_src_rules="${skip_src_rules}|System_DNS_Zone_Transfer"
      fi
      
      logdebug "Rules exported from source system (version < V9), before filter [${skip_src_rules}]: $(echo; cat $srcsecfile; wc -l $srcsecfile)"
      cat $srcsecfile    | awk -F ',' '{ print $2 }' | egrep -v "${skip_src_rules}" | sort | uniq > $rulesrc
      logdebug "Rules exported from source system (version < V9), after filter: $(echo; cat $rulesrc; wc -l $rulesrc)"
      
      cat $targetsecfile | awk -F ',' '{ print $2 }' | sort | uniq > $ruletarget
      logdebug "Rules exported from target system (version >= V9): $(echo; cat $ruletarget; wc -l $ruletarget)"
      
      #<ImportCstaPfr's>
         if osv_version.sh --major compare sys ge V4; 
         then
            cat /var/opt/image/allrules | grep -v CSTA > /tmp/allrules
         else
            cp -f /var/opt/image/allrules /tmp/allrules
         fi
      #<ImportCstaPfr's>

      #<V7SystemRules>
         if osv_version.sh --major compare sys ge V7; 
         then
             cat /tmp/allrules | sed -e "s/^'/'System_/g" > /tmp/allrules.system
             cat /tmp/allrules /tmp/allrules.system > /tmp/allrules.consolidate
             cp -f /tmp/allrules.consolidate /tmp/allrules
         fi
      #</V7SystemRules>
  
      #<IgnoreRemapCfg>
         if [ -f /etc/hiq8000/remaposv.cfg ];
         then
            cat /etc/hiq8000/remaposv.cfg | grep "^packetfilter:" > /tmp/pfrs.remap
            for pfridx in `cat /tmp/pfrs.remap`
            do
               remappfrname="`echo $pfridx  | awk -F ':' '{ print $2 }'`"
               remappfripact="`echo $pfridx | sed -n 's/^[a-z]*:[A-Za-z0-9_-]*:\[*[0-9a-fA-F.:\/]\+\]*:\[*[0-9a-fA-F.*\/:]\+\]*:\(.*\)$/\1/p'`"
               if [ "$remappfrname" != "" -a "$remappfripact" = "-" ];
               then
                  logstr "   - Dropping packet filter rule($remappfrname)."
                  echo "'$remappfrname'" >> /tmp/allrules
               fi
            done
         fi
      #</IgnoreRemapCfg>
      
      if [ "$Migrate8k" = "true" ];
      then
         cat $ruletarget /tmp/allrules | sort | uniq >  $ruleverify
         diff -Bw   $rulesrc $ruleverify  | grep "^<" | sed -e 's/<[\t ]*//g' > $ruleadd
      else
         diff -Bw   $rulesrc $ruletarget  | grep "^<" | sed -e 's/<[\t ]*//g' > $ruleadd
      fi
      
      seccount=0
      while read secname
      do
         grep -q "'${secname}'" $targetsecfile
         rulenamepresent=$?
         if [ "$secname" != "" ];
         then
            grep "$secname" $srcsecfile | head -1 | awk  -F',' '{                         \
                            printf idvar; for( awkidx=0x3; awkidx<=0xc; awkidx++ ) printf ","$awkidx; \
                              }' 1>/tmp/rule.next 2>/dev/null
            rulecondinsrc="`cat /tmp/rule.next 2>/dev/null`"
            if [ "$rulecondinsrc" != "" ];
            then
               rulecondintarget="`grep \"$rulecondinsrc\" $targetsecfile`"
            else
               rulecondintarget="."
            fi
         else
            rulecondintarget="."
         fi
         if [ $rulenamepresent -ne 0 -a "$rulecondintarget" = "" ];
         then
            #<HandleFlipFlops>
               flipflops="oam_ip_alias:bond_node_alias"
               breakfromme=false
               for idx in $flipflops 
               do
                  flipflopsname=`echo $flipflops | awk -F':' '{ print $1 }'`
                  flipflopsalternate=`echo $flipflops | awk -F':' '{ print $2 }'`
                  grep "$secname" $srcsecfile | head -1 | grep -q "'$flipflopsname'"
                  isaflipflop=$?
                  grep -q $flipflopsname /etc/hosts
                  isaknownflipflop=$?
                  if [ $isaflipflop -eq 0 -a $isaknownflipflop -ne 0 ];
                  then
                     flipflopstream="`grep "$secname" $srcsecfile | head -1 |                          \
                          awk  -F',' -v idvar="'$flipflopsalternate'" '{                               \
                             printf idvar; for( awkidx=0x4; awkidx<=0xd; awkidx++ ) printf ","$awkidx; \
                           }' 2>/dev/null`"
                     breakfromme=true
                     if [ $? -eq 0 ];
                     then
                        logstr "   - Removing known custom security rule $secname."
                     else
                        seccount=`expr $seccount + 1`
                        {
                           fmtseccount=`echo "$seccount" | awk '{ printf "      [%3d].,   ",$1 }'` 
                           echo -n "$fmtseccount $secname " 
                           grep "$secname" $srcsecfile | head -1 |                    \
                                sed -e "s/'$flipflopsname'/'$flipflopsalternate'/g" | \
                                awk -v idvar="\n                 " -F',' '{           \
                                   print idvar,$3,idvar,$5,idvar,$4                   \
                                }'
                        } >> $rulelog
                        grep "$secname" $srcsecfile | head -1 | sed -e "s/'$flipflopsname'/'$flipflopsalternate'/g" | \
                                                      sed s/[0-9][0-9.]*.,/$lastsecidx\.\',/1 >> $secfile
                        lastsecidx=`expr $lastsecidx + 1`
                     fi
                     break
                  fi
               done
               if [ "$breakfromme" = "true" ];
               then
                  continue
               fi
            #</HandleFlipFlops>
            logstr "   - Adding custom security rule $secname."
            if [ $seccount -eq 0 ];
            then
               {
                  echo "   ------------------------------------------------------"
                  echo "  |         Applied Security Rules                       |"  
                  echo "   ------------------------------------------------------"  
                  echo "  |   Index   |  RuleName ( localip,remoteip,remotefqdn) |"
                  echo "   ------------------------------------------------------"  
               } > $rulelog
            fi
            seccount=`expr $seccount + 1`
            {
               fmtseccount=`echo "$seccount" | awk '{ printf "      [%3d].,   ",$1 }'` 
               echo -n "$fmtseccount $secname " 
               grep "$secname" $srcsecfile | head -1 |          \
                    awk -v idvar="\n                 " -F',' '{ \
                       print idvar,$3,idvar,$5,idvar,$4         \
                    }'
            } >> $rulelog
            grep "$secname" $srcsecfile | head -1 | sed s/[0-9][0-9.]*.,/$lastsecidx\.\',/1 >> $secfile
            lastsecidx=`expr $lastsecidx + 1`
         fi
      done < $ruleadd
      if [ $seccount -ne 0 ];
      then
         echo "   --------------------------------------------------   "  >> $rulelog
      fi
      rm -f $rulesrc $ruletarget $ruleverify $ruleadd 
   #</RulesFromTargets>
   
   sync
}

# ----------------------------------------------------------------
# function: deletecstacustom
# args    : none
#   delete csta security rules that are custom if there exist a
#   security rule that is std.
# ----------------------------------------------------------------

deletecstacustom( )
{
   switchsolid ${mynode}
   count=1
   cstasql=/tmp/csta.sql
   currentrules=/tmp/DBA_PACKET_FILTERING_RULE_T.dat
   su - solid -c "cd  /tmp; $solexp 'tcp 16760' dba $(getDbaPassword) PACKET_FILTERING_RULE_T" 1>/dev/null 2>&1
   while ( true )
   do
      cstaserver="`cfgread csta_server${count}`"
      echo "CSTA: $cstaserver"
      if [ "$cstaserver" = "" ];
      then
         break;
      fi
      cat << EOF > ${cstasql}.prim
   delete from packet_filtering_rule_t                                        
   where (                                                                    
      LOCAL_IP_ADDR='csta_ip_alias_1' and LOCAL_PORT_BEGIN='1040' and         
      REMOTE_IP_ADDR='$cstaserver' and RULE_NAME!='CSTA_Server${count}_node1' and RULE_NAME!='CSTA_Server${count}_node2' 
   );
   commit work;
   exit;
EOF
      cat << EOF > ${cstasql}.sec
   delete from packet_filtering_rule_t 
   where (
      LOCAL_IP_ADDR='csta_ip_alias_2' and LOCAL_PORT_BEGIN=1040 and 
      REMOTE_IP_ADDR='$cstaserver' and RULE_NAME!='CSTA_Server${count}_node2' and RULE_NAME!='CSTA_Server${count}_node1'
   );
   commit work;
   exit;
EOF
      grep -q ",'CSTA_Server${count}_node1'" $currentrules 2>/dev/null
      if [ $? -eq 0 ];
      then
         su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) ${cstasql}.prim"  1>>$LOGFILE 2>&1
      fi
      grep -q ",'CSTA_Server${count}_node2'" $currentrules 2>/dev/null
      if [ $? -eq 0 ];
      then
         su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) ${cstasql}.sec"  1>>$LOGFILE 2>&1
      fi
      count="`expr $count + 1`"
   done
}

# ----------------------------------------------------------------
# function: reconfigureimm
# args    : none
# description:
#   reconfigures your remote admin card.
# ----------------------------------------------------------------

reconfigureimm( )
{
   echo "Configuring remote access interface ..."

   #<RemoveIpmiModules>
      if osv_version.sh --major compare sys lt V5; 
      then
         /etc/init.d/SMAWsf stop
      fi
   #</RemoveIpmiModules>

   #<GetLatestImm>
      if [ -f /unisphere/srx3000/callp/bin/rsaConfig ];
      then
         RsaRoot=/unisphere/srx3000/callp/bin
         rm -f /root/imm/rsaConfig
      else
         RsaRoot=/root/imm
      fi
   #</GetLatestImm>
 
   #<RestorePasswords>
      if [ -x ${RsaRoot}/rsaConfig ];
      then
         ${RsaRoot}/rsaConfig -v
      fi  
   #</RestorePasswords>
   

   #<RemoveIpmiModules>
      if osv_version.sh --major compare sys lt V5; 
      then
         /etc/init.d/SMAWsf start
      fi
   #</RemoveIpmiModules>

} 1>>$LOGFILE 2>&1

function backup_alf( )
{
   if [ ! -d ${LIC_BACKUP_DIR} ]
   then
      mkdir -p ${LIC_BACKUP_DIR}
   else
      rm -f ${LIC_BACKUP_DIR}/*
   fi
   cp -p ${EXPORTDIR}/unisphere/srx3000/callp/bin/*.alf ${LIC_BACKUP_DIR}
   cp -p /unisphere/srx3000/callp/bin/*.alf ${LIC_BACKUP_DIR}

   logstr "Copied a backup of alfs in ${LIC_BACKUP_DIR}"

}

# ---------------------------------------------------------------
# function: restorelicense
# args    : None
# description:
#   restores the license information.
# ---------------------------------------------------------------

restorelicense( )
{

   local PERFORM_ALF_UPGRADE=true
   #<AlfFileHanding>
       # In case of migration migrate8k or import8k consider that the license has been applied from image installation
       # so we do not process the update alf logic. Just keep what it is in the system 
       # Just copy current alf and exported alf in the backup dir
   
      if [ -f ${EXPORTDIR}/eth0Mac_permanent ]
      then
         oldpermmac=`cat  ${EXPORTDIR}/eth0Mac_permanent`
      else
         oldpermmac="" 
      fi
      newpermmac=`ethtool -P eth0 | awk '{print $3}' 2>/dev/null`


      if osv_version.sh --major compare sys ge V9 && [ "X$(isOSEE)X" = "XfalseX" ];
      then
         # Do not perform alf upgrade for migrations started with migrate8k
         if [ "$Migrate8k" = "true" ]
         then
            backup_alf
            PERFORM_ALF_UPGRADE=false
            logstr "Avoid alf upgrade , Migrate8k=${Migrate8k}"
         # Outage free upgrade -rsu upgrade or manaul import8k 
         elif [ ${upgrademode} != "OutageFree" ]
         then
            # manual import thriugh import8k
            if [ ! -f ${EXPORTDIR}/outage_upgrade_export ]
            then
               # if we are on the same host then we can upgrade alf
               # otherwise we should expect the licenses been installed during image installation
               if [ "$oldpermmac" != "$newpermmac" ]
               then
                  backup_alf
                  PERFORM_ALF_UPGRADE=false
                  logstr "Avoid alf upgrade, upgrademode=${upgrademode}, oldmac=${oldpermmac}, newmac=${newpermmac}"
               fi
             fi
          fi
      fi
       
      # Single load line alf file import
      # If we have not imported any new licenses from /repository/upload or we are in migrations then handle alf import
      if osv_version.sh --major compare sys ge V9 && [ "X$(isOSEE)X" = "XfalseX" -a ${licenses_found} -eq 0 -a "${PERFORM_ALF_UPGRADE}" = "true" ];
      then
         if [ -x /unisphere/srx3000/callp/bin/update_alf.sh ]
         then
           backup_alf

           # If we upgrade from an older major version (i.e. V9) the .alf should be retained
           ALFFILE=$(ls ${LIC_BACKUP_DIR}/*.alf 2>/dev/null | sort -V -r | head -n 2 | tail -n 1)
           if [ "X${ALFFILE}X" != "XX" ]
           then
              if /unisphere/srx3000/callp/bin/update_alf.sh ${ALFFILE}
              then
                 logstr "alf file ${ALFFILE} was restored successfully"
              fi
           else
              logstr "Could not find any alf file in ${LIC_BACKUP_DIR}"
           fi
         fi
       fi 
   #<\AlfFileHanding>

    #<RestoreLicense>
      if [ -f /sys/class/net/eth0/address -a -f ${EXPORTDIR}/eth0Mac ];
      then
         oldmac=`cat  ${EXPORTDIR}/eth0Mac`
         newmac=`cat /sys/class/net/eth0/address` 

         ENCLMSETTING="/enterprise/clm/ApacheTomcat/ClmSettings.xml"
         OPTCLMSETTING="/opt/licenses/clm/ApacheTomcat/ClmSettings.xml"

         # we have seen the mac addresss changing in SLES12 so also use perm addresses for comparing
         if [ "$oldmac" = "$newmac" -o "$oldpermmac" = "$newpermmac" ];
         then
            logstr "   - Restoring license data for valid eth0 MAC:$newmac."
            mkdir -p /repository/license
            cp ${EXPORTDIR}/opt/unisphere/srx3000/cla/license/rlf*.xml /opt/unisphere/srx3000/cla/import 2>/dev/null
            cp ${EXPORTDIR}/opt/unisphere/srx3000/cla/license/rlf*.xml /repository/license/. 2>/dev/null
            if [ -f /opt/unisphere/srx3000/cla/bin/get_ali ];
            then
               echo "ALI info( get_ali )"
               /opt/unisphere/srx3000/cla/bin/get_ali -p 
            fi 1>>$LOGFILE 2>&1
            if [ "$profile" = "integrated" -a "X$(isOSEE)X" = "XfalseX" ];
            then
               {
                  find -L ${EXPORTDIR}/enterprise/common/conf/license -name "*OpenScape*lic" ! -name "*OpenScape*Voice*lic" \
                              -exec cp -f {} /enterprise/common/conf/license 2>/dev/null \;
                  chown sym.sym /enterprise/common/conf/license/*OpenScape*lic
                  chmod a+r /enterprise/common/conf/license/*OpenScape*lic
               } 2>/dev/null
               if [ -f ${EXPORTDIR}/${OPTCLMSETTING} -a -f ${ENCLMSETTING} ];
               then
                  cp ${EXPORTDIR}/${OPTCLMSETTING} ${ENCLMSETTING} 
               fi
               if [ -f ${EXPORTDIR}/${ENCLMSETTING} -a -f ${OPTCLMSETTING} ];
               then
                  cp ${EXPORTDIR}/${ENCLMSETTING} ${OPTCLMSETTING} 
               fi
               if [ -f ${EXPORTDIR}/${OPTCLMSETTING} -a -f ${OPTCLMSETTING} ];
               then
                  cp ${EXPORTDIR}/${OPTCLMSETTING} ${OPTCLMSETTING} 
               fi
               if [ -f ${EXPORTDIR}/${ENCLMSETTING} -a -f ${ENCLMSETTING} ];
               then
                  cp ${EXPORTDIR}/${ENCLMSETTING} ${ENCLMSETTING} 
               fi
            fi
         else
            logstr "   - Skipping license data, as eth0 MAC's dont match($oldmac, $newmac)."
         fi
      else
         logstr "   - Skipping license data restore."
      fi
    #</RestoreLicense>

}

# ---------------------------------------------------------------
# function: mergesnmpV9
# args    : None
# merges snmpd from V7/V8 to V9 or from V9 to V9
# ---------------------------------------------------------------

mergesnmpV9( )
{
   # Define local variables

   local MERGE_TYPE=0						# 0 = from V7/V8 to V9, 1 = From V9 to V9
   local OLD_SNMPCFG=${EXPORTDIR}/etc/snmp/agt/snmpd.cnf
   local NEW_SNMPCFG=/etc/snmp/snmpd.conf

   if [ ! -f ${NEW_SNMPCFG} ];
   then
      logstr "   - New snmp configuration not found."
      return 1
   fi

   if [ ! -f ${OLD_SNMPCFG} ];
   then
      MERGE_TYPE=1
      OLD_SNMPCFG=${EXPORTDIR}/etc/snmp/snmpd.conf
      if [ ! -f ${OLD_SNMPCFG} ];
      then
         logstr "   - Old snmp configuration not found."
         return 1
      fi
   fi

   # Read important parameters and values from old snmp configuration file

   local syslocation="$(grep -i "^sysLocation" ${OLD_SNMPCFG} | head -1 | awk '{ print $2 }')"
   local syscontact="$(grep -i "^sysContact" ${OLD_SNMPCFG} | head -1 | awk -F'"' '{print $2}')"
   local sysname="$(grep -i "^sysName" ${OLD_SNMPCFG} | head -1 | awk '{ print $2 }')"

   if [ ${MERGE_TYPE} -eq 0 ];
   then
      local rocommunity="$(grep -i "^snmpCommunityEntry[ ]*t0000001" ${OLD_SNMPCFG} | head -1 | awk '{ print $3 }')"
      local rwcommunity="$(grep -i "^snmpCommunityEntry[ ]*t0000002" ${OLD_SNMPCFG} | head -1 | awk '{ print $3 }')"
      local rocommunity6="$(grep -i "^snmpCommunityEntry[ ]*t0000001" ${OLD_SNMPCFG} | head -1 | awk '{ print $3 }')"
      local rwcommunity6="$(grep -i "^snmpCommunityEntry[ ]*t0000002" ${OLD_SNMPCFG} | head -1 | awk '{ print $3 }')"
   else
      local rocommunity="$(grep -wi "^rocommunity" ${OLD_SNMPCFG} | head -1 | awk '{ print $2 }')"
      local rwcommunity="$(grep -wi "^rwcommunity" ${OLD_SNMPCFG} | head -1 | awk '{ print $2 }')"
      local rocommunity6="$(grep -wi "^rocommunity6" ${OLD_SNMPCFG} | head -1 | awk '{ print $2 }')"
      local rwcommunity6="$(grep -wi "^rwcommunity6" ${OLD_SNMPCFG} | head -1 | awk '{ print $2 }')"
   fi

   # IPv6 tags backwards compatibility with V7 and V8. If IPv6 tags empty then IPv4 tags values will be assigned.

   if [ "X${rocommunity6}X" == "XX" ];
   then
      sed '/^rocommunity/a rocommunity6' ${NEW_SNMPCFG}
      rocommunity6=${rocommunity} 
   fi

   if [ "X${rwcommunity6}X" == "XX" ];
   then
      sed '/^rwcommunity/a rwcommunity6' ${NEW_SNMPCFG}
      rwcommunity6=${rwcommunity} 
   fi

   # Replace specific parameters in V9 snmp configuration file with the above parameters

   sed -i "s/^syslocation.*/syslocation ${syslocation}/" ${NEW_SNMPCFG}
   sed -i "s/^sysname.*/sysname ${sysname}/" ${NEW_SNMPCFG}
   sed -i "s/^syscontact.*/syscontact ${syscontact}/" ${NEW_SNMPCFG}

   # Match only r[ow]community. Don't match the r[ow]community6
   sed -i "s/^rocommunity[[:blank:]].*/rocommunity ${rocommunity}/" ${NEW_SNMPCFG}
   sed -i "s/^rwcommunity[[:blank:]].*/rwcommunity ${rwcommunity} 127.0.0.1/" ${NEW_SNMPCFG}
      
   # Take the case we have a line starting with empty rocommunity and rwcommunity, without values
   sed -i "s/^rocommunity$/rocommunity ${rocommunity}/" ${NEW_SNMPCFG}
   sed -i "s/^rwcommunity$/rwcommunity ${rwcommunity} 127.0.0.1/" ${NEW_SNMPCFG}
   
   # match the rocommunity6 and rwcommunity6
   sed -i "s/^rocommunity6.*/rocommunity6 ${rocommunity6}/" ${NEW_SNMPCFG}
   sed -i "s/^rwcommunity6.*/rwcommunity6 ${rwcommunity6} ::1/" ${NEW_SNMPCFG}

   # Restarting snmp service

   systemctl restart snmpd 1>>$LOGFILE 2>&1
   logstr "   - snmp service has been restarted."

   return 0
}

# ---------------------------------------------------------------
# function: mergesnmp
# args    : None
# merges the community string from older versions.
# ---------------------------------------------------------------

mergesnmp( )
{
   SNMPDCNF=/etc/snmp/agt/snmpd.cnf
   cp -f $SNMPDCNF ${SNMPDCNF}.toolkit
   if [ -f $SNMPDCNF ];
   then
      expcomstrname="`cat ${EXPORTDIR}/${SNMPDCNF} 2>/dev/null   | \
                      egrep "^snmpCommunityEntry[ ]*t0000000 "   | \
                      head -1                                    | \
                      awk '{ print $3 }'`"
      comstrname="`cat ${EXPORTDIR}/${SNMPDCNF} 2>/dev/null      | \
                      egrep "^snmpCommunityEntry[ ]*t0000000 "   | \
                      head -1                                    | \
                      awk '{ print $3 }'`"

      if [ "$expcomstrname" = "" ];
      then
      expcomstrname="`cat ${EXPORTDIR}/${SNMPDCNF} 2>/dev/null   | \
                      egrep "^snmpCommunityEntry[ ]*t0000001 "   | \
                      head -1                                    | \
                      awk '{ print $3 }'`"
      fi
      if [ "$comstrname" = "" ];
      then
      comstrname="`cat ${SNMPDCNF} 2>/dev/null                   | \
                      egrep "^snmpCommunityEntry[ ]*t0000001 "   | \
                      head -1                                    | \
                      awk '{ print $3 }'`"
      fi
      if [ "$expcomstrname" = "" ];
      then
      expcomstrname="`cat ${EXPORTDIR}/${SNMPDCNF} 2>/dev/null   | \
                      egrep "^snmpCommunityEntry[ ]*t0000002 "   | \
                      head -1                                    | \
                      awk '{ print $3 }'`"
      fi
      rwcomstrname="`cat ${EXPORTDIR}/${SNMPDCNF} 2>/dev/null    | \
                      egrep \"^snmpCommunityEntry[ ]*t0000002 \" | \
                      head -1                                    | \
                      awk '{ print $3 }'`"
      if [ "$comstrname" = "" ];
      then
      comstrname="`cat ${SNMPDCNF} 2>/dev/null                   | \
                      egrep "^snmpCommunityEntry[ ]*t0000002 "   | \
                      head -1                                    | \
                      awk '{ print $3 }'`"
      fi

      if [ "$comstrname" != "" -a "$expcomstrname" != "" ];
      then
         logstr "   - Merging snmpd.cnf community strings."
         logstr "      Source SNMP info: $expcomstrname"
         logstr "      Target SNMP info: $comstrname"
         if [ "$rwcomstrname" != "" ];
         then
            cat $SNMPDCNF 2>/dev/null | sed -e "s/t0000000 [^ ]* /t0000000 $expcomstrname /" \
                                            -e "s/t0000001 [^ ]* /t0000001 $expcomstrname /" \
                                            -e "s/t0000002 [^ ]* /t0000002 $rwcomstrname /"  \
                                      > ${SNMPDCNF}.new
         else
            cat $SNMPDCNF 2>/dev/null | sed -e "s/t0000000[ ]*$comstrname/t0000000 $expcomstrname/" \
                                            -e "s/t0000001[ ]*$comstrname/t0000001 $expcomstrname/" \
                                            -e "s/t0000002[ ]*$comstrname/t0000002 $expcomstrname/" \
                                      > ${SNMPDCNF}.new
         fi
         cp ${SNMPDCNF}.new $SNMPDCNF
         #<AdditionalSNMPSettings>
            for anchoridx in 3 4 5 6 7 8 9
            do
               anchorprevidx=$[anchoridx-1]
               addcomstrlines=$(grep -w "t000000$anchoridx" "${EXPORTDIR}/${SNMPDCNF}")
               addcomstrlinestgt=$(grep -w "t000000$anchoridx" "${SNMPDCNF}")
               anchorline=$(grep "t000000$anchorprevidx" "$SNMPDCNF")
               if [ "$anchorline" != "" -a "$addcomstrlines" != "" -a "$addcomstrlinestgt" = "" ];
               then
                  logstr "   - Appending community string for t000000$anchoridx."
                  sed  -i "s/$anchorline/&\\n$addcomstrlines\\n/" $SNMPDCNF
               fi
            done
            syslocstr=$(grep "^sysLocation" "${EXPORTDIR}/${SNMPDCNF}")
            syscontactstr=$(grep "^sysContact" "${EXPORTDIR}/${SNMPDCNF}")
            sysnamestr=$(grep "^sysName" "${EXPORTDIR}/${SNMPDCNF}")
            sed  -i "s/^sysLocation.*/$syslocstr/" $SNMPDCNF
            sed  -i "s/^sysName.*/$sysnamestr/" $SNMPDCNF
            echo "$syscontactstr" | grep -qi siemens
            if [ $? -ne 0 ];
            then
               sed  -i "s/^sysContact.*/$syscontactstr/" $SNMPDCNF
            fi
         #</AdditionalSNMPSettings>
         rm -f ${SNMPDCNF}.new
         /etc/init.d/snmpdm restart 1>>$LOGFILE 2>&1
         sleep 2
         echo -n "   - Checking status of snmpd : "
         sysuptime="`snmpget -v 2c -c $expcomstrname -Otqev localhost system.sysUpTime.0 2>/dev/null`"
         if [ "$sysuptime" != "" ];
         then
            echo "up"
         else
            echo "not up"
            logstr "   - Restoring the origional snmp configuration."
            /etc/init.d/snmpdm stop
            sleep 2
            cp -f ${SNMPDCNF}.toolkit $SNMPDCNF 
            /etc/init.d/snmpdm restart 1>>$LOGFILE 2>&1
         fi
         
      fi
   fi
   rm -f ${SNMPDCNF}.toolkit
}

# ---------------------------------------------------------------
# function: buildnwmap
# args    : None
# description:
#   builds network information based on buildid & node.cfg.
# ---------------------------------------------------------------

buildnwmap( )
{
   cfgfile=$1
   cfgbuildid=$2

   cp $cfgfile ${cfgfile}.netcfg
   cfgfile=${cfgfile}.netcfg

   if osv_version.sh --major compare "$cfgbuildid" lt V5; 
   then
       for cfgidx in nafo0 nafo1 nafo2
       do
          cfgidxkey=$cfgidx
          cfgidxval=`fcfgread ${cfgfile} $cfgidx`
          if [ "$testbed" = "cluster" ];
          then
              cfgidxvalnwprim=`echo $cfgidxval | awk '{ print $4,"/",$6 }'`
              cfgidxvalnwsec=`echo $cfgidxval  | awk '{ print $5,"/",$9 }'`
              echo "<${cfgidxkey}nw>:${cfgidxvalnwprim},${cfgidxvalnwsec}"
          else
              cfgidxvalnwprim=`echo $cfgidxval | awk '{ print $4,"/",$6 }'`
              echo "<${cfgidxkey}nw>:${cfgidxvalnwprim}"
          fi
       done
       if [ "$testbed" = "cluster" ];
       then
          cfgcipprim=`fcfgread ${cfgfile} node_1_cip_logical`
          cfgcipprimnm=`fcfgread ${cfgfile} cip_netmask`
          cfgcipsec=`fcfgread ${cfgfile} node_2_cip_logical`
          cfgcipsecnm=`fcfgread ${cfgfile} cip2_netmask`
          echo "<nafo3nw>:${cfgcipprim}/${cfgcipprimnm},${cfgcipsec}/${cfgcipsecnm}"
       fi
   else
       for cfgidx in nafo0 nafo1 nafo2 nafo3
       do
          cfgidxkey=$cfgidx
          cfgidxval=`fcfgread ${cfgfile} $cfgidx`
          if [ "$cfgidxval" = "" ];
          then
             continue
          fi
          if [ "$testbed" = "cluster" ];
          then
              cfgidxvalnwprim=`echo $cfgidxval | awk '{ print $4,"/",$6 }'`
              cfgidxvalnwsec=`echo $cfgidxval  | awk '{ print $5,"/",$9 }'`
              echo "<${cfgidxkey}nw>:${cfgidxvalnwprim},${cfgidxvalnwsec}"
          else
              cfgidxvalnwprim=`echo $cfgidxval | awk '{ print $4,"/",$6 }'`
              echo "<${cfgidxkey}nw>:${cfgidxvalnwprim}"
          fi
       done
       rm -f ${cfgfile}
   fi | sed -e 's/[ \t]*//g' | sort > ${cfgfile}.nw
   rm -f ${cfgfile}
}


# ---------------------------------------------------------------
# function: calcocs
# args    : None
# description:
#   calculate Srx/Sip/Timer_OCS  parameter.
# ---------------------------------------------------------------

calcocs( )
{
   mapdes=$1
   valsrc=$2
   if [ "mapdes" != "" -a "$valsrc" != "" ];
   then
      valtimer="`egrep 'Srx/Sip/Timer_T1' $CUSTCONFHOME/SrxSip.parm | head -1 | awk -F'=' '{ print $2 }' | sed -e 's/ //g'`"
      valtimer=${valtimer:-"500"}
      case $valsrc in
         1)
            nvaltimer=`expr 2 \* $valtimer`
            ;;
         2)
            nvaltimer=`expr 4 \* $valtimer`
            ;;
         3)
            nvaltimer=`expr 8 \* $valtimer`
            ;;
         4)
            nvaltimer=`expr 16 \* $valtimer`
            ;;
         5)
            nvaltimer=`expr 32 \* $valtimer`
            ;;
         6)
            nvaltimer=`expr 64 \* $valtimer`
            ;;
         *)
            nvaltimer=`expr 8 \* $valtimer`
            ;;
      esac
      echo "$mapdes customer    integer = $nvaltimer" >> ${ZMODIFIED}
   fi
}

# ---------------------------------------------------------------
# function: calcpbs
# args    : None
# description:
#   calculate Srx/Sip/Timer_PBS  parameter.
# ---------------------------------------------------------------

calcpbs( )
{
   mapdes=$1
   valsrc=$2
   if [ "mapdes" != "" -a "$valsrc" != "" ];
   then
      valtimer="`egrep 'Srx/Sip/Timer_T1' $CUSTCONFHOME/SrxSip.parm | head -1 | awk -F'=' '{ print $2 }' | sed -e 's/ //g'`"
      valtimer=${valtimer:-"500"}
      case $valsrc in
         0)
            nvaltimer=`expr 1 \* $valtimer`
            ;;
         1)
            nvaltimer=`expr 3 \* $valtimer`
            ;;
         2)
            nvaltimer=`expr 7 \* $valtimer`
            ;;
         3)
            nvaltimer=`expr 15 \* $valtimer`
            ;;
         4)
            nvaltimer=`expr 31 \* $valtimer`
            ;;
         5)
            nvaltimer=`expr 63 \* $valtimer`
            ;;
         *)
            nvaltimer=`expr 15 \* $valtimer`
            ;;
      esac
      echo "$mapdes customer    integer = $nvaltimer" >> ${ZMODIFIED}
   fi
}

# ---------------------------------------------------------------
# function: mergertpparms
# args    : None
# description:
#   merges sys & customer rtp parms 
# ---------------------------------------------------------------

mergertpparms( )
{
   ZMODIFIED=/opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm
   CONFHOME=/opt/SMAW/SMAWrtp/conf
   CUSTCONFHOME=/opt/SMAW/SMAWrtp/cust_conf
   MergeList="                                                                               \
       Srx/SipReg/SRTPDeviceSupportList:/opt/SMAW/SMAWrtp/cust_conf/SrxSipRegistrar.parm     \
       Srx/SipReg/SRTPDeviceSupportListSDES:/opt/SMAW/SMAWrtp/cust_conf/SrxSipRegistrar.parm \
       Srx/SipReg/IceDeviceSupportList:/opt/SMAW/SMAWrtp/cust_conf/SrxSipRegistrar.parm      \
   "

   for mergeidx in $MergeList
   do
      mergeidxparm="`echo $mergeidx | awk -F ':' '{ print $1 }'`"
      mergeidxfile="`echo $mergeidx | awk -F ':' '{ print $2 }'`"
      grep -q "$mergeidxparm" $ZMODIFIED
      if [ $? -eq 0 ];
      then
         logstr "   - Merging ${mergeidxparm}."
         srcparmvalue="`grep \"$mergeidxparm\" $mergeidxfile | tail -1 | awk -F'=' '{ print $2 }' | sed -e 's/\"//g'`"         
         targetparmvalue="`grep \"$mergeidxparm\" $ZMODIFIED | tail -1 | awk -F'=' '{ print $2 }' | sed -e 's/\"//g'`"
         targetparmtype="`grep \"$mergeidxparm\" $ZMODIFIED  | tail -1 | awk -F'=' '{ print $1 }'`"
         echo $srcparmvalue,$targetparmvalue | sed -e 's/,/\n/g'                     \
                                             | sed -e 's/^[ ]*//g' -e 's/[ ]*$//g'   \
                                             | grep -v "^$" | sort | uniq > /tmp/csv.idx
         targetparmvalue=""
         for zidx in `cat /tmp/csv.idx`
         do
            if [ "$targetparmvalue" != "" ];
            then
               targetparmvalue="$targetparmvalue,$zidx"
            else
               targetparmvalue="$zidx"
            fi
         done
         cat $ZMODIFIED | grep -v "$mergeidxparm"  >  ${ZMODIFIED}.new 
         echo "$targetparmtype = $targetparmvalue" >> ${ZMODIFIED}.new
         cp ${ZMODIFIED}.new ${ZMODIFIED}
         rm -f ${ZMODIFIED}.new
      fi
   done

   #<CentralSbcSupport>
      if osv_version.sh compare "$expbuildid" lt V5 && osv_version.sh --major compare sys ge V5;
      then
         {
            cat $ZMODIFIED | grep -v "Srx/Sip/CentralSbcSupport" 
            echo "Srx/Sip/CentralSbcSupport customer boolean = RtpFalse" 
            echo "Srx/mgcp/SendFQDN  customer integer = 0" 
         } > ${ZMODIFIED}.new
         cp ${ZMODIFIED}.new ${ZMODIFIED}
         rm -f ${ZMODIFIED}.new
      fi
   #</CentralSbcSupport>

   #<TimerNAudit>
      if osv_version.sh compare "$expbuildid" lt V8 && osv_version.sh --major compare sys ge V8;
      then
         {
            cat $ZMODIFIED | grep -v "Srx/Xdm/SupportUnreachableState"
            echo "Srx/Xdm/SupportUnreachableState customer boolean = RtpFalse"
         } > ${ZMODIFIED}.new
         cp ${ZMODIFIED}.new ${ZMODIFIED}
         rm -f ${ZMODIFIED}.new
      fi
   #</TimerNAudit>

   #<BillingSupport>
      # Do this transformation only when source is V5 since billing node.cfg params have been deprecated since V6
      if osv_version.sh --major compare sys ge V6 && osv_version.sh compare "$expbuildid" lt V6;
      then
         for billingidx in "billing_client1:Srx/Usc/HostClient"        \
                           "billing_client2:Srx/Usc/HostClientBackup"  \
                           "billing_server1:Srx/Usc/Host"              \
                           "billing_server2:Srx/Usc/HostBackup"
         do
            billingnodecfg=`echo $billingidx | awk -F':' '{ print $1 }'`
            billingrtpscfg=`echo $billingidx | awk -F':' '{ print $2 }'`
            getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  $billingnodecfg expbillingid
            if [ "$expbillingid" != "" ];
            then
               grep -qw "$billingrtpscfg" $ZMODIFIED
               if [ $? -ne 0 ];
               then
                  logstr "   - RTP:$billingrtpscfg = $expbillingid"
                  echo "$billingrtpscfg customer string = $expbillingid" >> ${ZMODIFIED}
               fi
            fi
         done
      fi
   #</BillingSupport>

   #<StandAlonService>
      grep -qw "Srx/Main/StandAloneService" $ZMODIFIED
      if [ $? -ne 0 ];
      then
         expsasrv="`fcfgread ${EXPORTDIR}/etc/hiq8000/node.cfg stand_alone_service_permitted`"
         if [ "$expsasrv" != "" ];
         then
            if [ "$expsasrv" = "Yes" ];
            then
               echo "Srx/Main/StandAloneService customer boolean = RtpTrue"
            else
               echo "Srx/Main/StandAloneService customer boolean = RtpFalse"
            fi >> $ZMODIFIED
         fi
      fi
   #</StandAlonService>

   #<RtpDance>
      rtpdancelist=""
      if osv_version.sh --major compare sys ge V7; 
      then
         rtpdancelist="${rtpdancelist}                                                                                                    \
                       Srx/MobileClient/OSMOMutualAuth:Srx/Sip/AuthEnabled:$CUSTCONFHOME/SrxMobileClient.parm:$CUSTCONFHOME/SrxSip.parm:  \
                       " 
      fi
      if osv_version.sh --major compare sys ge V8; 
      then
         rtpdancelist="${rtpdancelist}                                                                                                                  \
                       Srx/Sip/Timer_OCS:Srx/Sip/InviteRetransmissions:$CUSTCONFHOME/SrxSip.parm:$CUSTCONFHOME/SrxSip.parm:calcocs                      \
                       Srx/Sip/Timer_PBS:Srx/Sip/ReroutingTimerInvite:$CUSTCONFHOME/SrxSip.parm:$CUSTCONFHOME/SrxSip.parm:calcpbs                       \
                       " 
      fi

      for danceidx in $rtpdancelist
      do
         ptfunc="`echo $danceidx | awk -F':' '{ print $5 }'`"
         filsrc="`echo $danceidx | awk -F':' '{ print $4 }'`"
         fildes="`echo $danceidx | awk -F':' '{ print $3 }'`"
         mapsrc="`echo $danceidx | awk -F':' '{ print $2 }'`"
         mapdes="`echo $danceidx | awk -F':' '{ print $1 }'`"
         valsrc="`egrep \"^$mapsrc\" ${EXPORTDIR}/${ZMODIFIED} | head -1 | awk -F'=' '{ print $2 }' | sed -e 's/ //g'`"
         rtpvalsrc="`egrep \"^$mapsrc\" ${EXPORTDIR}/${filsrc} 2>/dev/null | head -1 | awk -F'=' '{ print $2 }' | sed -e 's/ //g'`"

         # if source is V8 and later do not perform the param transformation for 
         # V8 obsolete params :  Srx/Sip/Timer_OCS , Srx/Sip/Timer_PBS Srx/Sip/SubscriberReroutingPAC.
         # The transformation should be performed only once from v7 - > v8.
         # Fix for OSV-2305.
         if osv_version.sh --major compare sys ge V8 && osv_version.sh compare "$expbuildid" ge V8 && [ "${mapsrc}" != "Srx/Sip/AuthEnabled" ];
         then
            logstr "source build is $expbuildid, current build is $buildid, will not calculate $mapdes"
            continue
         fi

         # if it was not modified then get the default value
         if [ "$valsrc" = "" ];
         then
            valsrc="${rtpvalsrc}"
         fi

         if [ "$valsrc" != "" ];
         then
            if [ "$ptfunc" = "" ];
            then
               egrep -q "^${mapdes}" $fildes 
               if [ $? -eq 0 ];
               then
                  egrep "^${mapdes}" $fildes | sed -e "s/=.*/= ${valsrc}/" >> ${ZMODIFIED}
               fi
            else
               $ptfunc "${mapdes}" "${valsrc}"
            fi
         fi
      done

      #################### OSV-5936 ####################
      # Changes in sipsm have been introduced with CQ00246661, in which:
      # If Srx/Sip/SubscriberReroutingPAC is empty, then ToolKit shall copy 
      # the value from Srx/Sip/InternationalReroutingPAC into Srx/Sip/SubscriberReroutingPAC 
      # before removing the Srx/Sip/InternationalReroutingPAC parameter.

      if osv_version.sh --major compare sys ge V8 && osv_version.sh compare "$expbuildid" lt V8;
      then
         mapsrc="Srx/Sip/InternationalReroutingPAC"
         valsrc="`egrep \"^${mapsrc}\" ${EXPORTDIR}/${ZMODIFIED} | head -1 | awk -F'=' '{ print $2 }' | sed -e 's/ //g'`"
         mapdes="Srx/Sip/SubscriberReroutingPAC"
         valdes="`egrep \"^${mapdes}\" ${EXPORTDIR}/${ZMODIFIED} | head -1 | awk -F'=' '{ print $2 }' | sed -e 's/ //g'`"

         if [ "X${valdes}X" = "XX" -a "X${valsrc}X" != "XX" ];
         then
            echo "${mapdes} customer    string = ${valsrc}" >> ${ZMODIFIED}
	    logstr "SubscriberReroutingPAC value was changed with InternationalReroutingPAC value."
         fi
      fi
      #################################################

   #</RtpDance>

   #<BlackHole>
   logdebug "RTP parameters preservation starts..."
   # Whenever you need to preserve the value of a parameter in upgrades, you can simply put
   # its parameter file and name in this list: filename:paramater

   # List of tickets concerning this logic:
   # OSV-2455: Preserve CDR delivery method to FTP or SFTP

      bhlist="                                                                              \
         /opt/SMAW/SMAWrtp/cust_conf/SrxMain.parm:Srx/Main/OutGoingCallingPartyNumberType   \
         /opt/SMAW/SMAWrtp/cust_conf/SrxMain.parm:Srx/Main/MwiNatureOfAddress               \
         /opt/SMAW/SMAWrtp/cust_conf/SrxMain.parm:Srx/Main/MwiEnablePrivateNumberingPlan    \
         /opt/SMAW/SMAWrtp/cust_conf/SrxSip.parm:Srx/Sip/Session_Timer                      \
         /opt/SMAW/SMAWrtp/cust_conf/SrxSip.parm:Srx/Sip/EnforceDNSResolutionOnRegistration \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/HTTPSoapListenerPort             \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/HTTPSoapSenderPort               \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/TelefonicaEBG                    \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/TelefonicaEID                    \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/TelefonicaPASCODE                \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/TelefonicaNPIDName               \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/TelefonicaBGName                 \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/TelefonicaAppID                  \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/TelefonicaOutsideAccess          \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/HeartbeatTimer                   \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/HeartbeatWatchDogTimer           \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/HeartbeatRetry                   \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/DelayAtRouteRequestedState       \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/ReRouteLoopCount                 \
         /opt/SMAW/SMAWrtp/cust_conf/hiQCSTA.parm:hiQ/CSTA/TelefonicaEBGMtuSize             \
         /opt/SMAW/SMAWrtp/cust_conf/SrxRss.parm:Srx/Rss/UniqueExtensions                   \
         /opt/SMAW/SMAWrtp/cust_conf/SrxXla.parm:Srx/Xla/ConvertIntoGnf                     \
         /opt/SMAW/SMAWrtp/cust_conf/SrxXdm.parm:Srx/Xdm/Registrar/EnableMultiPrimary       \
         /opt/SMAW/SMAWrtp/cust_conf/SrxUsc.parm:Srx/Usc/SftpEnable                         \
      "
      for idx in $bhlist
      do
         bhparmfile=`echo $idx|awk -F':' '{ print $1 }'`
         bhparm=`echo $idx|awk -F':' '{ print $2 }'`
         if [ -f  ${EXPORTDIR}/${bhparmfile} ];
         then
            logdebug "RTP parameter"
            egrep -qw "^$bhparm" ${EXPORTDIR}/${bhparmfile}
            if [ $? -eq 0 ];
            then
               egrep -qw "^$bhparm" ${ZMODIFIED}
               if [ $? -ne 0 ];
               then
                  egrep -qw "^$bhparm" ${bhparmfile}
                  if [ $? -eq 0 ];
                  then
                     logstr "   - Preserving $bhparm"
                     egrep -w "^$bhparm" ${EXPORTDIR}/${bhparmfile} >> ${ZMODIFIED}
                  fi
               fi
            fi
         else
             logstr "Warning: Asked to preserve this RTP param [${bhparm}] but the file [${bhparmfile}] is not saved in export directory [${EXPORTDIR}]"
         fi
      done

      logdebug "RTP parameters preservation ended. Preserved list in [${ZMODIFIED}]: $(echo; cat ${ZMODIFIED})"
   #</BlackHole>

   #<IgnoreList>
      IgnoreList="\
         SipAddress/1/Failover           \
         SipAddress/2/Failover           \
         SipServerAddress/1/Failover     \
         SipServerAddress/2/Failover     \
         NcsAddress/1/Failover           \
         NcsAddress/2/Failover           \
         CstaAddress/1/Failover          \
         CstaAddress/2/Failover          \
         LsmAddress/1/Failover           \
         LsmAddress/2/Failover           \
         AdminBaseAddress/1/Failover     \
         AdminBaseAddress/2/Failover     \
         SignalingBaseAddress/1/Failover \
         SignalingBaseAddress/2/Failover \
         BillingBaseAddress/1/Failover   \
         BillingBaseAddress/2/Failover   \
         SbcAddress/1/Failover           \
         SbcAddress/2/Failover           \
         Srx/PrttReader/ReadFromDriver   \
      "

      #<IgnoreRemapCfg>
         if [ -f /etc/hiq8000/remaposv.cfg ];
         then
            cat /etc/hiq8000/remaposv.cfg | grep "^cdrhost:" > /tmp/cdrhost.remap
            for cdridx in `cat /tmp/cdrhost.remap`
            do
               remappfrname="`echo $cdridx  | awk -F ':' '{ print $2 }'`"
               remappfripact="`echo $cdridx | awk -F ':' '{ print $5 }'`"
               if [ "$remappfrname" != "" -a "$remappfripact" = "-" ];
               then
                  logstr "   - Dropping parm($remappfrname)."
                  IgnoreList="${IgnoreList} ${remappfrname}"
               fi
            done
         fi
      #</IgnoreRemapCfg>

      igncmd=""
      igncnt=0
      for ignidx in $IgnoreList
      do 
         if [ $igncnt -eq 0 ];
         then
            igncmd="${igncmd}^$ignidx[ \t]"
         else
            igncmd="${igncmd}|^$ignidx[ \t]"
         fi
         igncnt=`expr $igncnt + 1`
      done

      cat $ZMODIFIED | egrep -v "$igncmd" > ${ZMODIFIED}.new
      cp ${ZMODIFIED}.new ${ZMODIFIED}
      rm -f ${ZMODIFIED}.new

   #</IgnoreList>

   #<ObsoleteList>
      ObsoleteList="                                                       \
         Srx/Main/hiQVariant                                               \
         Srx/Main/SS7Variant                                               \
         Srx/Main/CustomerType                                             \
         Srx/Main/Company                                                  \
         Srx/Main/SoftSwitchType                                           \
         Srx/Main/allowPrefixToEP                                          \
         Srx/Main/BlockQueriesForPrivateNumbers                            \
         Srx/Main/CaleaUseIncomingCallerId                                 \
         Srx/Main/CallingPartyDisplayPrependPrefix                         \
         Srx/Main/ClgPtyDisplayPrependPNAC                                 \
         Srx/Main/DoCNAMonAllENUM                                          \
         Srx/Main/ForwardingForceClgPtyDispPrefix                          \
         Srx/Main/OffNetINtlPrefexDigits                                   \
         Srx/Main/OffNetNtlPrefexDigits                                    \
         Srx/Main/OutGoingCallingPartyNumberType                           \
         Srx/Main/OverrideFRN859IntraBgDisplayWithExt                      \
         Srx/Main/SRSSetDiversionHeader                                    \
         Srx/Main/SrxCallingNameDeliveryMethod                             \
         Srx/Main/SrxLocalCallingNameDelivery                              \
         Srx/Main/SrxTcapCallingNameDelivery                               \
         Srx/Main/SvcAssignedPerOfficeCNAB                                 \
         Srx/Main/SvcAssignedPerOfficeCNDB                                 \
         Srx/Main/SvcAssignedPerOfficeUSCOLP                               \
         Srx/Main/SvcAssignedPerOfficeUSCOLR                               \
         Srx/Main/updateDisplayNonIntraBGCall                              \
         Srx/Main/updateDisplayNonIntraBGCallEPtoEP                        \
         Srx/Main/useExternCallerIDForExternDns                            \
         Srx/Main/UseNameCharactersInIAM                                   \
         Srx/Sip/cisco_guid_trans                                          \
         Srx/Sip/Country_Code                                              \
         Srx/Sip/EnableProxyRegistration                                   \
         Srx/Sip/IntlE164Numbers                                           \
         Srx/Sip/max_backgroundQ_threshold                                 \
         Srx/Sip/max_number_of_sessions                                    \
         Srx/Sip/max_parseQ_threshold                                      \
         Srx/Sip/PAI_AuthEnabled                                           \
         Srx/Sip/ProxyBypassEnabled                                        \
         Srx/Sip/ReroutingEndpointEnabled                                  \
         Srx/Sip/SDPProtocol                                               \
         Srx/Sip/SIPSTUNKeepAlive                                          \
         Srx/Sip/UdpPort                                                   \
         Srx/Sip/usePAIforCallingParty                                     \
         Srx/Sip/useAnonymousFrom                                          \
         Srx/IpPacketPriority/DSCPTOS/DQoS/Type                            \
         Srx/IpPacketPriority/DSCPTOS/DQoS/Value                           \
         Srx/IpPacketPriority/DSCPTOS/MGCP/Type                            \
         Srx/IpPacketPriority/DSCPTOS/MGCP/Value                           \
         Srx/IpPacketPriority/DSCPTOS/TGCP/Type                            \
         Srx/IpPacketPriority/DSCPTOS/TGCP/Value                           \
         Srx/IpPacketPriority/DSCPTOS/MEGACO/Type                          \
         Srx/IpPacketPriority/DSCPTOS/MEGACO/Value                         \
         Srx/Main/ACCTypeInterRejCall                                      \
         Srx/Main/ATTSendCdr (SBRK)                                        \
         Srx/Main/ATTSendStartCdr (SBRK)                                   \
         Srx/Main/BigcfHostSearchMethod                                    \
         Srx/Main/BigcfProxyCallIndicator                                  \
         Srx/Main/BigcfSupportedHostDomains                                \
         Srx/Main/FailureTreatmentOptionLINR                               \
         Srx/Main/HLSBlockEmergency                                        \
         Srx/Main/NumberOfAttemptsForContCdLINR                            \
         Srx/Main/NumberPlaybackOptLINR                                    \
         Srx/Main/OCBActivateDigitMap                                      \
         Srx/Main/OCBCheckCACMethod                                        \
         Srx/Main/OCBDeactOverDigitMap                                     \
         Srx/Main/RedialContinuationCodeLINR                               \
         Srx/Main/WLSBlockEmergency                                        \
         Srx/Main/WLSCfmTreat                                              \
         Srx/Main/SvcAssignedPerOfficeCCW                                  \
         Srx/Rss/maxBarringLevelTblSize                                    \
         Srx/Rss/maxBarringListTblSize                                     \
         Srx/Rss/maxQOSSvcTblSize                                          \
         Srx/Rss/maxRetailerIndexTblSize                                   \
         Srx/Rss/maxRetailerSvcTblSize                                     \
         Srx/Rss/maxTeenLineTblSize                                        \
         Srx/Service/ACAR/AnnouncementResponseTimer                        \
         Srx/Service/ACAR/ARActivationProcedure                            \
         Srx/Service/ACAR/PerSPCSBlkARMsgWICNInfo                          \
         Srx/Service/ACAR/MaxNum6SecondSpecialRingingCycles                \
         Srx/Service/ACAR/InvalidDialedDigitCounter                        \
         Srx/Service/ACAR/AnnouncementResponseTimeoutCounter               \
         Srx/Service/ACAR/DenyARtoNonUniqueDN                              \
         Srx/Service/ACAR/DenyARActivationsToAnonymousDN                   \
         Srx/Service/ACAR/DNVoiceBackOption                                \
         Srx/Service/ACAR/ARFeatureAssignedPerOffice                       \
         Srx/Service/ACAR/ACFeatureAssignedPerOffice                       \
         Srx/Service/ACAR/ResumeScanningTimer                              \
         Srx/Service/ACAR/InitialQueryResponseTimer                        \
         Srx/Service/ACAR/MonitoringTimer                                  \
         Srx/Service/ACAR/SubsequentQueryResponseTimer                     \
         Srx/Service/ACAR/OriginatingOverallMonitoringTimer                \
         Srx/Service/ACAR/ResumeScanningThresholdTimer                     \
         Srx/Service/ACAR/OriginatingScanRateTimer                         \
         Srx/Service/ACAR/TerminatingScanningMonitoringTimer               \
         Srx/Service/ACAR/OutstandingNotificationTimer                     \
         Srx/Service/ACAR/TerminatingOverallMonitoringTimer                \
         Srx/Service/ACAR/InterBusyIdleQueryDurationTimer                  \
         Srx/Service/ACAR/PeriodicScanRate                                 \
         Srx/Service/ACAR/RequestTerminatingScanningAllowed                \
         Srx/Service/ACAR/MaxNumConcurrentARActivationsAllowedPerCustomer  \
         Srx/Service/ACAR/MaxNumConcurrentACActivationsAllowedPerCustomer  \
         Srx/Service/ACAR/MaxNumQueueEntriesAllowedPerCalledParty          \
         Srx/Service/ACAR/MaxNumUnansweredSpecialRingingApplications       \
         Srx/Service/ACAR/CacTimerforReleaseB                              \
         Srx/Service/ACAR/HandleAsEmergencyCall                            \
         Srx/Service/CALEA/IPUnityEsPortReady                              \
         Srx/Service/CALEA/LIOSMode                                        \
         Srx/Service/CCS/CCBSActivationDialThrough                         \
         Srx/Service/CCS/CCBSActivationDialThroughDigit                    \
         Srx/Service/CCS/CCBSActivationHookFlash                           \
         Srx/Service/CCS/CcbsScanRateT10                                   \
         Srx/Service/CCS/CcnrScanRateT10                                   \
         Srx/Service/CCS/RetentionTimer                                    \
         Srx/Service/CWT/CWTActConfirmOpt                                  \
         Srx/Service/CWT/CWTDeactConfirmOpt                                \
         Srx/Service/CWT/HoldActiveDig                                     \
         Srx/Service/CWT/RejectIncDig                                      \
         Srx/Service/CWT/ReleaseActiveDig                                  \
         Srx/Service/CWT/SrxCallWaitingTimer                               \
         Srx/Subp/AllowTeenParentLnpUpdate                                 \
         Srx/Subp/MaxNrTeenPerParent                                       \
         Srx/Sip/SipRbtFlag                                                \
      "

      if osv_version.sh --major compare sys ge V8; 
      then
      ObsoleteList="                                   \
          $ObsoleteList                                \
          Srx/Sip/SMMode                               \
          Srx/Sip/Incoming_Registration_Check          \
          Srx/Sip/Profile_check_based_on_sub           \
          Srx/Sip/Profile_check_based_on_via           \
          Srx/Sip/Min_Expires_Presence                 \
          Srx/Sip/InternationalReroutingPAC            \
          Srx/Sip/NationalReroutingPAC                 \
          Srx/Sip/LocalReroutingPAC                    \
          Srx/Sip/AuthClientQopHeader                  \
          Srx/Sip/AuthGenerateNextNonce                \
          Srx/Sip/MaxSession                           \
          Srx/Sip/TransitMIME                          \
          Srx/Sip/event_header_trans                   \
          Srx/Sip/expires_header_trans                 \
          Srx/Sip/default_number_of_sessions           \
          Srx/Sip/init_context_free_list               \
          Srx/Sip/CpuSuppressOrigNotify                \
          Srx/Sip/sip_sbc_inside_ip                    \
          Srx/Sip/sip_sbc_customer_fqdn                \
          Srx/Sip/SIPOutbound                          \
          Srx/Sip/OptionsQuickReplyEnable              \
          Srx/Sip/MobileDeviceListMax                  \
          Srx/Sip/NetRelTimer                          \
          Srx/Sip/header_filter                        \
          Srx/Sip/p_preferred_identity_trans           \
          Srx/Sip/allow_trans                          \
          Srx/Sip/supported_trans                      \
          Srx/Sip/require_trans                        \
          Srx/Sip/header_filter                        \
          Srx/Sip/fork_on_failover                     \
          Srx/Sip/AllowBypassXla                       \
          Srx/Sip/InviteRetransmissions                \
          Srx/Sip/ReroutingTimerInvite                 \
           
      "
      fi

      if osv_version.sh --major compare sys ge V7; 
      then
      ObsoleteList="                                   \
          $ObsoleteList                                \
          Srx/Main/LongCallTimer                       \
          Srx/Sip/LongCall_disconnect_enabled          \
      "
      fi

      if osv_version.sh --major compare sys ge V6; 
      then
      ObsoleteList="                                   \
          $ObsoleteList                                \
          Srx/Xdm/EnableRegistrationRenewal            \
      "
      fi

      obscmd=""
      obscnt=0
      for obsidx in $ObsoleteList
      do 
         if [ $obscnt -eq 0 ];
         then
            obscmd="${obscmd}^$obsidx[ \t]"
         else
            obscmd="${obscmd}|^$obsidx[ \t]"
         fi
         obscnt=`expr $obscnt + 1`
      done

      if osv_version.sh --major compare sys ge V5;
      then
         cat $ZMODIFIED | egrep -v "$obscmd" > ${ZMODIFIED}.new
         cp ${ZMODIFIED}.new ${ZMODIFIED}
         rm -f ${ZMODIFIED}.new
      fi
   #</ObsoleteList>

   #<CMPAccess>
   if [ "$Migrate8k" = "true" ];
   then
       superuserip="`cfgread superuserip`"
       if [ "$superuserip" != "" ];
       then
          cat $ZMODIFIED | egrep -v "^Srx/Subp/SuperUserIpAddress|^Srx/Main/StandAloneService" > ${ZMODIFIED}.new
          cp ${ZMODIFIED}.new ${ZMODIFIED}
          rm -f ${ZMODIFIED}.new
       fi
   fi
   #</CMPAccess>

   #<EmergencyMode>
      grep -qw "Srx/Service/CFLoopPrevention customer boolean = RtpFalse" $ZMODIFIED

      if [ $? -ne 0 ];
      then
         expsasrv="`fcfgread /etc/hiq8000/node.cfg osv_emergency_mode`"

         if [ "$expsasrv" != "" ];
         then
            if [ "$expsasrv" = "ESRP-US" ] || [ "$expsasrv" = "ESRP-EU" ];
            then
               {
                  cat $ZMODIFIED | grep -v "Srx/Service/CFLoopPrevention"
                  echo "Srx/Service/CFLoopPrevention customer boolean = RtpFalse"
               } > ${ZMODIFIED}.new
               cp ${ZMODIFIED}.new ${ZMODIFIED}
               rm -f ${ZMODIFIED}.new
            fi
         fi
      fi
   #</EmergencyMode>

   #<RemoveSSLWeakCiphers>
      SSL_DEFAULTS='/opt/SMAW/SMAWrtp/cust_conf/SrxSSL.parm'

      is_jitc=$(fcfgread /etc/hiq8000/node.cfg dod_enabled)

      SSLCipherCaseList="\
         SSL\/MutualAuth\/Client\/SupportedCiphers     \
         SSL\/MutualAuth\/Server\/SupportedCiphers     \
         SSL\/CSTAMutualAuth\/Server\/SupportedCiphers \
         SSL\/EndPoint\/Server\/SupportedCiphers       \
         SSL\/Soap\/Server\/SupportedCiphers           \
      "

      if [ "${is_jitc}" = "Yes" ]
      then
         for ssl_case in $SSLCipherCaseList
         do
            ssl_custom_ciphers=$(grep -w ${ssl_case} $ZMODIFIED)
            if [ "${ssl_custom_ciphers}" = "" ];
            then
               ssl_source=$(grep -w ${ssl_case} ${SSL_DEFAULTS})
               secure_ciphers=$(echo "${ssl_source}" | sed -e 's/kRSA+FIPS:\+//g' -e 's/:\+kRSA+FIPS//g')
               echo "${secure_ciphers}" >> $ZMODIFIED
            else
               sed -i -e "/^${ssl_case}/ s/kRSA+FIPS:\+//g" -e "/^${ssl_case}/ s/:\+kRSA+FIPS//g" $ZMODIFIED
            fi
         done
      fi
   #</RemoveSSLWeakCiphers>
}

# ---------------------------------------------------------------
# function: migrate_config
# args    : None
# description: arg1 : config file
#   performs the migration of config files.
# ---------------------------------------------------------------
function migrate_config()
{
   config_file=$1
   # HiqAlarmFilters needs normalized IPs so we need to apply the normalized sed expressions
   if [ "${config_file}" = "/opt/SMAW/SMAWrtp/cust_conf/HiqAlarmFilters.tcn" ]
   then
      exec_pattern=${execcmd_norm}
      aux_pattern=${auxcmd_norm}
                  
      rm -rf /tmp/HiqAlarmFilters.tcn.norm
      # normalize HiqAlarmFilters
      while read line
      do
         if [ "$line" != "" ]
         then
            echo $line | egrep -q '^#|^[ \t]*$|^TABLE'
            if [ $? -eq 0 ]
            then
               echo "$line" >> /tmp/HiqAlarmFilters.tcn.norm
            else
               IP=$(echo $line | awk -F"::" '{print $1}')
               IP_NORM=$(getNormalizeIP ${IP})
               NORM_LINE=$(echo ${line} | sed -e "s|\\<${IP}\\>|${IP_NORM}|g")
               echo "$NORM_LINE" >> /tmp/HiqAlarmFilters.tcn.norm
            fi
         fi
      done < ${EXPORTDIR}/${config_file}

      cp -p ${EXPORTDIR}/opt/SMAW/SMAWrtp/cust_conf/HiqAlarmFilters.tcn{,.orig}        
      cat /tmp/HiqAlarmFilters.tcn.norm > ${EXPORTDIR}/opt/SMAW/SMAWrtp/cust_conf/HiqAlarmFilters.tcn
                 
   else
      exec_pattern=${execcmd}
      aux_pattern=${auxcmd}
   fi
   
   if [ "X${exec_pattern}X" != "XX" ]
   then
      # First pass with the exec pattern
      logstr "${config_file} - ${exec_pattern}" 
      cat ${EXPORTDIR}/${config_file} | ${exec_pattern} > ${config_file}.migrate
      ret=$?
      if [ $ret -ne 0 ]
      then
         rm -rf ${config_file}.migrate
         textncolor $BoldRed "[${_SELF_}]: Failed to migrate."
         exit $NOTIMPORTABLE 
      fi
      cp -f ${config_file}.migrate ${config_file}
      rm -rf ${config_file}.migrate
   fi
           
   if [ "X${aux_pattern}X" != "XX" ]
   then
      # Second pass with aux_pattern and eval
      # We use eval since bash adds some '' in variable assigment for variable like "'/XXX[ \t]'"
      
      sed_cmd="cat ${config_file} | sed ${aux_pattern} > ${config_file}.migrate"

      logstr "executing ${sed_cmd}"
      eval ${sed_cmd}
      ret=$?
            
      if [ ${ret} -eq 0 ];
      then
         cp -f ${config_file}.migrate ${config_file}
         rm -f ${config_file}.migrate
      else
         textncolor $BoldRed "[${_SELF_}]: Failed to migrate."
         exit $NOTIMPORTABLE      
      fi
   fi
}

# ---------------------------------------------------------------
# function: restorebkup
# args    : None
# description:
#   restore files in restorelist.
# ---------------------------------------------------------------

restorebkup( )
{
    local sed_cmd=""
    local exec_pattern
    local aux_pattern
    local ret
    logstr "function: restorebkup is called"
    for idx in $restorelist
    do
         passiveidx="`echo $idx | cut -d':' -f1`"
         activeidx="`echo $idx | cut -d':' -f2`"
         nonimgidx="`echo $idx | cut -d':' -f3`"
         diridx="`echo $idx | cut -d':' -f4`"
         logstr "restorebkup: passiv = $passiveidx - active = $activeidx - nonimg = $nonimgidx - dir = $diridx .... IMPORT = $SYSIMPORT"
         if [ "$SYSIMPORT" != "true" ];
         then
            if [ "$Migrate8k" = "true" ];
            then
               basediridx="`basename $diridx`"
               if [ "$IMPORTHOSTS" = "false" -o "X$(isOSEE)X" = "XtrueX" ];
               then
                  if [ "$basediridx" = "resolv.conf" -o   \
                       "$basediridx" = "ntp.conf"    -o   \
                       "$basediridx" = "ntp.conf.cluster" ];
                  then
                     logstr "restorebkup: $IMPORTHOSTS importhosts"
                     continue;
                  fi
               fi

               if [ ! -f ${EXPORTDIR}/${nonimgidx}/${diridx} ];
               then
                  logstr "restorebkup: ${EXPORTDIR}/${nonimgidx}/${diridx} -- Something went wrong"
                  continue;
               fi
               
               migrate_config "${nonimgidx}${diridx}"
               
            else # Non migrate8k non SYSIMPORT

               if [ ! -f ${passiveidx}/${diridx} ];
               then
                  logstr "restorebkup: ${passiveidx}/${diridx} -- Something went wrong"
                  continue;
               fi
               cat ${passiveidx}/${diridx} | $execcmd $auxcmd > ${activeidx}/${diridx}.migrate
               if [ $? -eq 0 ];
               then
                  cp -f ${nonimgidx}/${diridx}.migrate ${nonimgidx}/${diridx}
                  rm -f ${nonimgidx}/${diridx}.migrate
                  logstr "restorebkup: cp -f ${nonimgidx}/${diridx}.migrate ${nonimgidx}/${diridx} -- rm -f ${nonimgidx}/${diridx}.migrate"
               else
                  textncolor $BoldRed "[${_SELF_}]: Failed to migrate."
                  exit $NOTIMPORTABLE      
               fi
            fi
            
            if osv_version.sh --major compare sys ge V9 && [ "${diridx}" = "/etc/rsyslog.d/0_osv_forward.conf" ];
            then
               RESTART_SYSLOG=true
            fi
            
         else # SYSIMPORT
            if [ ! -f ${EXPORTDIR}/${nonimgidx}/${diridx} ];
            then
               logstr "restorebkup: if ${EXPORTDIR}/${nonimgidx}/${diridx} file doesn't exist "
               continue
            fi
            logstr "restorebkup: cp -f ${EXPORTDIR}/${nonimgidx}/${diridx} ${nonimgidx}/${diridx}"
            cp -f ${EXPORTDIR}/${nonimgidx}/${diridx} ${nonimgidx}/${diridx}
            if [ "$diridx" = "/lib/net-snmp/snmpd.conf" ]
            then
               date >>  $LOGFILE
               logstr "restorebkup 6133 : Check for differences"
               diff ${EXPORTDIR}/${nonimgidx}/${diridx} ${nonimgidx}/${diridx} >> $LOGFILE
            fi
            if osv_version.sh --major compare sys ge V9 && [ -f ${EXPORTDIR}/${nonimgidx}/${diridx} -a "${diridx}" = "/etc/rsyslog.d/0_osv_forward.conf" ];
            then
               RESTART_SYSLOG=true
            fi
 
         fi 
    done 

   isSNMPv3Lost "restorebkup" "after restorelist line:6157"

    #<V7RTPAlarms>
    if osv_version.sh --major compare sys ge V7;
    then
   
       alarmidx="/opt/SMAW/SMAWrtp/cust_conf/HiqAlarmFilters.tcn"
      
       if [ -f "$alarmidx" ]; 
       then
          cat $alarmidx | egrep "^#|^[ \t]*$|^TABLE" > ${alarmidx}.comments
          if osv_version.sh --major compare "$expbuildid" lt V7 && [ -f ${EXPORTDIR}/$alarmidx ];
          then
                cat $alarmidx | egrep -v "^#|^[ \t]*$|^TABLE" | sed -e '/::/s/$/::::::/g' > ${alarmidx}.filters
          else
                cat $alarmidx | egrep -v "^#|^[ \t]*$|^TABLE" > ${alarmidx}.filters
          fi
          #<MigratePorts>
             for portidx in `cat ${alarmidx}.filters`
             do
                nextipport=`echo $portidx  | sed -e 's/::.*//g'`
                # ':' may indicate an IPv6 address, not IP:port, only change if there's a single colon in the string
                colon_count=`echo $nextipport | tr -cd ':' | wc -c`
                if [ $colon_count -eq 1 ];
                then
                   nextip=`echo $nextipport   | cut -d':' -f1`
                   nextport=`echo $nextipport | cut -d':' -f2`
                   if [ "$nextport" != "" ];
                   then
                      echo $portidx | sed -e "s/:$nextport//" | sed -e "s/::::::$/::$nextport::::/"
                   else
                      echo $portidx
                   fi
                else
                   echo $portidx
                fi
             done > ${alarmidx}.filters.pmaped
          #</MigratePorts>
          cat ${alarmidx}.comments ${alarmidx}.filters.pmaped > $alarmidx
          rm -f ${alarmidx}.comments ${alarmidx}.filters*
       fi

    fi
    #</V7RTPAlarms>

    #</V9RTPAlarms>
    if osv_version.sh --major compare sys ge V9;
    then

     # For V9 add the extra columns
       alarmidx=/opt/SMAW/SMAWrtp/cust_conf/HiqAlarmFilters.tcn
       cat  ${alarmidx}  | awk -F"::" '{ if ( ($0 ~ '/\([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*.*\)/') && ( NF == 8 ) ) { print $0"::0::0::::"; } \
          else print $0 } ' > ${alarmidx}.new
       cp -p ${alarmidx}.new $alarmidx
       rm -f ${alarmidx}.new

    fi
    #</V9RTPAlarms>

    # HiqAlarmFilters.tcn was restored.  Replace anything in AltHiqAlarmFilters.tcn with the same.
    alarmidx="/opt/SMAW/SMAWrtp/cust_conf/HiqAlarmFilters.tcn"
    if [ -f "$alarmidx" ]
    then
        cp -p ${alarmidx} /opt/SMAW/SMAWrtp/cust_conf/AltHiqAlarmFilters.tcn
        chown srx:rtpgrp  /opt/SMAW/SMAWrtp/cust_conf/AltHiqAlarmFilters.tcn
    fi

}

# ---------------------------------------------------------------
# function:	isPoolServers
# args:		a domain name				
# description:
#  Check if this is a pool of servers
#  Return 0 if it is, otherwise return 1
# ---------------------------------------------------------------
isPoolServers()
{
   DNAME=$1

   if [ "$DNAME" = "" ]
   then
      return 1
   fi

   # This is an fqdn address
   if grep '[[:alpha:]]\+\.' <<< $DNAME | grep -qv ':'; then
      :
   else
      logstr "not valid fqdn $DNAME, skipping ntp pool check"
      return 1
   fi

   resolvedDomain=`host -R 1 -W 5 $DNAME`
   RET_DNS=$?
   logstr "DNS query returned $resolvedDomain for fqdn $DNAME, exit status ${RET_DNS}"
   if [ ${RET_DNS} -ne 0 ]; then
      return 1
   else
      if [ "$resolvedDomain" != "" -a  `grep -c address <<< "$resolvedDomain"` -gt 1 ]; then
         logstr "fqdn $DNAME is a  pool of ntp servers"
         return 0
      else
         logstr "fqdn $DNAME is not a  pool of ntp servers"
         return 1
      fi
   fi

}

# --------------------------------------------------------------
# function:           reconfigntp
# args: 
# description
#    Reconfig and restart ntp taking into account pool of servers 
#    No ntp restart if  no pool of servers found
#
#---------------------------------------------------------------
reconfigntp()
{
   local RESTART_NTP="false"
   NTPCNF=/etc/ntp.conf

   if osv_version.sh --major compare sys lt V8; 
   then
      logstr "No ntps pools configuration is currently supported for $buildid"
      return 1
   fi
 
   if [ ! -f $NTPCNF ]
   then
      logstr "No $NTPCNF found !!!"
      return 1
   fi
   
   #<PoolOfTimeservers>
    awk '/^server/ {print $2}' $NTPCNF | while read i; do
      [ -z "$i" ] && continue ;     
      isPoolServers $i 
      if [ $? -eq 0 ]; then
        RESTART_NTP="true"
        # this is the fqdn of a pool of timeservers, so configure it as such
        sed -i "/^server[ \t]$i/ s/^server/pool/" $NTPCNF
        sed -i "/^restrict[ \t]$i/ s/.*/restrict $i nomodify notrap noquery/" $NTPCNF 
      fi
    done

   #</PoolOfTimeservers>
   if [ "$RESTART_NTP" = "false" ]
   then
     return 1
   fi 

   return 0
}


# ---------------------------------------------------------------
# function: restorefsdata
# args    : None
# description:
#   restores the fsdata from import.
# ---------------------------------------------------------------

restorefsdata( )
{
    restorelicense
    logstr "   - Restoring file system data."
    restorebkup

    #<updateKeyIDs>
    NTPCNF=/etc/ntp.conf
     
    KEYFILE=`awk '/^keys/ {print $2}' $NTPCNF`
    
    if [ -z "$KEYFILE" -o ! -r "$KEYFILE" ]; then
      logstr "   ERROR: Missing NTP key or no NTP keys configured in /etc/ntp.conf"
    else
      KEYID=`head -1 $KEYFILE | awk '{print $1}'`
      for key in trustedkey requestkey controlkey; do
        if grep -q $key $NTPCNF; then
           sed -i "/^[[:blank:]]*#[[:blank:]]*$key/ s/^.*$key [0-9]\+/$key $KEYID/" $NTPCNF
        else
           # if for any reason the key is missing, append it
           echo "$key $KEYID" >> $NTPCNF
        fi
      done
    fi
    #</updateKeyIDs>

    #<updateSysconfigNtp>
    # In SLES11 starting from NTP Ver. 4.2.8p2 there is a different syntax in starting the process. It includes the '-c configfile' option.
    # So '-c configfile' has to be removed from /etc/sysconfig/ntp configuration (ref. CQ00338451).
    NTP_SYSCONF=/etc/sysconfig/ntp
    if [ -f /etc/init.d/ntp ]; then     # case of SLES11
      if grep  'startproc' /etc/init.d/ntp | grep -q '\-c'; then
        logstr "  NTP >= 4.2.8p2: '-c configfile' removed from $NTP_SYSCONF configuration"
        sed -i '/^NTPD_OPTIONS/ s/-c [^ ]*//' $NTP_SYSCONF
      fi
    else                                # case of SLES12
      if grep -q '\-c ' $NTP_SYSCONF; then
        logstr "  Migrate to V9: '-c configfile' removed from $NTP_SYSCONF configuration"
        sed -i '/^NTPD_OPTIONS/ s/-c [^ ]*//' $NTP_SYSCONF
      fi
    fi
    #</updateSysconfigNtp>

    #<FixNtpPeer>
       if [ "$testbed" = "cluster" -a "$cftype" = "3" ];
       then
          NTPCNFCLUSTER="${NTPCNF}.cluster"
          if [ "$mynode" = "$primhost" ];
          then
             othercip=$seccip
          else
             othercip=$primcip
          fi
          
          cat $NTPCNF | sed -e "s/^peer[ \t].*/server $othercip prefer/" > ${NTPCNFCLUSTER}.1
          egrep -q "^restrict" ${NTPCNFCLUSTER}.1
          if [ $? -eq 0 ];
          then
          {
             cat ${NTPCNFCLUSTER}.1 | sed -e "/^restrict[ \t]*$othercip.*/d" 
             echo "restrict $othercip nomodify notrap noquery nopeer"
          } > ${NTPCNFCLUSTER}.2
          else
             cp ${NTPCNFCLUSTER}.1 ${NTPCNFCLUSTER}.2
          fi
          cp -f ${NTPCNFCLUSTER}.2 $NTPCNF 
          # for v7/8 copy ntp.conf to ntp.conf.cluster       
          if osv_version.sh --major compare sys lt V9; 
          then
             cp -f $NTPCNF $NTPCNFCLUSTER
          fi

          rm -f ${NTPCNFCLUSTER}.1 ${NTPCNFCLUSTER}.2
       fi
    #</FixNtpPeer>

    #<Fix IPv6 restrict>
    if [ `grep -c "^restrict -6 ::1"      $NTPCNF` -eq 0 ] ; then
        echo "restrict -6 ::1"         >>  $NTPCNF
    fi
    #</IPv6 restrict>

   #<Remove D class mask>
      if osv_version.sh --major compare sys ge V9; 
      then
         sed -i 's|mask[[:blank:]]\+255[.]255[.]255[.]255||g' $NTPCNF
      fi
   #</Remove D class mask>  
    mergertpparms

    if osv_version.sh --major compare sys lt V9; 
    then
       mergesnmp
    else
       mergesnmpV9
    fi

    fixdns

    #<UpdateLoadLabel>
       recomputepsinfo
    #</UpdateLoadLabel>

    if [ "$SYSIMPORT" != "true" -a "$Migrate8k" != "true" ];
    then
       cp -p /img/rootimg/etc/hosts            /tmp/hosts
       cp -p /img/rootimg/etc/passwd           /tmp/passwd
       cp -p /img/rootimg/etc/group            /tmp/group
       cp -p /img/rootimg/etc/shadow           /tmp/shadow
       cp -p /img/rootimg/etc/hiq8000/node.cfg /tmp/node.cfg
    else
       cp -p ${EXPORTDIR}/etc/hosts            /tmp/hosts
       cp -p ${EXPORTDIR}/etc/passwd           /tmp/passwd
       cp -p ${EXPORTDIR}/etc/group            /tmp/group
       cp -p ${EXPORTDIR}/etc/shadow           /tmp/shadow
       cp -p ${EXPORTDIR}/etc/hiq8000/node.cfg /tmp/node.cfg
    fi
    if [ ! -f /tmp/hosts ];
    then
       echo "   - Skipping host adjustment. hosts not found."
    fi

    importrtt
    importtrusted
    if [ "X$(isOSEE)X" = "XtrueX" -a "$Migrate8k" = "true" ]
    then
       logstr "It is an OSEE migration do not import /etc/hosts"
    else
       if [ "$Migrate8k" = "true" ]
       then
          # for migrate use the node.cfg of the system and the exported hosts file
          # so it will add the custom hosts if they exist
          importhosts /tmp/hosts /etc/hiq8000/node.cfg
       else 
          # live upgrade
          importhosts   /tmp/hosts    /tmp/node.cfg
       fi
    fi
    importpasswds /tmp/passwd
    importgroups  /tmp/group
    importshadow  /tmp/shadow
    importhomes
    importfileparam
   #  importsshdconfig
    importaccessconf
    if [ "$Migrate8k" = "true" ]; then
       echo "Skipping import of survivability data"
    else
       importsurv
    fi
    importsbc
    if osv_version.sh --major compare sys lt V5; 
    then
       importsrcroutes
    else
       logstr "   - Your routing will be derived from node.cfg."
    fi
    importcerts
    importdns
    setupmtu

    if osv_version.sh --major compare sys ge V9 && osv_version.sh compare "$expbuildid" ge V9;
    then
       cp -p ${EXPORTDIR}/etc/audit/audit.rules /etc/audit
       if [ -x /unisphere/srx3000/callp/bin/audit_configuration.pl ]
       then
          /unisphere/srx3000/callp/bin/audit_configuration.pl -merge
          #if [ $? -eq 0 ]
          #then
          #   systemctl restart auditd
          #fi 
       fi
    fi

    rm -f  /tmp/hosts   \
           /tmp/passwd  \
           /tmp/group   \
           /tmp/shadow  \
           /tmp/node.cfg
}

# ---------------------------------------------------------------
# function: adjustfsresidue
# args    : None
# description:
#   reflects all file system files to match node.cfg.
# ---------------------------------------------------------------

adjustfsresidue( )
{
   logdebug "Function adjustfsresidue called"

   # The node_1_name, node_2_name variables are marked with + as special variables
   # According to the logic below, the special variables are supposed to be search
   # and replaced even in they are part of string. Exact matching and replace is
   # performed for the non-special variables only, by using the sed word binary \b
   # at the end of the search pattern.
   varlist="\
+node_1_name node_1_ip \
+node_2_name node_2_ip \
lsm_node_1_ip lsm_node_2_ip \
node_1_cip0 node_1_cip1 node_1_cip_logical \
node_2_cip0 node_2_cip1 node_2_cip_logical \
cip_network \
cip2_network \
cip_gateway \
cip2_gateway \
ccm10_1_vip ccm10_2_vip \
ccm05_1_vip ccm05_2_vip \
ccmtg_1_vip ccmtg_2_vip \
ccmdq_1_vip ccmdq_2_vip \
ccm10_1_vip_2 ccm10_2_vip_2 \
ccm05_1_vip_2 ccm05_2_vip_2 \
ccmtg_1_vip_2 ccmtg_2_vip_2 \
ccmdq_1_vip_2 ccmdq_2_vip_2 \
pcmm_ip pcmm_ip_2 \
smdi_vip \
sipsm1_vip sipsm2_vip sipsm3_vip sipsm4_vip sipsm3_vip_2 sipsm4_vip_2 \
cstasm1_vip cstasm2_vip cstasm1_vip_2 cstasm2_vip_2 \
node_1_vip1 node_2_vip1 node_1_vip2 node_2_vip2 node_1_vip3 node_2_vip3 \
node_1_vip4 node_2_vip4 node_1_vip5 node_2_vip5 \
cdc_df_vip \
subp_vip \
name_server_ip_1 name_server_ip_2 \
search_domain_1 \
ntp_server_1 \
ntp_server_2 \
rsa_1_ip rsa_2_ip \
default_router  default_router_2 \
survival_authority \
snmp_server1 snmp_server2 \
smc_server1 smc_server2 \
ssc_server1 \
superuserip \
pmc_server1 \
license_server1 \
billing_server1 billing_client1 \
nmc_vip \
sbc_lan_ip \
csta_server1 \
csta_server2 \
csta_server3 \
csta_server4 \
"


     ##########################################################################
     # Read some extra variables not in static list above
     getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_1_name      expn1name
     getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_2_name      expn2name
     for tendencyidx in clli_name_node_1 clli_name_node_2 domain_name DOMAIN_NAME
     do
        getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  clli_name_node_1 exptendency
        if [ "$exptendency" != "$expn1name" -a "$exptendency" != "$expn2name" ];
        then
           varlist="$varlist $tendencyidx"
        fi
     done
     ##########################################################################


     logdebug "[adjustfsresidue] Variable list to transform: ${varlist}"

     textncolor $BoldCyan "Adjusting data in file system."

     # Source node.cfg for the data migration
     IMPCFG8k=/software/export/etc/hiq8000/node.cfg

     logdebug "[adjustfsresidue] Source node.cfg[${IMPCFG8k}], Target node.cfg[${CFG8k}]"

     ##########################################################################
     # Read the networking values for all nafo lines
     nafovarlist="nafo0 nafo1 nafo2 nafo3"
     count=0
     for nafovaridx in $nafovarlist
     do
        getarraynafovar $IMPCFG8k $CFG8k $nafovaridx
        nafostatus=$?
        if [ $nafostatus -ne 0 ]
        then
           logstr "Skipping ${nafovarlist}."
        fi
     done
     ##########################################################################


     ##########################################################################
     # Read all the values from the list from both source and target node.cfg
     auxcmd="" 
     auxcmd_norm="" 
     for varidx in $varlist
     do
        getarraycfgvar $IMPCFG8k $CFG8k $varidx
        cfgstatus=$?
        if [ "$special" = "true" ]
        then
              logdebug "[adjustfsresidue] Special variable found [${varidx}], special=[${special}]"

              auxcmd="${auxcmd} -e s/$specialold/$specialnew/g"
              auxcmd_norm="${auxcmd}"
              logdebug "[adjustfsresidue] auxcmd=[${auxcmd}]"
        fi
        if [ ${cfgstatus} -eq 0 ]
        then
           logdebug "[adjustfsresidue] Valid variable found [${varidx}], count=[${count}], source value=[${srcnodecfg[$count]}], destination value=[${destnodecfg[$count]}]"

           count=$(expr $count + 1)
        fi
     done
     ##########################################################################


     # Fill last value with empty values for stop gap
     srcnodecfg[$count]=""
     destnodecfg[$count]=""
     nodecfgflag[$count]=""


     ##########################################################################
     # This block of code transforms the variable values in array srcnodecfg, so
     # that all '.' dot characters are transformed to '[.]' for the sed search
     # patterns below. Without this transformation the IPv4 and FQDN dot characters
     # would be considered regex '.' which is any character.
     # E.g. osv.xcomp.gr -> osv[.]xcomp[.]gr and 10.200.100.30 -> 10[.]200[.]100[.]30
     #<AdjustIp>
         count=0
         while [ "${srcnodecfg[${count}]}" != "" ]
         do
             logdebug "[adjustfsresidue] Adjusting [${srcnodecfg[${count}]}]"
             local adjsrcinfo=$(echo "${srcnodecfg[${count}]}" | sed -e 's/\./[.]/g')
             srcnodecfg[${count}]="${adjsrcinfo}"
             logdebug "[adjustfsresidue] Adjusted to [${srcnodecfg[${count}]}]"

             count=$(expr $count + 1)
         done
     #</AdjustIp>
     ##########################################################################


     ##########################################################################
     # If remaposv.cfg is generated then apply the mapping for solution entities
     # such as gateways and cmp's
     remapauxcmd=""
     if [ -f /etc/hiq8000/remaposv.cfg ];
     then
        logdebug "[adjustfsresidue] Found /etc/hiq8000/remaposv.cfg"

        cat /etc/hiq8000/remaposv.cfg | grep -v "^#" > /tmp/objects.remap
        for pfridx in `cat /tmp/objects.remap`
        do
           remappfrdefn="`echo $pfridx  | awk -F ':' '{ print $1 }'`"
           remappfrname="`echo $pfridx  | awk -F ':' '{ print $2 }'`"
           if [ "$remappfrdefn" = "management" -o "$remappfrdefn" = "packetfilter" ];
           then
              can_have_netmask=true
           else
              can_have_netmask=false
           fi
 
           # check if we have source address in brackets, which by rule contains an IPv6 address
           # either the 1st IP or the 2nd is IPv6
           echo "$pfridx" | grep -e '^[a-z]*:[A-Za-z0-9_-]*:\[\(.*\)\]:'
           if [ $? -eq 0 ]
           then
              # get the 1st IP addr inside the brackets
              remap_match="`echo $pfridx | sed -n 's/^[a-z]*:[A-Za-z0-9_-]*:\[\(.*\)\]:.*:.*/\1/p'`"
              
              # for gateways we have fqdn inside brackets
              if [ "$remappfrdefn" = "gateway" ]
              then
                 if ! isIPv6Addr ${remap_match}
                 then
                    # add again the brackets
                    remap_match="[${remap_match}]" 
                 fi
              fi

              if [ "${can_have_netmask}" = "true" ]
              then
                 remappfripold="`echo ${remap_match} | awk -F '/' '{ print $1 }'`"
                 remappfrnmold="`echo ${remap_match} | awk -F '/' '{ print $2 }'`"
              else
                 remappfripold="${remap_match}"
                 remappfrnmold=""
              fi

              # get the 2nd IP add inside the brackets
              remap_match="`echo $pfridx | sed -n 's/^[a-z]*:[A-Za-z0-9_-]*:\[.*\]:\[\(.*\)\]:.*/\1/p'`"

	      if [ "X${remap_match}X" = "XX" ]
              then
                 logstr "Invalid IPv6 remap for line : $pfridx"
                 continue
              fi 
          
              
              # for gateways we have fqdn inside brackets
              # so we add again the brackets
              if [ "$remappfrdefn" = "gateway" ]
              then
                 if ! isIPv6Addr ${remap_match}
                 then
                    # add again the brackets
                    remap_match="[${remap_match}]"
                 fi
              fi
              

              if [ "${can_have_netmask}" = "true" ]
              then
                 remappfripnew="`echo ${remap_match} | awk -F '/' '{ print $1 }'`"
                 remappfrnmnew="`echo ${remap_match} | awk -F '/' '{ print $2 }'`"
              else
                 remappfripnew="`echo ${remap_match} | awk -F '/' '{ print $1 }'`"
                 remappfrnmnew=""
              fi
                      
           else # IPv4 as usual since we don't have brackets in IPs

              if [ "X${can_have_netmask}X" = "XtrueX" ]
              then
                 remappfripold="`echo $pfridx | awk -F ':' '{ print $3 }' | awk -F '/' '{ print $1 }'`"
                 remappfrnmold="`echo $pfridx | awk -F ':' '{ print $3 }' | awk -F '/' '{ print $2 }'`"
                 remappfripnew="`echo $pfridx | awk -F ':' '{ print $4 }' | awk -F '/' '{ print $1 }'`"
                 remappfrnmnew="`echo $pfridx | awk -F ':' '{ print $4 }' | awk -F '/' '{ print $2 }'`"
              else
                 remappfripold="`echo $pfridx | awk -F ':' '{ print $3 }'`"
                 remappfripnew="`echo $pfridx | awk -F ':' '{ print $4 }'`"
                 remappfrnmold=""
                 remappfrnmnew=""
              fi
               
           fi

   

           if [ "$remappfrname" != "" -a "$remappfripold" != "" -a \
                "$remappfripnew" != "*" -a "$remappfripold" != "$remappfripnew" -a "$remappfrnmold" = "$remappfrnmnew" ];
           then
              logstr "   - Remapping $remappfrname from $remappfripold/$remappfripnew."
              auxcmd="${auxcmd} -e 's/$remappfripold[ \t]/$remappfripnew /g'"
              auxcmd_norm="${auxcmd_norm} -e 's/`getNormalizeIP $remappfripold`[ \t]/`getNormalizeIP $remappfripnew` /g'"
              remapauxcmd="${remapauxcmd} -e s/'$remappfripold'/'$remappfripnew'/g"
              srcnodecfg[${count}]=$remappfripold
              destnodecfg[${count}]=$remappfripnew
              elemnodecfg[${count}]=$remappfrname
              count=$[count+1]

              logdebug "[adjustfsresidue] auxcmd=[${auxcmd}], remapauxcmd=[${remapauxcmd}]"
           fi
        done
     fi
     ##########################################################################


     ##########################################################################
     # Loop through the variable transformation lists and produce a dynamic sed
     # search/replace command
     count=0
     execcmd="sed "
     execcmd_norm="sed "
     # Header of loop's printed output in color
     textncolor $BoldCyan "operation:element name:old value:new value" | \
                  awk -F':' '{ printf "%12s %20s %32s %32s\n", $1,$2,$3,$4 }'

     while [ "${srcnodecfg[${count}]}" != "" ] # While we have values to transform
     do
        if [ "${srcnodecfg[${count}]}"  != "0[.]0[.]0[.]0" -a \
             "${destnodecfg[${count}]}" != "0[.]0[.]0[.]0" -a \
             "${destnodecfg[${count}]}" != "::"           -a \
             "${destnodecfg[${count}]}" != "" ];
        then
           
           logstr "Processing:${elemnodecfg[${count}]}:${srcnodecfg[${count}]}:${destnodecfg[${count}]}" | \
                     sed -e 's/\[.\]/./g' | awk -F':' '{ printf "%12s %20s %32s %32s\n", $1,$2,$3,$4 }'
           nextsrccfg="`echo ${srcnodecfg[${count}]} | sed -e 's/\./\\\./g'`"
           nextdestcfg="`echo ${destnodecfg[${count}]} | sed -e 's/\./\\\./g'`"
            
           if [ "X${nodecfgflag[${count}]}X" = "XtrueX" ]
           then
              execcmd="${execcmd} -e s/${srcnodecfg[${count}]}/${destnodecfg[${count}]}/g "
           else
              src_ip_norm=`getNormalizeIP ${srcnodecfg[${count}]}`
              dest_ip_norm=`getNormalizeIP ${destnodecfg[${count}]}`
              
              # If one of source or target are IPv6 then we need to normalize them         
              # so we produce a set of sed regex with normalize IPs
              execcmd_norm="${execcmd_norm} -e s/\\<${src_ip_norm}\\>/${dest_ip_norm}/g "

              execcmd="${execcmd} -e s/\\<${srcnodecfg[${count}]}\\>/${destnodecfg[${count}]}/g "
           fi

           logdebug "[adjustfsresidue] execcmd=[${execcmd}], nodecfgflag=[${nodecfgflag[${count}]:-EMPTY}]"
        else
           logstr "Skipping:${elemnodecfg[${count}]}:${srcnodecfg[${count}]}:${destnodecfg[${count}]}"  | \
                     sed -e 's/\[.\]/./g' | awk -F':' '{ printf "%12s %20s %32s %32s\n", $1,$2,$3,$4 }'
        fi
        count=$(expr $count + 1)
    done
    ##########################################################################


    #<CyclicGraph>
       textncolor $BoldCyan "[${_SELF_}]: Checking cyclic mappings."
       cyclicsi=0
       while [ "${srcnodecfg[${cyclicsi}]}" != "" ];
       do
          cyclicelem=${elemnodecfg[${cyclicsi}]}
          cyclicsrc=`getNormalizeIP ${srcnodecfg[${cyclicsi}]}`
          cyclictgt=`getNormalizeIP ${destnodecfg[${cyclicsi}]}`
          if [ "$cyclictgt" = "" ];
          then
             cyclicsi=`expr $cyclicsi + 1`
             continue
          fi
          cyclicti=0
          while [ "${srcnodecfg[${cyclicti}]}" != "" ];
          do
             if [ "$cyclicelem" = "${elemnodecfg[${cyclicti}]}" ];
             then
                cyclicti=`expr $cyclicti + 1`
                continue
             fi
             logstr "Cyclic :$cyclicsi - ${cyclicti} -  $cyclictgt - `getNormalizeIP ${srcnodecfg[${cyclicti}]}` - `getNormalizeIP ${destnodecfg[${cyclicti}]}`"
                
             cyclicsrc_target="`echo $(getNormalizeIP ${srcnodecfg[${cyclicti}]}) | sed 's|\[\.\]|\.|g'`" 
             
             if [ "$cyclictgt" = "${cyclicsrc_target}" -a \
                  "X${cyclicsrc_target}X" != "X`getNormalizeIP ${destnodecfg[${cyclicti}]}`X" ];
             then
                textncolor $BoldRed "Sorry, You have a weird mapping($cyclictgt).Check node.cfg."
                logstr "[${_SELF_}]: Invalid mapping ${cyclicelem}:${srcnodecfg[${cyclicti}]}:${destnodecfg[${cyclicti}]}"
                exit $FAIL
             fi
             cyclicti=`expr $cyclicti + 1`
          done
          cyclicsi=`expr $cyclicsi + 1`
       done
    #<CyclicGraph>
    
    getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  cf_type  expcftype
    getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_separation  expnodesep 
    getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  test_bed exptestbed
    {
       logstr "cftype=<$cftype>, expcftype=<$expcftype>"
       logstr "nodesep=<$nodesep>, expnodesep=<$expnodesep>"
       logstr "testbed=<$testbed>, exptestbed=<$exptestbed>" 
    } 1>/dev/null 2>&1

    if [ "$cftype" = "$expcftype" -a "$nodesep" = "$expnodesep" -a "$testbed" = "$exptestbed" ];
    then
       restorefsdata
    else 
       if [ "$IMPORTHOSTS" = "true" ];
       then
          restorefsdata
       else
          #<RestoreUnchangeDataOnly>
             restorelicense
             getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  rsa_1_ip exprsaprimip
             getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  rsa_2_ip exprsasecip
             getcfgvar /etc/hiq8000/node.cfg              rsa_1_ip rsaprimip
             getcfgvar /etc/hiq8000/node.cfg              rsa_2_ip rsasecip

             if [ "$exprsaprimip" = "$rsaprimip" -a "$exprsasecip" = "$rsasecip" ];
             then
                importsurv
             fi

             ZMODIFIED=/opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm
             if [ -f ${EXPORTDIR}/${ZMODIFIED} ];
             then
                cp ${EXPORTDIR}/${ZMODIFIED} $ZMODIFIED
                if osv_version.sh --major compare sys ge V4; 
                then
                   chown srx.rtpgrp $ZMODIFIED 
                fi
             fi
             #<UpdateLoadLabel>
                recomputepsinfo
             #</UpdateLoadLabel>

             if [ "$SYSIMPORT" != "true" -a "$Migrate8k" != "true" ];
             then
                cp -p /img/rootimg/etc/passwd           /tmp/passwd
                cp -p /img/rootimg/etc/group            /tmp/group
                cp -p /img/rootimg/etc/shadow           /tmp/shadow
             else
                cp -p ${EXPORTDIR}/etc/passwd           /tmp/passwd
                cp -p ${EXPORTDIR}/etc/group            /tmp/group
                cp -p ${EXPORTDIR}/etc/shadow           /tmp/shadow
             fi
             if [ ! -f /tmp/hosts ];
             then
                echo "   - Skipping host adjustment. hosts not found."
             fi
             importpasswds /tmp/passwd
             importgroups  /tmp/group
             importshadow  /tmp/shadow

             mergertpparms

          #</RestoreUnchangeDataOnly>
       fi
    fi
}

# ---------------------------------------------------------------
# function: solidperfsetup
# args    : None
# description:
#   boosts solid performance.
# ---------------------------------------------------------------

solidperfsetup( )
{
   logstr "function: solidperfsetup is called"
   if osv_version.sh --major compare sys ge V4 && [ "$steroid4solid" = "true" ];
   then
      #<Steroid4Solid>
      mount | grep -q tmpfs
      if [ $? -eq 0 ];
      then
         cp $SOLINI ${SOLINI}.steroid
         cat $SOLINI | sed -e 's/^TmpDir_1.*/TmpDir_1 = \/dev\/shm\/solidws/g'        \
                           -e 's/.*TmpDir_2.*/TmpDir_2 = \/home\/solid\/RtpDb/g'      \
                           -e 's/^CacheSize.*/CacheSize = 512MB/g'                    \
                           -e 's/^CheckpointInterval.*/CheckpointInterval = 500000/g' \
                     > ${SOLINI}.new
         cp  ${SOLINI}.new $SOLINI
         rm -f ${SOLINI}.new
         mkdir -p  /dev/shm/solidws
         chmod 777 /dev/shm/solidws
      fi
      #</Steroid4Solid>
   fi
}

# ---------------------------------------------------------------
# function: solidperfclean
# args    : None
# description:
#   cleans boosts for solid performance.
# ---------------------------------------------------------------

solidperfclean( )
{
   if osv_version.sh --major compare sys ge V4 && [ "$steroid4solid" = "true" ];
   then
      if [ -f ${SOLINI}.steroid ];
      then
         cp ${SOLINI}.steroid ${SOLINI}
         rm -f ${SOLINI}.steroid
      fi
   fi

}

# ---------------------------------------------------------------
# function: adjustimportdb
# args    : None
# description:
#   migrates db for current configuration.
# ---------------------------------------------------------------

adjustimportdb( ) 
{
    #<MigrateFiles>
      textncolor $BoldCyan "Migrating data."
      saveappsfromdb
      cleanappsfromdb
      setmode $BoldPurple

      # OSV-2473: Do not change the endpoint Openscape_CNF1 of type OpenScape UC
      # when you are migrating OSEEV8R1 export data to an OSEE >V9 system. This
      # requires these steps:
      # 1) Skip changing ENDPOINT_T table record where the field EP_NAME = Openscape_CNF1
      # 2) Skip changing ALIAS_T table record where the field EP_ID is equal to the
      # corresponding EP_ID of table ENDPOINT_T record we skipped in step 1.
      if [ "X$(isOSEE)X" = "XtrueX" ]
      then
          local alias_table_data="${SOLIDHOME}/migrate8knew/RTPDB/DBA_ALIAS_T.dat"
          local endpoint_table_data="${SOLIDHOME}/migrate8knew/RTPDB/DBA_ENDPOINT_T.dat"
          [ ! -f "${alias_table_data}" ] && logstr "No endpoint alias table found for migration..."
          [ ! -f "${endpoint_table_data}" ] && logstr "No endpoint table found for migration..."

          # Record of ENDPOINT_T
          local skip_endpoint_name='Openscape_CNF1'
          local skip_endpoint_record="$(grep "${skip_endpoint_name}" "${endpoint_table_data}" 2>/dev/null)"
          local skip_endpoint_id="$(echo "${skip_endpoint_record}" | awk -F',' '{ print $2 }')"
          skip_endpoint_id="$(eval echo ${skip_endpoint_id})"
          local skip_endpoint_value="$(echo "${skip_endpoint_record}" | awk -F',' '{ print $3 }')"
          skip_endpoint_value="$(eval echo ${skip_endpoint_value})"

          logdebug "We will skip the migration of endpoint [${skip_endpoint_name}] with ID [${skip_endpoint_id}], full record [${skip_endpoint_record}]"

          # Record of ALIAS_T
          local skip_alias_record=''
          local skip_alias_value=''
          local skip_alias_id=''
          if [ "X${skip_endpoint_value}X" != "XX" -a "X${skip_endpoint_id}X" != "XX" ]
          then
              skip_alias_record="$(grep "'${skip_endpoint_value}','[[:digit:]]*','[[:digit:]]*','${skip_endpoint_id}'" "${alias_table_data}" 2>/dev/null)"
              skip_alias_value="$(echo "${skip_alias_record}" | awk -F',' '{ print $1 }')"
              skip_alias_value=$(eval echo ${skip_alias_value})
              skip_alias_id="$(echo "${skip_alias_record}" | awk -F',' '{ print $4 }')"
              skip_alias_id="$(eval echo ${skip_alias_id})"
          fi

          logdebug "We will skip the migration of alias [${skip_alias_value}] with endpoint ID [${skip_alias_id}], full record [${skip_alias_record}]"
      fi


      dbfiles="`find ${SOLIDHOME}/migrate8knew`"
      for idx in $dbfiles
      do
         if [ -f $idx ]
         then

            logstr "   - Migrating $(basename $idx)"

            # OSV-2473: OSEE specific part
            if [ "X$(isOSEE)X" = "XtrueX" ]
            then
                # Skip the ALIAS_T, ENDPOINT_T record transformation
                if [ "X${skip_endpoint_record}X" != "XX" ] && [[ ${idx} = *"DBA_ENDPOINT_T.dat" ]]
                then
                    logdebug "Skipping record [${skip_endpoint_record}] of table [${idx}]"
                    cat ${idx} | grep -v "${skip_endpoint_record}" | ${execcmd} > ${idx}.migrate
                    # Put back the skipped record, we want to keep it as it is
                    echo "${skip_endpoint_record}" >> ${idx}.migrate
                elif [ "X${skip_alias_record}X" != "XX" ] && [[ ${idx} = *"DBA_ALIAS_T.dat" ]]
                then
                    logdebug "Skipping record [${skip_alias_record}] of table [${idx}]"
                    cat ${idx} | grep -v "${skip_alias_record}" | ${execcmd} > ${idx}.migrate
                    # Put back the skipped record, we want to keep it as it is
                    echo "${skip_alias_record}" >> ${idx}.migrate
                else
                    cat ${idx} | ${execcmd} > ${idx}.migrate
                fi
            else
                # Regular OSVs do not skip anything
                cat ${idx} | ${execcmd} > ${idx}.migrate
            fi

            cp -f ${idx}.migrate ${idx}
            chmod a+r ${idx}
            rm -f ${idx}.migrate

         fi
      done
      restoreappsfromdb
      setmode $Norm
    #</MigrateFiles>

}

# ---------------------------------------------------------------
# function: handletriggers
# args    : None
# description:
#   enables or disables triggers in the db.
# ---------------------------------------------------------------


buildtriggers( ) 
{
   trigfile=/tmp/soltriggers
   su - solid -c "$solsql -x onlyresults -o $trigfile -a \
      -e \"select trigger_name,trigger_schema,trigger_catalog from sys_triggers where trigger_enabled='YES' \" \"tcp 16760\" dba $(getDbaPassword)" 1>/dev/null 2>&1
   cat $trigfile | sed '/^$/d' > ${trigfile}.lst
   echo `cat ${trigfile}.lst | wc -l`
}

handletriggers( )
{
   trigopt=$1
   trigfile=/tmp/soltriggers
   while read triginfo
   do
      trigcatalog=`echo $triginfo | awk '{ print $3 }'`
      trigschema=`echo $triginfo | awk '{ print $2 }'`
      trigname=`echo $triginfo | awk '{ print $1 }'`
      echo "Alter $trigopt triggers for $trigname."
      su - solid -c "$solsql -a \
         -e \"alter trigger ${trigcatalog}.${trigschema}.${trigname} set ${trigopt} \" \"tcp 16760\" dba $(getDbaPassword)"
   done < ${trigfile}.lst
}

# ---------------------------------------------------------------
# function: importsecendpoint
# args    : None
# description:
#   bring in secure_endpoint_t table, bringing entries which have
#   valid alias.
# ---------------------------------------------------------------

importsecendpoint( )
{
  endpointfile=$1
  rm -f ${endpointfile}.new
  touch ${endpointfile}.new
  if [ -f $endpointfile ];
  then
     logstr "   - Adapting security profiles for ipsec."
     while read line
     do
        epalias=`echo $line | cut -f8 -d',' | sed -e s/\'//g` 
        epname=`echo $line  | cut -f2 -d',' | sed -e s/\'//g` 
        egrep -qw "$epalias" /etc/hosts
        if [ $? -eq 0 ]; 
        then
           logstr "      - Adding $epname profile to database."
           echo $line >> ${endpointfile}.new
        else
           logstr "      - Skipping $epname profile inside database."
        fi
     done < $endpointfile
     cp -f ${endpointfile}.new ${endpointfile}
     rm -f ${endpointfile}.new
     chmod 777 ${endpointfile}
  fi
}

# ---------------------------------------------------------------
# function: diffbksize
# args    : None
# description:
#   Checks the database block size of the source and target systems.
#   Returns success(0) if they dont differ. Otherwise, the database
#   will be rebuilt to to rectify the block size.
# ---------------------------------------------------------------

diffbksize( ) {

   if ! diff_blk_sz_msg=$(/usr/bin/solid_block_size_verifier $SOLINI) ; then
      logstr $diff_blk_sz_msg
      logstr "[WARNING]: Rebuilding database to rectify block size."
      return $FAIL
   fi

   logstr $diff_blk_sz_msg
   logstr "[INFO]: There is no need to rebuild database."
   return $SUCCESS

}

# ---------------------------------------------------------------
# function: createemptydb
# args    : None
# description:
#   Remove the old database, create a new (empty) one and start
#   Assumption: OSV is on state 2
# ---------------------------------------------------------------

createemptydb( ) {

   logstr "[${_SELF_}]: Creating empty database."
   rm -f ${RtpDb8k}/sol*

   if ! su - solid -c "solid -c /var/RtpDb -C RTPDB -U dba -P $(getDbaPassword) -x exit" 2>&1>>$LOGFILE;
   then
      textncolor $BoldCyan "Failed to create an empty database"
      return 1
   fi

   if ! su - solid -c "solid -c /var/RtpDb" 2>&1>>$LOGFILE;
   then
      textncolor $BoldCyan "Unable to change solid working directory"
      return 1
   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: rebuilddb
# args    : None
# description:
#   rebuild db for current configuration of solid.ini block size.
# ---------------------------------------------------------------

rebuilddb( ) {

   logstr "[*] [${_SELF_}]: Rebuilding db."

   export Export8k=${SOLIDHOME}/migrate8k
   export Apps8k=${SOLIDHOME}/apps8k
   export RtpDb8k=${SOLIDHOME}/RtpDb

   #[1]. First export all the data in current db.

   #<SwitchSolid>
      switchsolid ${mynode}
   #</SwitchSolid>
   {
      rm -rf ${Export8k} 
      mkdir -p ${Export8k}
      chmod 777  ${Export8k}
   }

   catfile=/tmp/solcat
   su - solid -c "$solsql -x onlyresults -o $catfile -a \
              -e \"select name from sys_catalogs \" \"tcp 16760\" dba $(getDbaPassword)" 1>/dev/null 2>&1
   cat $catfile | sed '/^$/d' > ${catfile}.lst

   su - solid -c "cd  ${Export8k};$soldd  -xFKAlterTable 'tcp 16760' dba $(getDbaPassword)"
   if [ $? -ne 0 ];
   then
      logstr "[${_SELF_}]: Sorry, Solid schema could not be exported"
      exit $DBRESTOREFAILED
   fi

   #<SolidBug?>
      if [ "$profile" = "integrated" -a "X$(isOSEE)X" = "XfalseX" ];
      then
         fixappsschema ${Export8k}/soldd.sql
         su - solid -c "cd ${Export8k}; $soldd -C opensoa -s symgroupware 'tcp 16760' dba $(getDbaPassword) owners 1>>$LOGFILE 2>&1"
         cat ${Export8k}/OWNERS.sql 2>/dev/null | sed -e 's/"OWNERTYPE" WVARCHAR(255),/"OWNERTYPE" WVARCHAR(255) NOT NULL,/g' \
                                    > ${Export8k}/OWNERS.sql.migrate8k
         su - solid -c "cd ${Export8k}; $soldd -C opensoa -s symgroupware 'tcp 16760' dba $(getDbaPassword) contactstores 1>>$LOGFILE 2>&1"
         cp ${Export8k}/OWNERS.sql.migrate8k ${Export8k}/OWNERS.sql
         rm -f ${Export8k}/OWNERS.sql.migrate8k
      fi
   #</SolidBug?>

   for catidx in `cat ${catfile}.lst`
   do
      textncolor $BoldCyan "Exporting catalog $catidx."
      mkdir -p ${Export8k}/${catidx}
      chmod 777 ${Export8k}/${catidx}
      su - solid -c "cd  ${Export8k}/${catidx}; $solexp -C $catidx 'tcp 16760' dba $(getDbaPassword) \*" 1>/dev/null 2>&1
      if [ $? -ne 0 ];
      then
         logstr "[${_SELF_}]: Sorry, Solid data could not be exported for catlog $catidx"
         exit $DBRESTOREFAILED
      fi
   done

   triggersbefore=`buildtriggers`
   logstr "   - There are $triggersbefore triggers active in your database."
   cat /tmp/soltriggers 1>>$LOGFILE 2>&1


   #[2]. Bring system to state#2.
   textncolor $BoldCyan "Bringing system to state#2 : `date`"
   sleep 20
   /unisphere/srx3000/srx/startup/srxctrl 2 `remotestate 2`  1>>$LOGFILE 2>&1
   if [ $? -ne 0 ];
   then
      logstr "[${_SELF_}]: Cannot bring system to state#2."
      exit $DBRESTOREFAILED
   fi
   if [ -f /etc/init.d/symphoniad -a "X$(isOSEE)X" = "XfalseX" ];
   then
      textncolor $BoldCyan "LocalNode: Stopping Symphonia Applications"
      checkappstatus stop local
   fi

   #[3]. Create empty database.
   if ! createemptydb;
   then
      exit $DBRESTOREFAILED
   fi

   #<CheckSolidCon>
      textncolor $BoldCyan "Waiting for database to be fully up. `date`"
      while ( true )
      do
         lsof -i :16760 1>/dev/null 2>&1
         if [ $? -eq 0 ];
         then
            su - solid -c "$solsql -a -e \"admin command 'status' \" \"tcp 16760\" dba $(getDbaPassword)" 1>/dev/null 2>&1
            if [ $? -eq 0 ];
            then
               break;
            fi
         fi
         echo -n "."
         sleep 4
      done
   #</CheckSolidCon>

   #[4]. Import it back.
   textncolor $BoldCyan "   - Loading schema."
   su - solid -c "$solsql -a -e \"admin command 'hsb switch primary' \" \"tcp 16760\" dba $(getDbaPassword)"
   restoresystables
   su - solid -c "$solsql -a 'tcp 16760' dba $(getDbaPassword) ${Export8k}/soldd.sql" 1>>$LOGFILE 2>&1
   #<SolidBug?>
      if [ "$profile" = "integrated" ];
      then
         su - solid -c "$solsql -a 'tcp 16760' dba $(getDbaPassword) ${Export8k}/OWNERS.sql 1>>$LOGFILE 2>&1"
      fi
   #</SolidBug?>
   chmod -R a+r $Export8k

   # We will handle creation of OSV user later on dbExecuter so drop SCHEMA OSVUSER
   #<Drop schema OSVUSER>
   dropuserfile="/tmp/drop_user_schema.sql"
   if osv_version.sh --major compare sys ge V9; 
   then
      {
         echo "drop schema OSVUSER;"
         echo "commit work;"
      } > $dropuserfile
      chmod a+r $dropuserfile
      su - solid -c "$solsql -a 'tcp 16760' dba $(getDbaPassword) $dropuserfile" 1>>$LOGFILE 2>&1
      if [ $? -ne 0 ];
      then
         logstr "[${_SELF_}]: Cannot drop schema OSVUSER."
         exit $DBRESTOREFAILED
      fi

    fi
   #</Drop schema OSVUSER>

   setmode $Norm
   rm -rf $Sys8k $createuserfile

   handletriggers disabled
   rm -f ${LOGSOLIDHOME}/solload.log
   touch ${LOGSOLIDHOME}/solload.log
   chmod 777 ${LOGSOLIDHOME}/solload.log
   textncolor $BoldCyan "   - Loading tables."
   setmode $BoldPurple
   for catidx in `cat ${catfile}.lst`
   do
      for ctridx in `ls ${Export8k}/${catidx}/*ctr 2>/dev/null`
      do
         logstr "   - Loading `basename $ctridx .ctr`"
         su - srx -c "cd ${Export8k}/${catidx}; $solload -C $catidx -L ${LOGSOLIDHOME}/solload.log -b 1000 \
                  -x nointegrity 'tcp 16760' dba $(getDbaPassword) ${ctridx}" 1>>$LOGFILE 2>&1
      done
   done
   setmode $Norm
   handletriggers enabled
   triggersafter=`buildtriggers`
   logstr "   - There are $triggersafter triggers active in your database."
   cat /tmp/soltriggers 1>>$LOGFILE 2>&1
   if [ "$triggersbefore" != "$triggersafter" ];
   then
      textncolor $BoldGreen "Note: #Triggers before is $triggersbefore"
      textncolor $BoldGreen "Note: #Triggers after is $triggersafter"
   fi
   su - solid -c "$solsql -a -e \"admin command 'makecp -s' \" \"tcp 16760\" dba $(getDbaPassword)"
   su - solid -c "$solsql -a -e \"admin command 'status' \" \"tcp 16760\" dba $(getDbaPassword)"
   su - solid -c "$solsql -a -e \"admin command 'shutdown force' \" \"tcp 16760\" dba $(getDbaPassword)"  1>/dev/null 2>&1


   xconvstatus=1
   logstr "[*] Waiting for solid to shutdown."
   while [ $xconvstatus -eq 1 ];
   do
      ps -ef | grep solid | grep -v grep 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         logstr "[*] [${_SELF_}]: Waiting for DB to shutdown"
      else
         textncolor $BoldCyan "[${_SELF_}]: DB has shutdown."
         break;
      fi
      sleep 8
   done
   sync

      #[6]. Bring system to state#3.
   textncolor $BoldCyan "[${_SELF_}]: Bringing system to state#3, on $mynode.`date`"
   if ! srxctrl 3 `remotestate 3`  1>>$LOGFILE 2>&1; then
      logstr "[${_SELF_}]: Cannot bring system to state#3."
      exit $DBRESTOREFAILED
   fi

   switchsolid ${mynode}

   textncolor $BoldCyan "Solid db state :"
   logstr               "    ----------------"
   su - solid -c "RtpSolid -l"

   rm -f $catfile ${catfile}.lst

}

# ---------------------------------------------------------------
# function: migratedb
# args    : None
# description:
#   migrates db for current configuration.
# ---------------------------------------------------------------

migratedb( ) 
{
   logstr "[*] [${_SELF_}]: Migrating db."
   
   export Export8k=${SOLIDHOME}/migrate8k
   export Apps8k=${SOLIDHOME}/apps8k
   export Import8k=${SOLIDHOME}/migrate8knew
   export RtpDb8k=${SOLIDHOME}/RtpDb

   #[1]. First export all the data in current db.

   #<SwitchSolid>
         switchsolid ${mynode}
   #</SwitchSolid>
   {
      rm -rf ${Export8k} ${Import8k} 
      mkdir -p ${Export8k}
      chmod 777  ${Export8k}
   } 

   catfile=/tmp/solcat
   su - solid -c "$solsql -x onlyresults -o $catfile -a \
              -e \"select name from sys_catalogs \" \"tcp 16760\" dba $(getDbaPassword)" 1>/dev/null 2>&1
   cat $catfile | sed '/^$/d' > ${catfile}.lst

   su - solid -c "cd  ${Export8k};$soldd  -xFKAlterTable 'tcp 16760' dba $(getDbaPassword)"
   if [ $? -ne 0 ];
   then
      logstr "[${_SELF_}]: Sorry, Solid schema could not be exported"
      exit $DBRESTOREFAILED
   fi

   #<SolidBug?>
      if [ "$profile" = "integrated" -a "X$(isOSEE)X" = "XfalseX" ];
      then
         fixappsschema ${Export8k}/soldd.sql
         su - solid -c "cd ${Export8k}; $soldd -C opensoa -s symgroupware 'tcp 16760' dba $(getDbaPassword) owners 1>>$LOGFILE 2>&1"
         cat ${Export8k}/OWNERS.sql 2>/dev/null | sed -e 's/"OWNERTYPE" WVARCHAR(255),/"OWNERTYPE" WVARCHAR(255) NOT NULL,/g' \
                                    > ${Export8k}/OWNERS.sql.migrate8k
         su - solid -c "cd ${Export8k}; $soldd -C opensoa -s symgroupware 'tcp 16760' dba $(getDbaPassword) contactstores 1>>$LOGFILE 2>&1"
         cp ${Export8k}/OWNERS.sql.migrate8k ${Export8k}/OWNERS.sql
         rm -f ${Export8k}/OWNERS.sql.migrate8k
      fi
   #</SolidBug?>

   for catidx in `cat ${catfile}.lst`
   do
      textncolor $BoldCyan "Exporting catalog $catidx."
      mkdir -p ${Export8k}/${catidx}
      chmod 777 ${Export8k}/${catidx}
      su - solid -c "cd  ${Export8k}/${catidx}; $solexp -C $catidx 'tcp 16760' dba $(getDbaPassword) \*" 1>/dev/null 2>&1
      if [ $? -ne 0 ];
      then
         logstr "[${_SELF_}]: Sorry, Solid data could not be exported for catlog $catidx"
         exit $DBRESTOREFAILED
      fi
   done

   triggersbefore=`buildtriggers`
   logstr "   - There are $triggersbefore triggers active in your database."
   cat /tmp/soltriggers 1>>$LOGFILE 2>&1
   

   #[2]. Bring system to state#2.
   textncolor $BoldCyan "Bringing system to state#2 : `date`"
   sleep 20
   /unisphere/srx3000/srx/startup/srxctrl 2 `remotestate 2`  1>>$LOGFILE 2>&1
   if [ $? -ne 0 ];
   then
      logstr "[${_SELF_}]: Cannot bring system to state#2."
      exit $DBRESTOREFAILED
   fi
   if [ -f /etc/init.d/symphoniad -a "X$(isOSEE)X" = "XfalseX" ];
   then
      textncolor $BoldCyan "LocalNode: Stopping Symphonia Applications"
      checkappstatus stop local
   fi

   #[3]. Create empty database.
   if ! createemptydb;
   then
      exit $DBRESTOREFAILED
   fi
 
   #<CheckSolidCon>
      textncolor $BoldCyan "Waiting for database to be fully up. `date`"
      while ( true )
      do
         lsof -i :16760 1>/dev/null 2>&1
         if [ $? -eq 0 ];
         then
            break;
         fi
         echo -n "."
         sleep 4
      done
   #</CheckSolidCon>

   #[4]. Migrate the data.
   cp -R ${Export8k} ${Import8k}
   #<SpecialHandleSecurity>
      getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  cf_type  expcftype
      importsecendpoint ${Import8k}/RTPDB/DBA_SECURE_ENDPOINT_T.dat
      cp ${Import8k}/RTPDB/DBA_PACKET_FILTERING_RULE_T.dat $SRCRULES
      rm -f ${Import8k}/RTPDB/DBA_PACKET_FILTERING_RULE_T.dat
      touch ${Import8k}/RTPDB/DBA_PACKET_FILTERING_RULE_T.dat
      chmod 777 ${Import8k}/RTPDB/DBA_PACKET_FILTERING_RULE_T.dat 
   #</SpecialHandleSecurity>
   adjustimportdb

   #[5]. Import it back.
   textncolor $BoldCyan "   - Loading schema." 
   su - solid -c "$solsql -a -e \"admin command 'hsb switch primary' \" \"tcp 16760\" dba $(getDbaPassword)"
   restoresystables
   su - solid -c "$solsql -a 'tcp 16760' dba $(getDbaPassword) ${Export8k}/soldd.sql" 1>>$LOGFILE 2>&1
   #<SolidBug?>
      if [ "$profile" = "integrated" -a "X$(isOSEE)X" = "XfalseX" ];
      then
         su - solid -c "$solsql -a 'tcp 16760' dba $(getDbaPassword) ${Export8k}/OWNERS.sql 1>>$LOGFILE 2>&1"
      fi
   #</SolidBug?>
   
   # We will handle creation of OSV user later on dbExecuter so drop SCHEMA OSVUSER
   #<Drop schema OSVUSER>
   dropuserfile="/tmp/drop_user_schema.sql"
   if osv_version.sh --major compare sys ge V9; 
   then
      {
         echo "drop schema OSVUSER;"
         echo "commit work;"
      } > $dropuserfile
      chmod a+r $dropuserfile
      su - solid -c "$solsql -a 'tcp 16760' dba $(getDbaPassword) $dropuserfile" 1>>$LOGFILE 2>&1
      if [ $? -ne 0 ];
      then
         logstr "[${_SELF_}]: Cannot drop schema OSVUSER."
         exit $DBRESTOREFAILED
      fi

    fi
   #</Drop schema OSVUSER>

   handletriggers disabled
   rm -f ${LOGSOLIDHOME}/solload.log
   touch ${LOGSOLIDHOME}/solload.log
   chmod 777 ${LOGSOLIDHOME}/solload.log
   textncolor $BoldCyan "   - Loading tables."
   setmode $BoldPurple
   for catidx in `cat ${catfile}.lst`
   do
      for ctridx in `ls ${Import8k}/${catidx}/*ctr 2>/dev/null`
      do
         logstr "   - Loading `basename $ctridx .ctr`"
         su - srx -c "cd ${Import8k}/${catidx}; $solload -C $catidx -L ${LOGSOLIDHOME}/solload.log -b 1000 \
                  -x nointegrity 'tcp 16760' dba $(getDbaPassword) ${ctridx}" 1>>$LOGFILE 2>&1
      done
   done
   setmode $Norm
   handletriggers enabled
   triggersafter=`buildtriggers`
   logstr "   - There are $triggersafter triggers active in your database."
   cat /tmp/soltriggers 1>>$LOGFILE 2>&1
   if [ "$triggersbefore" != "$triggersafter" ];
   then
      textncolor $BoldGreen "Note: #Triggers before is $triggersbefore"
      textncolor $BoldGreen "Note: #Triggers after is $triggersafter"
   fi
   su - solid -c "$solsql -a -e \"admin command 'makecp -s' \" \"tcp 16760\" dba $(getDbaPassword)"
   su - solid -c "$solsql -a -e \"admin command 'status' \" \"tcp 16760\" dba $(getDbaPassword)"
   su - solid -c "$solsql -a -e \"admin command 'shutdown force' \" \"tcp 16760\" dba $(getDbaPassword)"  1>/dev/null 2>&1

   xconvstatus=1
   logstr "[*] Waiting for solid to shutdown."
   while [ $xconvstatus -eq 1 ];
   do
      ps -ef | grep solid | grep -v grep 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         logstr "[*] [${_SELF_}]: Waiting for DB to shutdown"
      else
         textncolor $BoldCyan "[${_SELF_}]: DB has shutdown."
         break;
      fi
      sleep 8
   done
   sync

   if [ "$testbed" = "cluster" ];
   then
      echo "Displaying solid files, when system at #2."
      ls -l ${RtpDb8k}
      rscp -p ${RtpDb8k}/sol*.db $sechost:${RtpDb8k}
      rssh $sechost "rm -f ${RtpDb8k}/sol*.log; ls -l ${RtpDb8k}"      
   fi  1>>$LOGFILE 2>&1


   #[6]. Bring system to state#3.
   textncolor $BoldCyan "[${_SELF_}]: Bringing system to state#3, on $mynode.`date`"
   if ! srxctrl 3 `remotestate 3`  1>>$LOGFILE 2>&1; then
      logstr "[${_SELF_}]: Cannot bring system to state#3."
      exit $DBRESTOREFAILED
   fi

   if [ "$testbed" = "cluster" ];
   then
      echo "Displaying solid files, when system at #3."
      ls -l ${RtpDb8k}
      rssh $sechost "ls -l ${RtpDb8k}"      
   fi  1>>$LOGFILE 2>&1

   switchsolid ${mynode}

   textncolor $BoldCyan "Solid db state :"
   logstr               "    ----------------"
   su - solid -c "RtpSolid -l"

   rm -f $catfile ${catfile}.lst

}



# ---------------------------------------------------------------
# function: copyexports
# args    : None
# description:
#   copy remote nodes exported data.
# ---------------------------------------------------------------

copyexports( )
{
      if [ "$testbed" = "cluster" ];
      then

         #[1]. First try the cluster ip
     
         partnerdata=$EXPORTBKDIR/${othernode}
         rm -rf $partnerdata
         sshcip=$othercip
         rscp -p -r -o ConnectTimeout=8 root@${othercip}:$partnerdata  $EXPORTBKDIR/.
         sshstatus=$?
     
         #[2]. Next try the logical name
  
         if [ $sshstatus -ne 0 ];
         then
            rm -rf $partnerdata
            sshcip=$othercipname
            rscp -p -r -o ConnectTimeout=8 root@${othercipname}:$partnerdata  $EXPORTBKDIR/.
            sshstatus=$?
         fi
 
         #[3]. Last try the hostname via admin network.

         if [ $sshstatus -ne 0 ];
         then
            rm -rf $partnerdata
            sshcip=$othernode
            rscp -p -r root@${othernode}:$partnerdata  $EXPORTBKDIR/.
            sshstatus=$?
         fi
      
         if [ $sshstatus -ne 0 ];
         then
            textncolor $BoldRed "Sorry, cannot distribute exported data. Check network."
            exit $FAIL
         fi

      fi
}

# ---------------------------------------------------------------
# function: checkremote
# args    : None
# description:
#   checks if remote node has the same level as current node.
#   Also this function propagates the local action (import,migrate) to remote
# ---------------------------------------------------------------

checkremote( ) 
{
   remoteopt="$*"
   if [ "$RECOVER8k" = "true" -o "$LIVE8kUPGRADE" = "true" ];
   then
      return 0
   fi

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

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

   if [ "$mynode" = "$primhost" ];
   then
      othernode=$sechost
      othercip=$seccip
      othercipname="clusternode2-priv"
      #<SwitchSolid>
         if [ "$CLUSTERIPXCHANGE" != "true" ];
         then
            switchsolid ${mynode}
         fi
      #</SwitchSolid>
   else
      othernode=$primhost
      othercip=$primcip
      othercipname="clusternode1-priv"
   fi

   #<CheckRtpSolid>
      if [ "$CLUSTERIPXCHANGE" != "true" ];
      then
         su - srx -c "RtpSolid -c" 2>/dev/null
         if [ $? -ne 0 ];
         then
            logstr "[${_SELF_}]: RtpSolid check of database failed."
            exit $DBCHECKFAILED
         fi
      fi
   #</CheckRtpSolid>

   cat /etc/fstab | grep "/home" | grep -v "^/dev/sda" | grep -q primary
   if [ $? -eq 0 ];
   then
      syncpart="primary"
      syncother="secondary"
   else
      syncpart="secondary"
      syncother="primary"
   fi
   rm -f /tmp/${othernode}.fstab
   echo "   - Checking for mount<$syncpart> on partner node<${othernode}>."
   while ( true )
   do
      #[1]. First try the cluster ip
      
      sshcip=$othercip
      rssh ${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
         rssh ${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
         rssh ${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 [ "$singleimaged" = "false" ];
         then
            if [ $status -ne 0 ];
            then
               echo "-"
               textncolor $BoldPurple "Interesting, Both the nodes are not installed on same <$syncpart> side."
               grep -q $syncother /tmp/${othernode}.fstab
               status=$?
            fi
         fi
         if [ $status -eq 0 -o "$singleimaged" = "true" ];
         then
            logstr "   - The mounts are ok for current operation."
            if [ "$mynode" = "$primhost" ];
            then
               logstr ""
               rssh ${sshcip} -o ConnectTimeout=8 "${_SELF_} ${remoteopt}"
               if [ $? -ne 0 ];
               then
                  if [ "$testbed" = "$exptestbed" -o "$exptestbed" = "" ];
                  then
                     logstr "[${_SELF_}]: Sorry, cannot $remoteopt remote node<$othernode>."
                     exit $REMOTEOPTFAILED
                  else
                     logstr "[${_SELF_}]: Nothing to $remoteopt remote node<$othernode>."
                     logstr "         : scenario $exptestbed -> $testbed."
                  fi
               fi
               logstr ""
            fi
            break;
         fi
         echo -n "."
      fi
      if [ "$CHECK4CLSTATUS" = "true" ];
      then
         exit $REMOTEOPTFAILED
      fi
      sleep 8
   done
}


# ---------------------------------------------------------------
# function: removertpfromdb
# args    : None
# description:
#   removes rtp from db.
# ---------------------------------------------------------------

removertpfromdb( )
{
   schemafile=/tmp/schema
   delschemafile=/tmp/delschema
   droptablesfile=/tmp/droptables
   dropschemafile=/tmp/dropschema
   rm -f $schemafile $delschemafile $droptablesfile $dropschemafile
   su - solid -c "$solsql -x onlyresults -o $schemafile -a \
      -e \"select table_name,table_schema,table_catalog from sys_tables \" \"tcp 16760\" dba $(getDbaPassword)" 1>/dev/null 2>&1
   cat $schemafile  | grep -v "^$" |  awk '{ print $1":"$2":"$3 }' > ${schemafile}.delim
   setmode $BoldPurple
   for schemaidx in `cat ${schemafile}.delim`
   do 
      tablename=`echo $schemaidx | awk -F':' '{ print $1 }'`
      tableschema=`echo $schemaidx | awk -F':' '{ print $2 }'`
      tablecatalog=`echo $schemaidx | awk -F':' '{ print $3 }'`
      strippedtableschema=${tableschema:0:8}
      if [ "$strippedtableschema" = "RTP_USER" ];
      then
          echo "${tablecatalog}:${tableschema}" >> $delschemafile
          logstr "   - Dropping table $tablename"
          {
             echo "set catalog ${tablecatalog};"
             echo "truncate table $tablename;"
             echo "commit work;"
             echo "drop table $tablename cascade constraints;"
             echo "commit work;"
          } > $droptablesfile
          su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $droptablesfile" 1>>$LOGFILE 2>&1
      fi
   done
   setmode $Norm

   if [ -f $delschemafile ];
   then
      cat $delschemafile | sort | uniq > ${delschemafile}.uniq
      setmode $BoldPurple
      for schemaidx in `cat ${delschemafile}.uniq`
      do
         tablecatalog=`echo $schemaidx | awk -F':' '{ print $1 }'`
         tableschema=`echo $schemaidx | awk -F':' '{ print $2 }'`
         logstr "   - Dropping Schema $tableschema"
         {
            echo "set catalog $tablecatalog;"
            echo "drop schema $tableschema cascade;"
            echo "commit work;"
         } > $dropschemafile
         su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $dropschemafile" 1>>$LOGFILE 2>&1
      done
      setmode $Norm
   fi
   rm -f $schemafile $delschemafile
}

# ---------------------------------------------------------------
# function: savesystables
# args    : None
# description:
#   saves sys users table from db.
# ---------------------------------------------------------------

savesystables( )
{
   setmode $BoldPurple
   logstr "   - Saving system tables."
   Sys8k=${SOLIDHOME}/sys8k
   mkdir -p $Sys8k
   chmod 777 $Sys8k
   su - solid -c "cd $Sys8k; $solexp 'tcp 16760' dba $(getDbaPassword) sys_users" 1>/dev/null 2>&1
   setmode $Norm
}

# ---------------------------------------------------------------
# function: restoresystables
# args    : None
# description:
#   restore sys users table from db.
# ---------------------------------------------------------------

restoresystables( )
{
   setmode $BoldPurple
   export Sys8k=${SOLIDHOME}/sys8k
   #for sysidx in `ls $Sys8k/*.ctr`
   #do
   #   logstr "   - Loading `basename $sysidx .ctr`"
   #   su - srx -c "cd ${Sys8k}; $solload -L ${LOGSOLIDHOME}/solload.log -b 1000 \
   #            -x nointegrity 'tcp 16760' dba $(getDbaPassword) ${sysidx}" 1>>$LOGFILE 2>&1
   #done
   createuserfile=/tmp/user.sql
   if [ "X$(isOSEE)X" = "XfalseX" ]
   then
      TESTBED=$(cfgread test_bed)
      if [ "$TESTBED" != "cluster" ]
      then
         {
             echo "create user SYMPHONIA identified by xxxx;"
             echo "grant SYS_ADMIN_ROLE to SYMPHONIA ;"
             echo "commit work;"
         } > $createuserfile
    
         chmod a+r $createuserfile
         su - solid -c "$solsql -a 'tcp 16760' dba $(getDbaPassword) $createuserfile" 1>>$LOGFILE 2>&1
         if [ $? -ne 0 ];
         then
           logstr "[${_SELF_}]: Cannot create user symphonia."
           exit $DBRESTOREFAILED
        fi
      fi
   fi
   if osv_version.sh --major compare sys ge V9; 
   then
      {
         echo "drop schema OSVUSER;"
         echo "commit work;"
      } > $createuserfile
      chmod a+r $createuserfile
      su - solid -c "$solsql -a 'tcp 16760' dba $(getDbaPassword) $createuserfile" 1>>$LOGFILE 2>&1
      if [ $? -ne 0 ];
      then
         logstr "[${_SELF_}]: Cannot drop schema OSVUSER."
         exit $DBRESTOREFAILED
      fi

    fi

   setmode $Norm
   rm -rf $Sys8k $createuserfile
}

# ---------------------------------------------------------------
# function: saveappsfromdb
# args    : None
# description:
#   saves applications from db.
# ---------------------------------------------------------------

saveappsfromdb( )
{
   schemafile=/tmp/schema
   rm -f $schemafile  ${schemafile}.delim
   export Apps8k=${SOLIDHOME}/apps8k
   rm -rf ${Apps8k}
   mkdir -p ${Apps8k}
   chmod 777 ${Apps8k}
   su - solid -c "$solsql -x onlyresults -o $schemafile -a \
      -e \"select table_name,table_schema,table_catalog from sys_tables \" \"tcp 16760\" dba $(getDbaPassword)" 1>/dev/null 2>&1
   cat $schemafile  | grep -v "^$" |  awk '{ print $1":"$2":"$3 }' > ${schemafile}.delim
   setmode $BoldPurple
   for schemaidx in `cat ${schemafile}.delim`
   do 
      tablename=`echo $schemaidx | awk -F':' '{ print $1 }'`
      tableschema=`echo $schemaidx | awk -F':' '{ print $2 }'`
      tablecatalog=`echo $schemaidx | awk -F':' '{ print $3 }'`
      strippedtableschema=${tableschema:0:3}
      strippedtablename=${tablename:0:3}
      catdir=${Apps8k}/${tablecatalog}
      if [ "$strippedtableschema" = "SYM" -o "$strippedtableschema" = "DSA" -o \
           "$strippedtableschema" = "RG8" -o "$strippedtableschema" = "DLS" -o \
           "$tablecatalog" = "DLSDB"      -o "$strippedtablename" = "DLS"   -o \
           "$tablecatalog" = "OPENSOA"                                         \
         ];
      then
          logstr "   - Saving table $tablename"
          su - solid -c "mkdir -p ${catdir}; cd  ${catdir}; $solexp -C $tablecatalog -s $tableschema 'tcp 16760' dba $(getDbaPassword) $tablename" 1>>$LOGFILE 2>&1
          if [ $? -ne 0 ];
          then
            logstr "[${_SELF_}]: Cannot save<$tablecatalog/$tableschema/$tablename>."
            exit $DBRESTOREFAILED
          fi
      fi
   done
   #<SaveDBA4Apps>
   dbaapps="\
      ADMIN_SETTINGS
      DSABGDATA
      DSABGLDLS
      EXTERNALWEBGUI
      EX_SEC_GROUP
      EX_SEC_MEMBER
      EX_SEC_MEMBER_LINES
      EX_SEC_REL
      HIPATH8000
      JOBIDDATA
      REMARKS_DATA
      REMARKS_ID_MAPPING
      RG2700CONNECTIONINFO
      RS_ACTIVE_RULESETS
      RS_CATEGORY_TABLE
      RS_COMRESPONSE
      RS_GROUPWARE_STATUS
      RS_LOGIN_TABLE
      RS_MBXALIAS_TABLE
      RS_MEDIA_FILTERS
      RS_RULEBOOKS
      RS_SWITCHBACK_TABLE
      SCHEMA_VERSION
      SUBSCRIBERTEMPLATE
   "

   catdir=${Apps8k}/RTPDB
   tablecatalog=RTPDB
   tableschema=DBA
   for dbappsidx in $dbaapps
   do
       logstr "   - Saving table $dbappsidx"
       su - solid -c "mkdir -p ${catdir}; cd  ${catdir}; $solexp -C $tablecatalog -s $tableschema 'tcp 16760' dba $(getDbaPassword) $dbappsidx" 1>/dev/null 2>&1
       if [ $? -ne 0 ];
       then
            logstr "   - Skipping $tablecatalog/$tableschema/$dbappsidx."
       fi
      
   done
   
   #</SaveDBA4Apps>
   setmode $Norm
   rm -f $schemafile  ${schemafile}.delim

}

cleanappsfromdb( )
{
   for appsidx in `find $Apps8k`
   do
      if [ -d $appsidx ];
      then
         continue
      else
         baseappsidx=`basename $appsidx`
         find ${SOLIDHOME}/migrate8knew -name ${baseappsidx} -exec rm -f {} \;
         logstr "   - Removed ${baseappsidx}"
      fi
   done
}

restoreappsfromdb( )
{
   logstr "   - Restoring apps from ${Apps8k}."
   #<MigrateHost&IP>
      if [ "$mynode" = "$primhost" ];
      then
         appnodename="`cfgread node_1_name`" 
         expappnodename="`fcfgread ${EXPORTDIR}/etc/hiq8000/node.cfg node_1_name`"
         appnodeip="`cfgread node_1_ip`" 
         expappnodeip="`fcfgread ${EXPORTDIR}/etc/hiq8000/node.cfg node_1_ip`"
      else
         appnodename="`cfgread node_2_name`" 
         expappnodename="`fcfgread ${EXPORTDIR}/etc/hiq8000/node.cfg node_2_name`"
         appnodeip="`cfgread node_2_ip`" 
         expappnodeip="`fcfgread ${EXPORTDIR}/etc/hiq8000/node.cfg node_2_ip`"
      fi
      dbfiles="`find ${Apps8k}`"
      for idx in $dbfiles
      do
         if [ -f $idx ];
         then
            logstr "   - Migrating `basename $idx`" 
            cat $idx | sed -e "s/'${expappnodename}'/'${appnodename}'/g" \
                           -e "s/${expappnodeip}/${appnodeip}/g"         \
            > ${idx}.migrate 
            cp -f  ${idx}.migrate $idx
            chmod a+r $idx
            rm -f ${idx}.migrate
         fi 
      done
   #</MigrateHost&IP>
   for appidx in `ls $Apps8k`
   do
      fqdir=$Apps8k/$appidx
      if [ -d "$fqdir" -a "$appidx" != "." -a "$appidx" != ".." ];
      then
         mkdir -p ${Import8k}/${appidx}
         chmod 777 ${Import8k}/${appidx}
         mv -f $fqdir/* ${Import8k}/${appidx}
      fi
   done
   rm -rf $Apps8k
}

# ---------------------------------------------------------------
# function: oscexport
# args    : None
# description:
#   logic for osc upgrade or migration.
# ---------------------------------------------------------------

oscexport( )
{
   textncolor $BoldCyan "Exporting applications data on <$mynode>."
   echo -n "   - Detecting rsync : "
   rpm -q rsync
   if [ $? -eq 0 ];
   then
      expcount=0
      while ( true )
      do
         rsync -cavz --whole-file                                                       \
                     --exclude=$APPSDIR/sw_repository                                   \
                     --exclude=$APPSDIR/share                                           \
                     --exclude=$APPSDIR/*/dist*/*                                       \
                     --exclude=$APPSDIR/.java/*                                         \
                     --exclude=$APPSDIR/assistant/war_files/*                           \
                     --exclude=$APPSDIR/HiPathCA/backups/*                              \
                     --exclude=$APPSDIR/HiPathCA/distribution/*                         \
                     --exclude=$APPSDIR/clm/Trace/*                                     \
                     --exclude=$APPSDIR/clm/jre/*                                       \
                     --exclude=$APPSDIR/Loquendo/*                                      \
                     --exclude=$APPSDIR/HiPathCA/logs/*                                 \
                     --exclude=$APPSDIR/HiPathCA/installlogs/*                          \
                     --exclude=$APPSDIR/clm/ApacheTomcat/logs/*                         \
                     --exclude=$APPSDIR/mediaserver/application_host/bin/nativeRTPunit* \
                     --exclude=$APPSDIR/var/osgi/runtime/*                              \
                     --exclude=*.jar                                                    \
                     --exclude=*.zip                                                    \
                     --exclude=*.wav                                                    \
                     --exclude=*.gz                                                     \
                     --exclude=*.bin                                                    \
                     --exclude=*.war                                                    \
                     --exclude=*.class                                                  \
                     --exclude=*.pdf                                                    \
                     --exclude=*.gif                                                    \
                     --exclude=*.png                                                    \
                     --exclude=*.js                                                     \
                     --exclude=*.mkv                                                    \
                     --exclude=*.html                                                   \
                     --exclude=*.wsdl                                                   \
                     --exclude=*.so                                                     \
                     --exclude=*.so.*                                                   \
                     --exclude=*.exe                                                    \
                     --exclude=core.*                                                   \
                     --exclude=javacore.*                                               \
                     --exclude=heapdump*                                                \
                     --exclude=core.*                                                   \
                     /$APPSDIR ${EXPORTDIR} 1>>$LOGFILE 2>&1
         if [ $? -ne 0 ];
         then
            if [ $expcount -ge 8 ];
            then
               textncolor $BoldRed "Failed to export applications data."
               exit $FAIL
            else
               echo -n "+"
            fi
         else
            if [ $expcount -ne 0 ];
            then
               echo ""
            fi
            break;
         fi
         expcount=`expr $expcount + 1`
      done
   else
       find $APPSDIR  ! -regex "${APPSDIR}/sw_repository.*"                                 \
                      ! -regex "${APPSDIR}/share.*"                                         \
                      ! -regex "${APPSDIR}/.java/*"                                         \
                      ! -regex "${APPSDIR}/HiPathCA/backups.*"                              \
                      ! -regex "${APPSDIR}/HiPathCA/dist.*"                                 \
                      ! -regex "${APPSDIR}/Loquendo.*"                                      \
                      ! -regex "${APPSDIR}/clm/jre.*"                                       \
                      ! -regex "${APPSDIR}/clm/Trace.*"                                     \
                      ! -regex "${APPSDIR}/HiPathCA/logs/*"                                 \
                      ! -regex "${APPSDIR}/HiPathCA/installlogs/*"                          \
                      ! -regex "${APPSDIR}/clm/ApacheTomcat/logs/*"                         \
                      ! -regex "${APPSDIR}/mediaserver/application_host/bin/nativeRTPunit*" \
                      ! -regex "${APPSDIR}/var/osgi/runtime/*"                              \
                      ! -name "*.jar"                                                       \
                      ! -name "*.zip"                                                       \
                      ! -name "*.wav"                                                       \
                      ! -name "*.gz"                                                        \
                      ! -name "*.bin"                                                       \
                      ! -name "*.war"                                                       \
                      ! -name "*.class"                                                     \
                      ! -name "*.pdf"                                                       \
                      ! -name "*.gif"                                                       \
                      ! -name "*.png"                                                       \
                      ! -name "*.js"                                                        \
                      ! -name "*.mkv"                                                       \
                      ! -name "*.html"                                                      \
                      ! -name "*.wsdl"                                                      \
                      ! -name "*.so"                                                        \
                      ! -name "*.so.*"                                                      \
                      ! -name "*.exe"                                                       \
                      ! -name "core.*"                                                      \
                      ! -name "javacore.*"                                                  \
                      ! -name "core.*"                                                      \
                      ! -name "heapdump*"                                                   \
                      | cpio -pdmv ${EXPORTDIR} 1>>$LOGFILE 2>&1
   fi
   {
    #<UserRes>
      cp -R -p --parents                                                                                          \
      /enterprise/mediaserver/application_host/providers/tomcat/tomcat-home/webapps/voiceportal/res/userresources \
      ${EXPORTDIR}
      cp -R -p --parents /enterprise/mediaserver/application_host/deployment/userresources/res ${EXPORTDIR}
      cp -R -p --parents /enterprise/share/tomcat/webapps/management/rebranding ${EXPORTDIR}
    #</UserRes>
    #<Certs>
       cp -p --parents /enterprise/assistant/data/ssl.jar ${EXPORTDIR}
    #</Certs>
    #<BCom>
       cp -p /enterprise/scs_bcom/lib/osa-bcomssl-current.jar ${EXPORTDIR}
    #</BCom
    #<Keytool>
       exportKeyTool
    #</Keytool>

    # Solid symphonia schema and data
    if [ "${UC_DB_EXPORT}X" = "trueX" ]
    then
       source /etc/sysconfig/siemens/symphonia
       if [ -x ${SYMPHONIA_HOME}/servicetools/install/bin/exportUCDB.sh ]
       then
          UC_DB_EXPORT_BIN=${SYMPHONIA_HOME}/servicetools/install/bin/exportUCDB.sh
       else
          UC_DB_EXPORT_BIN=/usr/bin/exportUCDB.sh
       fi
     
       mkdir -p ${EXPORTDIR}/ucdbschema
       ${UC_DB_EXPORT_BIN} ${EXPORTDIR}/ucdbschema
       if [ $? -ne 0 ]
       then
          textncolor $BoldRed "Failed to export UC DB schema and data through ${UC_DB_EXPORT_BIN}."
          exit $FAIL
       fi
    fi

   } 1>>$LOGFILE 2>&1
   RespCfg=/enterprise/servicetools/install/conf/responsefile.txt
   if [ -f $RespCfg ];
   then
      comstr="`cat $RespCfg | grep SI_COMMUNITY_NAME | awk -F'=' '{ print $2 }'`"
   fi
   textncolor $BoldPurple "Note:Please note your current community name."
   logstr "   - $comstr."

}

# ---------------------------------------------------------------
# function: checkappstatus
# args    : None
# description:
#   check every instance of start stop sym failure.
# ---------------------------------------------------------------

checkappstatus( )
{
   appcmd=$1
   appmode=$2
   if [ "$LOGFILE" != "" ];
   then
      if [ "$appmode" = "local" ];
      then
         /etc/init.d/symphoniad $appcmd 1>>$LOGFILE 2>&1
      else
         rssh $othernode "/etc/init.d/symphoniad $appcmd 1>>$LOGFILE 2>&1"
      fi
   else
      if [ "$appmode" = "local" ];
      then
         /etc/init.d/symphoniad $appcmd 
      else
         rssh $othernode "/etc/init.d/symphoniad $appcmd"
      fi
   fi
   appstatus=$?
   if [ $appstatus -ne 0 ];
   then
      textncolor $BoldRed "Note: Application could not $appcmd(exit=$appstatus)."
      if [ "$LOGFILE" != "" ];
      then
         echo "Note: Application could not $appcmd(exit=$appstatus)." >> $LOGFILE
      fi
      exit $SYMSTFAILED
   fi
}

# ---------------------------------------------------------------
# function: offboardoscimport
# args    : None
# description:
#   logic for osc upgrade or migration.
# ---------------------------------------------------------------

offboardoscimport( )
{
   if [ -f ${APPSDIR}/servicetools/install/bin/customizeImage.sh ];
   then
      checkappstatus stop local
      AppDataDir="${EXPORTDIR}/enterprise"
      APPSFAIL=false
      if [ -f ${AppDataDir}/servicetools/install/conf/responsefile.txt ];
      then
         ResponseCfgDetected=true
      else
         ResponseCfgDetected=false
      fi
      textncolor $BoldPurple "$mynode :-"
      textncolor $BoldPurple "Stopping solid."
      sh /etc/init.d/solid.sh stop 1>>$LOGFILE 2>&1
      textncolor $BoldPurple "Restoring applications database."
      pushd ${APPSDIR}/solid/RtpDb
      tar -xvf ${EXPORTDIR}/backup_all.tar
      textncolor $BoldPurple "Starting solid."
      #Regarding OSV-18739:
      # This would probably need updating regarding activating diagnostics, but is a single-case of
      # an executable that doesn't seem to exist any more. This is probably dead-code to be removed
      # at some point to reduce tech-debt
      sh /etc/init.d/solid.sh start 1>>$LOGFILE 2>&1
      popd 1>/dev/null
      su - solid -c "solid -x convert -C RtpDb -c ${APPSDIR}/solid/RtpDb" 1>/dev/null 2>&1
      if [ $? -ne 0 ];
      then
         textncolor $BoldCyan "[${_SELF_}]: Db conversion failed."
         exit $DBCONVERTFAILED
      fi
      xconvstatus=1
      logstr "[*] Waiting for solid conversion to finish."
      while [ $xconvstatus -eq 1 ];
      do
         ps -ef | grep solid | grep -v grep | grep -q convert
         if [ $? -eq 0 ];
         then
            logstr "[*] [${_SELF_}]: Waiting for DB conversion to finish"
         else
            textncolor $BoldCyan "[${_SELF_}]: Conversion of DB is finished."
            break;
         fi
         sleep 8
      done
      su - solid -c "$solsql -a -e \"drop schema RTP_USER_40 cascade\" \"tcp 16760\" dba $(getDbaPassword)" 1>>$LOGFILE 2>&1
      dropalarms
      textncolor $BoldCyan "Reorganizing solid db. This may take some time."
      su - solid -c "solid -x reorganize" >> $LOGFILE 2>&1
      sync

      {
         echo "Dumping ulimits for user root."
         echo "------------------------------"
         ulimit -a 
         echo "Dumping ulimits for user srx."
         echo "-----------------------------"
         su - srx -c "ulimit -a"
         echo "Dumping ulimits for user solid."
         echo "-------------------------------"
         su - solid -c "ulimit -a"
      } >> $LOGFILE 2>&1

      textncolor $BoldCyan "Locking Applications data."
      ${APPSDIR}/servicetools/install/bin/customizeImage.sh  lock 1>>$LOGFILE 2>&1
      if [ "$ResponseCfgDetected" = "true" ];
      then
         logstr "   - Upgrading Applications with backed up data."
         ${APPSDIR}/servicetools/install/bin/customizeImage.sh  upgrade $AppDataDir 1>>$LOGFILE 2>&1
         if [ $? -ne 0 ]; 
         then
            APPSFAIL=true
            textncolor $BoldRed "Note: Application upgrade failed. Check /log/prepare8k.log for details."
            textncolor $BoldRed "    : This needs to be investigated by applications team. Applications are locked."
            textncolor $BoldRed "    : The upgrade itself will continue."
            if [ "$SYSIMPORT" = "true" ];
            then
               textncolor $BoldRed "Hint#1: If application data need not be preserved, rerun import8k -noapps."
            else
               textncolor $BoldRed "Hint#1: If application data need not be preserved, rerun migrate8k -noapps."
            fi
            textncolor $BoldRed "Hint#2: At prompt type 'n' to destroy application data."
            textncolor $BoldRed "Hint#3: Reinstall applications like fresh install."
            clearstdin
            echo -n "Please press enter to ackowlege this error : "
            zanswer="`quietread yes`"
         fi
      else
         logstr "   - Upgrading Applications as fresh install."
         ${APPSDIR}/servicetools/install/bin/installlib.sh persistence.runDBInstaller.all -Dcommand=update  1>>$LOGFILE 2>&1
      fi
      if [ "$APPSFAIL" != "true" ];
      then
         textncolor $BoldCyan "Unlocking Apllications data."
         ${APPSDIR}/servicetools/install/bin/customizeImage.sh  unlock 1>>$LOGFILE 2>&1
         checkappstatus start local
      fi
      #<WorkAround4Apps>
            ${APPSDIR}/servicetools/install/bin/installlib.sh installplugins.execute \
                   -Dinstallplugin.name=mgmtportalinstall -Dinstallplugin.action=reconfigure 1>>$LOGFILE 2>&1
      #</WorkAround4Apps>
   fi
}

# ---------------------------------------------------------------
# function: oscimport
# args    : None
# description:
#   logic for osc upgrade or migration.
# ---------------------------------------------------------------

oscimport( )
{
   clearstdin
   #<ApplicationEnv>
      if [ -f /etc/sysconfig/siemens/symphonia ];
      then
         source  /etc/sysconfig/siemens/symphonia
      fi
   #<ApplicationEnv>

   #<Certs>
   # Jira OSV-1080: If replaceSecureSocketFactory.sh is delivered to the system use it to upgrade
   # SSL Socket factories, else just perform a static logic.
   local replaceSSLFactory="/enterprise/assistant/scripts/replaceSecureSocketFactory.sh" 
   if [ -x "${replaceSSLFactory}" ] # if executable found
   then
       ${replaceSSLFactory} "${EXPORTDIR}"
   else # ... perform static logic
       # update the classes of existing ssl.jar
       if [ -f ${EXPORTDIR}/enterprise/assistant/data/ssl.jar ]
	   then
           unzip ${EXPORTDIR}/enterprise/assistant/data/ssl.jar "*.*" -d /tmp/sslExport/
		       
           if [ -f /enterprise/assistant/data/ssl.jar ]
		   then
               echo "Copying contents of original ssl.jar"        
               unzip /enterprise/assistant/data/ssl.jar "*.*" -d /tmp/sslOrigin/
               rm -rf /tmp/sslExport/com/siemens/dsa/hipath8000facade/ssl/*
               echo "Updating class files of ssl.jar"
               cp /tmp/sslOrigin/com/siemens/dsa/hipath8000facade/ssl/* /tmp/sslExport/com/siemens/dsa/hipath8000facade/ssl/
           fi

           echo "Creating updated ssl.jar"
        
           pushd /tmp/sslExport
           zip -r /tmp/ssl.jar . -i \*.*

           echo "Overwriting ssl.jar"
           mv /tmp/ssl.jar /enterprise/assistant/data/ssl.jar
           chown sym:sym /enterprise/assistant/data/ssl.jar
           chmod 644 /enterprise/assistant/data/ssl.jar
           popd
           # clean up
           rm -rf /tmp/sslOrigin
           rm -rf /tmp/sslExport
       fi
   fi 
   #</Certs>

   #<ApplicationCustomization>
      if [ -f ${APPSDIR}/servicetools/install/bin/customizeImage.sh ];
      then
         if [ "$Restore8k" = "true" ];
         then
           AppDataDir=""
         else
           AppDataDir="${EXPORTDIR}/enterprise"
         fi
	 APPSFAIL=false
         if [ -f ${AppDataDir}/servicetools/install/conf/responsefile.txt ];
         then
            ResponseCfgDetected=true
         else
            ResponseCfgDetected=false
         fi
         #<PrimNode>
         if [ "$mynode" = "$primhost" ];
         then
            textncolor $BoldPurple   "$mynode :-"
            textncolor $BoldCyan "Stopping symphonia applications."
            checkappstatus stop local
	    textncolor $BoldCyan "Locking Applications data."
            ${APPSDIR}/servicetools/install/bin/customizeImage.sh  lock 1>>$LOGFILE 2>&1
            if [ "$ResponseCfgDetected" = "true" ];
            then
               textncolor $BoldCyan "Upgrading Applications with backed up data."
               ${APPSDIR}/servicetools/install/bin/customizeImage.sh  upgrade $AppDataDir 1>>$LOGFILE 2>&1
               if [ $? -ne 0 ]; 
               then
	          APPSFAIL=true
                  textncolor $BoldRed "Note: Application upgrade failed. Check /log/prepare8k.log for details."
                  textncolor $BoldRed "    : This needs to be investigated by applications. Applications are locked."
                  textncolor $BoldRed "    : Do not use applications unless this is resolved."
                  textncolor $BoldRed "    : The upgrade itself will continue."
                  if [ "$SYSIMPORT" = "true" ];
                  then
                     textncolor $BoldRed "Hint#1: If the application data need not be preserved, rerun import8k -noapps."
                  else
                     textncolor $BoldRed "Hint#1: If the application data need not be preserved, rerun migrate8k -noapps."
                  fi
                  textncolor $BoldRed "Hint#2: At prompt type 'n' to destroy application data."
                  textncolor $BoldRed "Hint#3: Reinstall applications like fresh install."
                  clearstdin
                  echo -n "Please press enter to ackowlege this error : "
                  zanswer="`quietread yes`"
               fi
            else
               textncolor $BoldCyan "Upgrading Applications as fresh install."
               {
                  ${APPSDIR}/servicetools/install/bin/installlib.sh persistence.runDBInstaller.all -Dcommand=update  
                  ${APPSDIR}/assistant/scripts/image_upgrade.sh upgrade
               } 1>>$LOGFILE 2>&1
            fi
	    if [ "$APPSFAIL" != "true" ];
      	    then
               textncolor $BoldCyan "Unlocking Apllications data."
               ${APPSDIR}/servicetools/install/bin/customizeImage.sh  unlock 1>>$LOGFILE 2>&1
            fi
	    #<WorkAroundf4Apps>
               ${APPSDIR}/servicetools/install/bin/installlib.sh installplugins.execute \
                      -Dinstallplugin.name=mgmtportalinstall -Dinstallplugin.action=reconfigure 1>>$LOGFILE 2>&1
            #</WorkAroundf4Apps>
         fi
         if [ "$testbed" = "cluster" ];
         then
            if [ -f /log/osgi.log ];
            then
              echo > /log/osgi.log
            fi
            checkappstatus start local
            textncolor $BoldPurple "Symphonia applications starting."
            while ( true )
            do
               grep -qi "Start processing all bundles done" /log/osgi.log 2>/dev/null
               if [ $? -eq 0 ];
               then
                  break;
               fi
               sleep 4
            done
            textncolor $BoldCyan "Symphonia applications started."

            textncolor $BoldPurple "$othernode :-"
            textncolor $BoldCyan "Stopping symphonia applications."
            checkappstatus stop remote
	    textncolor $BoldCyan "Locking Applications data."
            rssh $othernode "${APPSDIR}/servicetools/install/bin/customizeImage.sh  lock 1>>$LOGFILE 2>&1"
            if [ "$ResponseCfgDetected" = "true" ];
            then
               textncolor $BoldCyan "Upgrading Applications with backed up data."
               rssh $othernode "${APPSDIR}/servicetools/install/bin/customizeImage.sh  upgrade $AppDataDir 1>>$LOGFILE 2>&1"
               if [ $? -ne 0 ]; 
               then
                  textncolor $BoldRed "Note: Application upgrade failed. Check /log/prepare8k.log for details."
                  textncolor $BoldRed "    : This needs to be investigated by applications."
                  textncolor $BoldRed "    : Do not use applications unless this is resolved."
                  textncolor $BoldRed "    : The upgrade itself will continue."
                  clearstdin
                  echo -n "Please press enter to ackowlege this error : "
                  zanswer="`quietread yes`"
               fi
            else
               textncolor $BoldCyan "Upgrading Applications as fresh install."
               rssh $othernode "${APPSDIR}/servicetools/install/bin/installlib.sh \
                              persistence.runDBInstaller.all -Dcommand=update $AppDataDir 1>>$LOGFILE 2>&1"
            fi
            textncolor $BoldCyan "Unlocking Applications data."
            rssh $othernode "${APPSDIR}/servicetools/install/bin/customizeImage.sh  unlock 1>>$LOGFILE 2>&1"
            #<WorkArounf4Apps>
               rssh $othernode "${APPSDIR}/servicetools/install/bin/installlib.sh installplugins.execute \
                      -Dinstallplugin.name=mgmtportalinstall -Dinstallplugin.action=reconfigure 1>>$LOGFILE 2>&1"
            #</WorkArounf4Apps>
            textncolor $BoldPurple "Symphonia applications stopping."
            checkappstatus stop local
         fi
         #</PrimNode>
      fi
   #<ApplicationCustomization>

   #<SynSymphiniaPasswds>
      if [ -f ${APPSDIR}/servicetools/install/bin/installlib.sh ];
      then
         logstr "   - Synchornize password for Symphonia"
         ${APPSDIR}/servicetools/install/bin/installlib.sh persistence.synchronize.userpassword  >> $LOGFILE 2>&1
         if [ "$testbed" = "cluster" ];
         then
            rssh $othernode "${APPSDIR}/servicetools/install/bin/installlib.sh persistence.synchronize.userpassword  >> $LOGFILE 2>&1"
         fi
      fi
   #</SynSymphiniaPasswds>
   clearstdin
}

# ---------------------------------------------------------------
# function: waitonsolid
# args    : None
# description:
#   upconvert solid version.
# ---------------------------------------------------------------

waitonsolid( )
{
   xconvstatus=1
   logstr "[*] Waiting for solid conversion to finish."
   while [ $xconvstatus -eq 1 ];
   do
         ps -ef | grep solid | grep -v grep | grep -q convert
         if [ $? -eq 0 ];
         then
            logstr "[*] [${_SELF_}]: Waiting for DB conversion to finish"
         else
            textncolor $BoldCyan "[${_SELF_}]: Conversion of DB is finished."
            break;
         fi
         sleep 8
   done
}


changedbuserpasswd()
{
   PASSWDFILE=${1}
   DBUSER=${2}

   if osv_version.sh --major compare sys ge V6; 
   then
      if osv_version.sh --major compare "$expbuildid" lt V6; 
      then
         passwd="`cat ${EXPORTDIR}/${PASSWDFILE} 2>/dev/null`"
         mv ${EXPORTDIR}/${PASSWDFILE} ${EXPORTDIR}/${PASSWDFILE}.plain
         $DBCRYPT enc ${EXPORTDIR}/${PASSWDFILE} $passwd 1>/dev/null 2>>$LOGFILE
      else
         $DBCRYPT dec ${EXPORTDIR}/${PASSWDFILE} ${EXPORTDIR}/${PASSWDFILE}.plain 1>/dev/null 2>>$LOGFILE
         passwd="`cat ${EXPORTDIR}/${PASSWDFILE}.plain 2>/dev/null`"
      fi

      NORMPASSWDFILE=${EXPORTDIR}/${PASSWDFILE}.plain

      if [ "$testbed" = "cluster" ];
      then
         rscp -p  $NORMPASSWDFILE ${othernode}:$NORMPASSWDFILE
      fi
   else
      passwd="`cat ${EXPORTDIR}/${PASSWDFILE} 2>/dev/null`"
   fi

   logstr "   - Database password  will be adapted by toolkit."
   su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword)" << PASSWDEOF
ALTER USER ${DBUSER} IDENTIFIED BY $passwd;
commit work;
PASSWDEOF
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "Database password change for user ${DBUSER} failed."
      exit $DBRESTOREFAILED
   fi
   # Update the DBA password for the rest of the script
   if [ "${DBUSER}" = "${DBA}" ]
   then
      setDbaPassword ${passwd}
   fi

   cp ${EXPORTDIR}/${PASSWDFILE} $PASSWDFILE
   if [ "$testbed" = "cluster" ];
   then
     rscp -p  $PASSWDFILE ${othernode}:$PASSWDFILE
   fi

   rm -f ${EXPORTDIR}/${PASSWDFILE}.plain
   if [ "$testbed" = "cluster" ];
   then
      rssh $othernode "rm -f ${EXPORTDIR}/${PASSWDFILE}.plain"
   fi
}

# ---------------------------------------------------------------
# function: changedbpasswds
# args    : None
# description:
#   changes db users password
# ---------------------------------------------------------------

changedbpasswds()
{
   #<ChangeDBApassword>
   if [ -f ${EXPORTDIR}/${DBA_PASSWDFILE} ];
   then
      changedbuserpasswd "${DBA_PASSWDFILE}" "${DBA}"
      X_CREATE_DB_PLAIN=0
      #<ChangeDbPasswd4Apps>
         if [ "$profile" = "integrated" -a "X$(isOSEE)X" = "XfalseX" ];
         then
            if [ -x ${APPSDIR}/servicetools/install/bin/changeDBAdminPassword.sh ];
            then
	       if [ ! -f "$NORMPASSWDFILE" ]
	       then
		     logstr " $NORMPASSWDFILE missing .... will be created again "
		     $DBCRYPT dec ${EXPORTDIR}/${DBA_PASSWDFILE} $NORMPASSWDFILE 1>/dev/null 2>>$LOGFILE
		     X_CREATE_DB_PLAIN=1
	       fi
               textncolor $BoldCyan "[${_SELF_}]: Changing application passwords on $mynode."
               ${APPSDIR}/servicetools/install/bin/changeDBAdminPassword.sh $NORMPASSWDFILE
               if [ "$testbed" = "cluster" ];
               then
                  textncolor $BoldCyan "[${_SELF_}]: Changing application passwords on $othernode."
                  rssh $othernode "${APPSDIR}/servicetools/install/bin/changeDBAdminPassword.sh $NORMPASSWDFILE"
               fi
            else
               logstr "   - Skipping application password restore."
            fi
	    if [ $X_CREATE_DB_PLAIN -eq 1 ]
	    then
	       rm $NORMPASSWDFILE
	       X_CREATE_DB_PLAIN=0
	    fi
         fi
      #</ChangeDbPasswd4Apps>
   fi
   #</ChangeDBApassword>

   #<ChangeRTP_USER_40password>
   if [ -f ${EXPORTDIR}/${RTP_USER_40_PASSWDFILE} ];
   then
      changedbuserpasswd "${RTP_USER_40_PASSWDFILE}" "${RTP_USER_40}"
   fi
   #</ChangeRTP_USER_40password>

   #<ChangeOSVUSERpassword>
   if [ -f ${EXPORTDIR}/${OSVUSER_PASSWDFILE} ];
   then
      changedbuserpasswd "${OSVUSER_PASSWDFILE}" "${OSVUSER}"
   fi
   #</ChangeRTP_USER_40password>

}


# ---------------------------------------------------------------
# function: removeappsfromdb
# args    : None
# description:
#   removes applications from db.
# ---------------------------------------------------------------

removeappsfromdb( )
{
   schemafile=/tmp/schema
   delschemafile=/tmp/delschema
   droptablesfile=/tmp/droptables
   dropschemafile=/tmp/dropschema
   rm -f $schemafile $delschemafile $droptablesfile $dropschemafile
   su - solid -c "$solsql -x onlyresults -o $schemafile -a \
      -e \"select table_name,table_schema,table_catalog from sys_tables \" \"tcp 16760\" dba $(getDbaPassword)" 1>/dev/null 2>&1
   cat $schemafile  | grep -v "^$" |  awk '{ print $1":"$2":"$3 }' > ${schemafile}.delim
   setmode $BoldPurple
   for schemaidx in `cat ${schemafile}.delim`
   do 
      tablename=`echo $schemaidx | awk -F':' '{ print $1 }'`
      tableschema=`echo $schemaidx | awk -F':' '{ print $2 }'`
      tablecatalog=`echo $schemaidx | awk -F':' '{ print $3 }'`
      strippedtableschema=${tableschema:0:3}
      strippedtablename=${tablename:0:3}
      if [ "$strippedtableschema" = "SYM" -o "$strippedtableschema" = "DSA" -o \
           "$strippedtableschema" = "RG8" -o "$strippedtableschema" = "DLS" -o \
           "$tablecatalog" = "DLSDB"      -o "$strippedtablename" = "DLS"   -o \
           "$tablecatalog" = "OPENSOA"    -o "$tablecatalog" = "SYMCADB" ];
      then
          echo "${tablecatalog}:${tableschema}" >> $delschemafile
          logstr "   - Dropping table $tablename"
          {
             echo "set catalog ${tablecatalog};"
             echo "truncate table $tablename;"
             echo "commit work;"
             echo "drop table $tablename cascade constraints;"
             echo "commit work;"
          } > $droptablesfile
          su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $droptablesfile" 1>>$LOGFILE 2>&1
      fi
   done
   setmode $Norm

   if [ -f $delschemafile ];
   then
      cat $delschemafile | sort | uniq > ${delschemafile}.uniq
      setmode $BoldPurple
      for schemaidx in `cat ${delschemafile}.uniq`
      do
         tablecatalog=`echo $schemaidx | awk -F':' '{ print $1 }'`
         tableschema=`echo $schemaidx | awk -F':' '{ print $2 }'`
         logstr "   - Dropping Schema $tableschema"
         {
            echo "set catalog $tablecatalog;"
            echo "drop schema $tableschema cascade;"
            echo "commit work;"
         } > $dropschemafile
         su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $dropschemafile" 1>>$LOGFILE 2>&1
      done
      setmode $Norm
   fi
   dbaapps="\
      ADMIN_SETTINGS
      DSABGDATA
      DSABGLDLS
      EXTERNALWEBGUI
      EX_SEC_GROUP
      EX_SEC_MEMBER
      EX_SEC_MEMBER_LINES
      EX_SEC_REL
      HIPATH8000
      JOBIDDATA
      REMARKS_DATA
      REMARKS_ID_MAPPING
      RG2700CONNECTIONINFO
      RS_ACTIVE_RULESETS
      RS_CATEGORY_TABLE
      RS_COMRESPONSE
      RS_GROUPWARE_STATUS
      RS_LOGIN_TABLE
      RS_MBXALIAS_TABLE
      RS_MEDIA_FILTERS
      RS_RULEBOOKS
      RS_SWITCHBACK_TABLE
      SCHEMA_VERSION
      SUBSCRIBERTEMPLATE
   "
   dbaappsfile=/tmp/dbapps
   {
      echo "set catalog RTPDB;"
      echo "set schema  DBA;"
      for dbappsidx in $dbaapps
      do
         echo "truncate table $dbappsidx;"
         echo "commit work;"
         echo "drop table $dbappsidx cascade constraints;"
      done
      echo "commit work;"
   } > $dbaappsfile
   {
      su - solid -c "$solsql -a -e \"drop catalog DLSDB cascade\" \"tcp 16760\" dba $(getDbaPassword)"
      su - solid -c "$solsql -a -e \"drop catalog OPENSOA cascade\" \"tcp 16760\" dba $(getDbaPassword)"
      su - solid -c "$solsql -a -e \"drop catalog SYMCADB cascade\" \"tcp 16760\" dba $(getDbaPassword)"
      su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $dbaappsfile"
   } 1>>$LOGFILE 2>&1
   rm -f $schemafile $delschemafile $dbaappsfile
}

# ---------------------------------------------------------------
# function: uninstallapps
# args    : None
# description:
#   remove apps.
# ---------------------------------------------------------------

uninstallapps( )
{
   #<OSCMigration>
   if [ "$NOAPPS" = "true" ];
   then
      if [ "$profile" = "integrated" ];
      then
         if [ -f /etc/init.d/symphoniad ];
         then
            textncolor $BoldCyan "[${_SELF_}]: Uninstalling applications on $mynode."
            sh /enterprise/overall_installer/uninstall.sh uninstall
            if [ $? -ne 0 ];
            then
               textncolor $BoldCyan "[${_SELF_}]: Uninstall of applications failed."
               exit $UNINSTALLAPPSFAIL
            fi
            if [ "$testbed" = "cluster" ];
            then
               textncolor $BoldCyan "[${_SELF_}]: Uninstalling applications on $othernode."
               rssh $othernode "sh /enterprise/overall_installer/uninstall.sh uninstall"
               if [ $? -ne 0 ];
               then
                  textncolor $BoldCyan "[${_SELF_}]: Uninstall of applications failed."
                  exit $UNINSTALLAPPSFAIL
               fi
            fi
         fi
      fi
   fi
   #</OSCMigration>
}

# ---------------------------------------------------------------
# function: saveinstance
# args    : None
# description:
#   save instance files, that need to be adapted by importinstance.
# ---------------------------------------------------------------

saveinstance( )
{
   instancesource="$1"
   instancedest="$2"
   instance="$3"
   instancename="$4"
   instancealtr="$5"
   
   mkdir -p ${instance}/old ${instance}/new
   oldfile=`grep -l "$instancename" $instancesource/instance* 2>/dev/null`
   newfile=`grep -l "$instancename" $instancedest/instance*   2>/dev/null`
   if [ "$oldfile" = "" -o "$newfile" = "" ];
   then
      if [ "$oldfile" != "" -a "$instancealtr" != "" ];
      then
         baseoldfile=`basename $oldfile`
         cat "$oldfile" | sed -e "s/$instancename/$instancealtr/" > $instance/old/$baseoldfile
      fi
      return
   fi

   cp -p $oldfile $instance/old/. 
   cp -p $newfile $instance/new/.
}

# ---------------------------------------------------------------
# function: importinstance
# args    : None
# description:
#   selectively replace instance files for services which claim
#   to be well behaved.
# ---------------------------------------------------------------

importinstance( )
{
   instance="$1"
   instancename="$2"
   instanceproperty="$3"
   oldfile=`grep -l "$instancename" $instance/old/*`
   newfile=`grep -l "$instancename" $instance/new/*`
   if [ "$oldfile" = "" -o "$newfile" = "" ];
   then
      return
   fi
   logstr "   - Adapting poperty $instanceproperty."
   grep "name=\"$instanceproperty\"" $oldfile | \
   sed -e 's/.*value=\(.*\) .*/\1/' -e 's/"//g' \
       -e 's/\\/\\\\/g' -e 's/\//\\\//g'        \
       -e 's/\&/\\\&/g' -e 's/\;/\\\;/g'        \
   > /tmp/oldval
   oldval="`cat /tmp/oldval`"
   if [ "$oldval" = "" ];
   then
      return
   fi
   cat $newfile | sed -e "/\"$instanceproperty\"/s/value=.*[ \t]/value=\"$oldval\" /" > ${newfile}.new
   cp ${newfile}.new ${newfile}
   rm -f ${newfile}.new
} 2>/dev/null

# ---------------------------------------------------------------
# function: rebuildusers
# args    : None
# description:
#   For tigher security user and group info on builds V7 and
#   above have changed. Make sure the exported data is also 
#   tailored for the change.
# ---------------------------------------------------------------

rebuildusers( ) {

   #<DodSecurityAdaptations>
   if osv_version.sh --major compare sys ge V7; 
   then
      local users_to_adjust="sym"
      
      logstr "   - Adjusting user and group information for users [${users_to_adjust}]."
      for users in ${users_to_adjust}
      do
         curuid="`id -u $users 2>/dev/null`"
         curgid="`id -g $users 2>/dev/null`"
         expuid="`cat ${EXPORTDIR}/etc/passwd | egrep "^${users}:" | awk -F':' '{ print $3 }'`"
         expgid="`cat ${EXPORTDIR}/etc/passwd | egrep "^${users}:" | awk -F':' '{ print $3 }'`"
         if [ "$curuid" != "" -a \
              "$curgid" != "" -a \
              "$expuid" != "" -a \
              "$expgid" != "" ];
         then
             if [ "$curuid" != "$expuid" ];
             then
                logstr "      - Adjusting $users user information."
                find ${EXPORTDIR} -uid $expuid -exec chown $users {} \;
             fi
             if [ "$curgid" != "$expgid" ];
             then
                logstr "      - Adjusting $users group information."
                find ${EXPORTDIR} -gid $expuid -exec chgrp $users {} \;
             fi
         fi
      done
   fi
   #</DodSecurityAdaptations>
}

# ----------------------------------------------------------------
# function: importmtu
# args    : none
# description:
#   import exported mtu, for all known interfaces.
# ----------------------------------------------------------------

importmtu( )
{
   EXPORTMTUDIR=${EXPORTDIR}/etc/sysconfig/network
   SYSMTUDIR=/etc/sysconfig/network
   importdevice=$1
   nafodevice=$2
   if [ "$importdevice" = "" ];
   then
      return
   fi
   if [ -f ${EXPORTMTUDIR}/ifcfg-$importdevice -a -f ${SYSMTUDIR}/ifcfg-$importdevice ];
   then
      mtudevice="`cat ${EXPORTMTUDIR}/ifcfg-$importdevice | egrep "^MTU=" | tail -1 | awk -F'=' '{ print $2 }'`"
      numericmtudevice="`echo $mtudevice | sed -e \"s/'//g\"`"
      echo $numericmtudevice | egrep -q "^['0-9]+$"
      if [ $? -eq 0 ];
      then
         if [ "$numericmtudevice" -gt 1000 ];
         then
            logstr "   - Detected exported MTU($nafodevice:$mtudevice) for $importdevice. Will use it."
            {
                cat ${SYSMTUDIR}/ifcfg-$importdevice | egrep -v "^MTU="
                echo "MTU=$mtudevice"
            } > ${SYSMTUDIR}/ifcfg-${importdevice}.mtu
            cp -f ${SYSMTUDIR}/ifcfg-${importdevice}{.mtu,}
            rm -f ${SYSMTUDIR}/ifcfg-${importdevice}.mtu
         fi
      fi
   fi
}

# ----------------------------------------------------------------
# function: setupmtu
# args    : none
# description:
#   detect xchannel mtu for normal cluster installs.
# ----------------------------------------------------------------

setupmtu( )
{
   #<CfgMtu>
   for nafoidx in nafo0 nafo1 nafo2 nafo3
   do
      if [ "$mynode" = "$primhost" ];
      then
         mtudev="`cfgread $nafoidx| awk '{ print $2 }'`"
      else
         mtudev="`cfgread $nafoidx| awk '{ print $3 }'`"
      fi
      importmtu "$mtudev" "$nafoidx"
   done
   #</CfgMtu>
}

# ----------------------------------------------------------------
# function: enablearpsig
# args    : none
# description:
#   enable arp on all signalling interfaces and mark those who had 
#   the NOARP flag
# -------------
enablearpsig( )
{
   local noderole="" 
   if [ "$primary" != "" ]
   then
      noderole=primary
   else
      noderole=secondary
   fi
   # FRN10513 : enable arp in signalling interfaces so there will not be any problem with IPv6 neighbour discovery
   local SIGNALLING_IFACES=`getSignallingInterfaces $noderole`
   if [ $? -eq 0 ]
   then
      for iface in ${SIGNALLING_IFACES} 
      do
         markArpStatus $iface
         setifarp on $iface
      done
   fi

}

# ----------------------------------------------------------------
# function: disablearpsig
# args    : none
# description:
#  disable arp on all signalling interfaces that had
#  the NOARP flag
# -------------
disablearpsig()
{
   local noderole="" 
   
   if [ "$primary" != "" ]
   then
      noderole=primary
   else
      noderole=secondary
   fi

   # Now turn arp back to what it was in signalling interfaces
   local arp_was_on=false
   local SIGNALLING_IFACES=`getSignallingInterfaces $noderole`
   for iface in ${SIGNALLING_IFACES}
   do
      arp_was_on=has_arp_flag_$iface
      if [ "${!arp_was_on}" = "true" ]
      then
         setifarp off $iface
      fi   
   done

}

# ---------------------------------------------------------------
# function: RTPchecksnapshot
# args    : None
# description:
#   checks for DB snapshot
# ---------------------------------------------------------------

RTPchecksnapshot()
{
    logstr " $(date) checking alternatively if Database Snapshot has been created "
    xstatus=1
    xresult=$(tail -30 $LOGFILE | grep "Database snapshot file saved to" | wc -l )
    if [ $xresult -gt 0 ]
    then
        xstatus=0
	logstr " Database Snapshot has been created - all fine"
    fi
    return $xstatus
}

# ---------------------------------------------------------------
# function: restoresysdata
# args    : None
# description:
#   saves system data of current active image. 
# ---------------------------------------------------------------

restoresysdata( ) {

   rebuildusers
   buildSrxSystemDependentParm


   ##########################################################################
   # Get the configuration variable of the exported system
   
   getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  srx_build_id expbuildid
   getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  cf_type  expcftype
   getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_separation  expnodesep 
   getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  test_bed exptestbed
   getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_1_name expprimhost
   getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_2_name expsechost
   getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_1_ip   expprimip
   getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_2_ip   expsecip
   expnafoxch="`fcfgread ${EXPORTDIR}/etc/hiq8000/node.cfg nafo3`"
   logstr "   - Processing for source build $expbuildid."
   if osv_version.sh --major compare "$expbuildid" lt V5 || [ "$expnafoxch" = "" ];
   then
      getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_1_cip_logical expprimcip
      getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_2_cip_logical expseccip
   else
      export expprimcip="`echo $expnafoxch   | awk '{ print $4 }'`"
      export expseccip="`echo $expnafoxch    | awk '{ print $5 }'`"
   fi
   
   ##########################################################################
   
   
   #<CompareLoads>
   if [ "$ImportOsv" = "true" -o "$Migrate8k" = "true" ]
   then
       if osv_version.sh compare "$expbuildid" gt "$buildid"; 
       then

           logstr "   - Target Load: $buildid"
           logstr "   - Source Load: $expbuildid"
           logstr "   - Sorry, upgrades are only possible to a greater load id."

           exit $DBRESTOREFAILED
       else
           if [ "$expbuildid" = "$buildid" -a -f ${EXPORTDIR}/patchversion ];
           then
               expps="`cat ${EXPORTDIR}/patchversion`"
               if [ "$expps" \> "$latestps" ];
               then
                   logstr "   - Target PS: $latestps"
                   logstr "   - Source PS: $expps"
                   logstr "   - Sorry, upgrades are only possible to a greater patch set level."

                   exit $DBRESTOREFAILED
               fi
           fi

       fi # if [ "$expbuildid" \> "$buildid" ]

   fi # if [ "$ImportOsv" = "true" -o "$Migrate8k" = "true" ]
   #</CompareLoads>


   #<CompareNetworks>
      buildnwmap /etc/hiq8000/node.cfg             "${buildid}"    
      buildnwmap ${EXPORTDIR}/etc/hiq8000/node.cfg "${expbuildid}" 
      {
         echo "Source networks"
         echo "///////////////"
         cat ${EXPORTDIR}/etc/hiq8000/node.cfg.netcfg.nw
         echo ""
         echo "Target networks"
         echo "///////////////"
         cat  /etc/hiq8000/node.cfg.netcfg.nw
         echo ""

      } >>$LOGFILE
      diff -iBwq /etc/hiq8000/node.cfg.netcfg.nw ${EXPORTDIR}/etc/hiq8000/node.cfg.netcfg.nw >>$LOGFILE
      if [ $? -eq 0 ];
      then
         logstr "   - Networks match between source and target."
         nwmatch=true
      else
         logstr "   - Networks differ between source and target."
         nwmatch=false
      fi
      rm -f /etc/hiq8000/node.cfg.netcfg.nw ${EXPORTDIR}/etc/hiq8000/node.cfg.netcfg.nw
   #</CompareNetworks>


   #<InterfaceCheck>
      getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  numberOfInterfaces expninterfaces
      ninterfaces=`cfgread numberOfInterfaces`
      if osv_version.sh compare "$expbuildid" ge V6 && osv_version.sh --major compare sys ge V6;
      then
         if [ "$Migrate8k" = "true" ];
         then
            if [ "$ninterfaces" \> "$expninterfaces" ];
            then
               logstr "[${_SELF_}]: Toolkit does not support interface change!"
               logstr "          numberOfInterfaces:$ninterfaces / numberOfInterfaces on Exported data:$expninterfaces."
               exit $DBRESTOREFAILED
            fi
         else
            if [ "$ninterfaces" != "$expninterfaces" ];
            then
               if [ "$nwmatch" = "true" ];
               then
                  logstr "   - Interface change for import detected.!"
                  logstr "   - Networks match, hence import will continue."
               else
                  logstr "   - Toolkit does not support interface change for import.!"
                  logstr "   - numberOfInterfaces:$ninterfaces / numberOfInterfaces on Exported data:$expninterfaces."
                  if [ "$ninterfaces" \< "$expninterfaces" ];
                  then
                     logstr "   - You must try migrate8k, instead of import8k." 
                  fi
                  exit $DBRESTOREFAILED
               fi
            fi
         fi
      fi
   #</InterfaceCheck>


   #<CheckExpApp>
      if [ ! -d ${EXPORTDIR}${APPSDIR} -a "$profile" = "integrated" -a "$NOAPPS" = "false" ];
      then
         if [ "X$(isOSEE)X" = "XfalseX" ]
         then
            logstr "[${_SELF_}]: Toolkit does not support this scenario! Please use option -noapps if you want to try your luck."  
         
            exit $CHECKEXPAPP
         fi
       fi
   #</CheckExpApp>


   #<CompareRoutes>
      getrouteinfo des
      routediff=false
      >/log/route8k.diff
      sync
      for devidx  in eth0 eth1 eth2 eth3 eth4 eth5 eth6 eth7 bond0 bond1 bond2 bond3 cip0 cip1 cip2 cip3
      do
         for infotype in addr route
         do
            if [ -f ${EXPORTDIR}/srcrouteinfo/${devidx}.${infotype} -a -f ${EXPORTDIR}/desrouteinfo/${devidx}.${infotype} ];
            then
               diff -iBwq ${EXPORTDIR}/srcrouteinfo/${devidx}.${infotype} \
                          ${EXPORTDIR}/desrouteinfo/${devidx}.${infotype} \
                          1>/dev/null 2>&1
               if [ $? -ne 0 ];
               then
                  routediff=true
                  nordevidx="`echo $devidx | awk '{ printf \"%-8s\", $1 }'`"
                  logstr "   - Routing via $nordevidx appears to differ from your src system.(type:${infotype})"
                  {
                  echo   "///////// - ${devidx}.${infotype} - ////////////"
                  diff -iBw ${EXPORTDIR}/srcrouteinfo/${devidx}.${infotype} \
                            ${EXPORTDIR}/desrouteinfo/${devidx}.${infotype} 
                  } 1>>/log/route8k.diff 2>&1
                  cat /log/route8k.diff >> $LOGFILE
               fi
            fi
         done
      done
      if [ "$routediff" = "true" ];
      then
         echo    "   - Routing difference details under /log/route8k.diff."
      fi
   #</CompareRoutes>


   #<DbmsProps>
      if [ "$Restore8k" = "true" ];
      then
           AppDataDir=""
      else
           AppDataDir="${EXPORTDIR}/enterprise"
      fi
      if [ "$profile" = "integrated" -a "$Migrate8k" = "true" -a "X$(isOSEE)X" = "XfalseX" ];
      then
         if [ -f ${EXPORTDIR}/enterprise/common/conf/dbms.properties ];
         then

            getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_1_ip   expprimip
            getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_2_ip   expsecip
            getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_1_name oldprimnodename
            getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_2_name oldsecnodename
            getcfgvar /etc/hiq8000/node.cfg              node_1_name newprimnodename
            getcfgvar /etc/hiq8000/node.cfg              node_2_name newsecnodename

            if [ -f ${AppDataDir}/servicetools/install/conf/responsefile.txt ];
            then
               oldcomstr=`cat ${EXPORTDIR}/enterprise/servicetools/install/conf/responsefile.txt| \
                          grep SI_COMMUNITY_NAME | awk -F'=' '{ print $2 }' | sed -e "s/[ \t]*//g"`
               comstr=`cat /enterprise/servicetools/install/conf/responsefile.txt| \
                       grep SI_COMMUNITY_NAME | awk -F'=' '{ print $2 }' | sed -e "s/[ \t]*//g"`
               if [ "$oldcomstr" != "$comstr" ];
               then
                  textncolor $BoldPurple "Note: your community strings differ between source and target release."
                  logstr "   Source community string - $oldcomstr"
                  logstr "   Target community string - $comstr"
               fi
            fi

            logstr "Source Information :"
            logstr "   - $expprimip"
            logstr "   - $expsecip"
            logstr "   - $oldprimnodename"
            logstr "   - $oldsecnodename"
            logstr "   - $oldcomstr"

            logstr "Target Information :"
            logstr "   - $primip"
            logstr "   - $secip"
            logstr "   - $newprimnodename"
            logstr "   - $newsecnodename"
            logstr "   - $comstr"

            INSTANCEDIR=/enterprise/common/conf/config-beans
            ALTINSTANCEDIR=/enterprise/common/conf
            RELOCINSTANCEDIR=/tmp/instance
            rm -rf $RELOCINSTANCEDIR
            saveinstance ${EXPORTDIR}/$INSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "Conferencing Service"
            saveinstance ${EXPORTDIR}/$INSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "Conferencing Applets Service"
            saveinstance ${EXPORTDIR}/$INSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "Fastviewer Web Conference Component"
            saveinstance ${EXPORTDIR}/$INSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "Presence XMPP Integration - Connector"
            saveinstance ${EXPORTDIR}/$INSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "ConnectionManager"
            saveinstance ${EXPORTDIR}/$INSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "Conferencing Component"
            saveinstance ${EXPORTDIR}/$INSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "LDAP Connector Service"

            saveinstance ${EXPORTDIR}/$ALTINSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "Conferencing Service"
            saveinstance ${EXPORTDIR}/$ALTINSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "Conferencing Applets Service"
            saveinstance ${EXPORTDIR}/$ALTINSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "Fastviewer Web Conference Component"
            saveinstance ${EXPORTDIR}/$ALTINSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "Presence XMPP Integration - Connector"
            saveinstance ${EXPORTDIR}/$ALTINSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "ConnectionManager"
            saveinstance ${EXPORTDIR}/$ALTINSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "Conferencing Component" "Conferencing Service"
            saveinstance ${EXPORTDIR}/$ALTINSTANCEDIR $INSTANCEDIR $RELOCINSTANCEDIR "LDAP Connector Service"

            #<OverrideCerts>
               rm -rf ${EXPORTDIR}/enterprise/common/conf /tmp/responsefile.gen.txt
               cp -R -p /enterprise/common/conf ${EXPORTDIR}/enterprise/common/conf 
               for idx in `find ${EXPORTDIR}/enterprise -name "*.p12"  \
                                          -o -name "*.jks"             \
                                          -o -name "*.sks"             \
                                          -o -name "instance*.xml"` 
               do
                  rm -f $idx
               done 
               for idx in `find /enterprise -name "*.p12"          \
                                          -o -name "*.jks"         \
                                          -o -name "*.sks"         \
                                          -o -name "instance*.xml"` 
               do
                  cp $idx ${EXPORTDIR}/${idx}
               done 2>/dev/null
            #</OverrideCerts>
 
            for idx in `find ${EXPORTDIR} -name "*.xml"           \
                                          -o -name "*.properties" \
                                          -o -name "*.env"        \
                                          -o -name "*.cfg"        \
                                          -o -name "*.txt"`
            do
               #<ExcludeNodeCfg>
                  baseidx="`basename $idx`"
                  if [ "$baseidx" = "node.cfg" ];
                  then
                     continue
                  fi
               #</ExcludeNodeCfg>
               if [ "$testbed" = "cluster" ];
               then
                  cat $idx |                                                      \
                      sed -e "s/${oldcomstr}/${comstr}/g"                         \
                          -e "s/\"${oldprimnodename}\"/\"${newprimnodename}\"/g"  \
                          -e "s/\"${oldsecnodename}\"/\"${newsecnodename}\"/g"    \
                          -e "s/${expprimip}/${primip}/g"                         \
                          -e "s/${expsecip}/${secip}/g"                           \
                  >  ${idx}.migrate8k
               else
                  cat $idx |                                                      \
                      sed -e "s/${oldcomstr}/${comstr}/g"                         \
                          -e "s/\"${oldprimnodename}\"/\"${newprimnodename}\"/g"  \
                          -e "s/${expprimip}/${primip}/g"                         \
                  >  ${idx}.migrate8k
               fi
               cp ${idx}.migrate8k ${idx}
               rm -f ${idx}.migrate8k
            done
 
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "bridgeNumberToll"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "bridgeNumberTollFree"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "bridgeNumberOther"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "DefaultLanguage"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "CalloutAllowed"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "suppressJoinLeftIndicationCount"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "maxConferenceDuration"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "autoProlongConferences"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "prolongDelta"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "maintenanceTime"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "DirectPINCall"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "CleanUserConferencesAfterUserDeletion"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "enableEmailNotification"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "ConferenceViewerURL"
            importinstance $RELOCINSTANCEDIR "Conferencing Service"   "resourceMngTimeFrame"

            importinstance $RELOCINSTANCEDIR "Conferencing Component" "bridgeNumberToll"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "bridgeNumberTollFree"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "bridgeNumberOther"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "DefaultLanguage"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "CalloutAllowed"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "suppressJoinLeftIndicationCount"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "maxConferenceDuration"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "autoProlongConferences"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "prolongDelta"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "maintenanceTime"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "DirectPINCall"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "CleanUserConferencesAfterUserDeletion"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "enableEmailNotification"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "ConferenceViewerURL"
            importinstance $RELOCINSTANCEDIR "Conferencing Component" "resourceMngTimeFrame"

            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "connection.serverURL"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "connection.username"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "connection.password"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "connection.displayName"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "connection.useSSL"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "searchBase"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Alias"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.AppSpecificPresenceInfo"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.BuildingNumber"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Business"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Business2"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.BusinessNormalized"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Business2Normalized"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.BusinessFax"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.BusinessFaxNormalized"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.City"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.CompanyName"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.CountryCode"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Department"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Description"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.DisplayName"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Email"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Email2"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.GivenName"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Home"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.HomeNormalized"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.HomeUrl"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.ImAddress"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.LastName"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.MiddleName"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Mobile"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.MobileNormalized"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Picture"
            importinstance $RELOCINSTANCEDIR "LDAP Connector Service" "AttrMap.Phone"

            importinstance $RELOCINSTANCEDIR "Conferencing Applets Service" "CapAudioOnlyConferences"
            importinstance $RELOCINSTANCEDIR "Conferencing Applets Service" "CapWebConferences"
            importinstance $RELOCINSTANCEDIR "Conferencing Applets Service" "CapVideoConferences"
            importinstance $RELOCINSTANCEDIR "Conferencing Applets Service" "SelectionFilterNumberingPlan"

            importinstance $RELOCINSTANCEDIR "Fastviewer Web Conference Component" "HostAddress"
            importinstance $RELOCINSTANCEDIR "Fastviewer Web Conference Component" "MaxExternalParticipants"
            importinstance $RELOCINSTANCEDIR "Fastviewer Web Conference Component" "MaxExternalParticipants"
            importinstance $RELOCINSTANCEDIR "Fastviewer Web Conference Component" "PingInterval"

            importinstance $RELOCINSTANCEDIR "Presence XMPP Integration - Connector" "XMPP Server Admin Port"
            importinstance $RELOCINSTANCEDIR "Presence XMPP Integration - Connector" "XMPP Server Name"
            importinstance $RELOCINSTANCEDIR "Presence XMPP Integration - Connector" "XMPP Transparent Address"

            importinstance $RELOCINSTANCEDIR "ConnectionManager" "cm.ipaddress"
            importinstance $RELOCINSTANCEDIR "ConnectionManager" "cm.port"

            cp $RELOCINSTANCEDIR/new/*.xml ${EXPORTDIR}/$INSTANCEDIR/. 2>/dev/null

            {
               cp ${EXPORTDIR}/enterprise/common/conf/dbms.properties /enterprise/common/conf/dbms.properties
               /enterprise/servicetools/install/bin/installlib.sh persistence.synchronize.userpassword
            } 1>>$LOGFILE 2>&1 
         fi
      fi
   #</DbmsProps>

   isSNMPv3Lost "restoresysdata" "before CreateRespCfg4Migration line:9567"

   #</CreateRespCfg4Migration>
   if osv_version.sh --major compare sys ge V4 && [ "$profile" = "integrated" -a "X$(isOSEE)X" = "XfalseX" ];
   then
      RESPONSECFG=/etc/hiq8000/response.cfg
      INSTALLRESPONSECFG=/opt/unisphere/srx3000/ifw/tmp/response.cfg
      if [ -f $INSTALLRESPONSECFG ];
      then
         cp -f $INSTALLRESPONSECFG $RESPONSECFG
      fi
      if [ -f $RESPONSECFG ];
      then
         cp $RESPONSECFG ${RESPONSECFG}.install
         if [ "$NOAPPSINDB" = "true" ];
         then
            cat $RESPONSECFG | sed -e 's/SI_FW_DB_MIGRATION.*/SI_FW_DB_MIGRATION=false/' > ${RESPONSECFG}.new
         else
            cat $RESPONSECFG | sed -e 's/SI_FW_DB_MIGRATION.*/SI_FW_DB_MIGRATION=true/'  > ${RESPONSECFG}.new
         fi
         cp ${RESPONSECFG}.new $RESPONSECFG
         rm -f ${RESPONSECFG}.new
         if [ "$testbed" = "cluster" -a "$RECOVER8k" = "false" ];
         then
            rscp -p $RESPONSECFG $othernode:${RESPONSECFG}
         fi
      fi
   fi 1>>$LOGFILE 2>&1
   #</CreateRespCfg4Migration>

   isSNMPv3Lost "restoresysdata" "after CreateRespCfg4Migration line:9597"

   #<RebuildCDRInfo>
      CDRTCN=/opt/SMAW/SMAWrtp/cust_conf/SrxUsc.tcn
      oldcdrusage=`cat $CDRTCN |  grep '^CDR' | awk -F '::' '{ print $3 }'`
      newcdrusage=`cat ${EXPORTDIR}/$CDRTCN 2>/dev/null |  grep '^CDR' | awk -F '::' '{ print $3 }'`
      newcdrusage=${newcdrusage:-3000}
      if [ "$oldcdrusage" = "" ];
      then
         sed -i -e "s/^CDR::::::/CDR::::$newcdrusage::/g" $CDRTCN
      fi
   #</RebuildCDRInfo>


   ##################################################################################
   # Perform the following actions on node1 or Simplex only
   if [ "$mynode" = "$primhost" ];
   then

      checkprocs
      
      #<SysAtState#3>
         if [ -f /etc/init.d/symphoniad -a "X$(isOSEE)X" = "XfalseX" ];
         then
            textncolor $BoldCyan "[${_SELF_}]: Bringing applications down, on $mynode.`date`"
            logstr "[*] $mynode: Stopping symphonia applications."
            checkappstatus stop local
            if [ "$testbed" = "cluster" ];
            then
               logstr "[*] $othernode: Stopping symphonia applications."
               checkappstatus stop remote
            fi
         fi
         textncolor $BoldCyan "[${_SELF_}]: Bringing system to state#3, on $mynode.`date`"
         if ! srxctrl 3 `remotestate 3`  1>>$LOGFILE 2>&1; then
            logstr "[${_SELF_}]: Cannot bring system to state#3.`date`"
            exit $DBRESTOREFAILED
         fi
      #</SysAtState#3>


      #<SwitchSolid>
         switchsolid ${mynode}
      #</SwitchSolid>


      #<UninstallApps>
         uninstallapps
         if [ "X$(isOSEE)X" = "XtrueX" ]
         then
            if [ -f /enterprise/overall_installer/uninstall.sh ]
            then
               textncolor $BoldCyan "[${_SELF_}]: V9 OSEE Uninstalling applications on $mynode."

               sh /enterprise/overall_installer/uninstall.sh uninstall
               if [ $? -ne 0 ];
               then
                  textncolor $BoldCyan "[${_SELF_}]: Uninstall of applications failed."
                  #exit $UNINSTALLAPPSFAIL
               fi
            fi
         fi
      #</UninstallApps>


      #<ExportBaseSchema>
         textncolor $BoldCyan "Collecting reference schema."
         setmode $BoldPurple
         export ExportAudit8k=${SOLIDHOME}/audit8k
         rm -rf $ExportAudit8k
         mkdir -p  $ExportAudit8k/reference $ExportAudit8k/customer
         chmod -R 777 $ExportAudit8k
         chown -R solid.dba $ExportAudit8k
         schemafile=/tmp/schema
         su - solid -c "$solsql -x onlyresults -o $schemafile -a \
            -e \"select table_name,table_schema from sys_tables \" \"tcp 16760\" dba $(getDbaPassword)" 1>/dev/null 2>&1
         cat $schemafile  | grep -v "^$" |  awk '{ print $1":"$2 }' > ${schemafile}.delim
         for schemaidx in `cat ${schemafile}.delim`
         do 
            tablename=`echo $schemaidx | awk -F':' '{ print $1 }'`
            tableschema=`echo $schemaidx | awk -F':' '{ print $2 }'`
            strippedtablename=${tablename:0:12}
            if [ "$strippedtablename" = "RTP_CFG_PARA" ];
            then
               continue
            fi
            logstr "   - Reference Definition ${tablename}/${tableschema}" 
            su - solid -c "cd  ${ExportAudit8k}/reference;$soldd -s ${tableschema} \
               -o ${ExportAudit8k}/reference/${tablename}.sql -xFKAlterTable 'tcp 16760' dba $(getDbaPassword) $tablename" 1>>$LOGFILE 2>&1
            if [ $? -ne 0 ];
            then
               logstr "[${_SELF_}]: Sorry, Solid schema for $tablename could not be exported."
               exit $DBRESTOREFAILED
            fi
         done
         rm -f $schemafile ${schemafile}.delim
         setmode $Norm
      #</ExportBaseSchema>


      #<DeleteRtp>
         if [ -d /unisphere/srx3000/srx/40 ];
         then
            textncolor $BoldCyan "[${_SELF_}]: deleting RTP on $mynode."
            if [ -f /opt/SMAW/SMAWrtp/bin/deleteRTPsnc ];
            then
              deleteRTPcmd=/opt/SMAW/SMAWrtp/bin/deleteRTPsnc
            else
              deleteRTPcmd=deleteRTP
            fi
            # savebanner
            su - srx  -c "yes 2>/dev/null | $deleteRTPcmd" 1>>$LOGFILE 2>&1 
            status=$?
            # restorebanner
            if [ $status -ne 0 ];
            then
               textncolor $BoldRed "[${_SELF_}]: deleting RTP failed."
               exit $DBRESTOREFAILED
            fi
         else
            logstr "Skiping delete RTP/Nothing to delete."
         fi
      #</DeleteRtp>

   fi # if [ "$mynode" = "$primhost" ];
   ##################################################################################

   #<Normal installs>
   if [ "$instmode" = "normal" ]; 
   then

      #<CheckMagic>
      if [ "$SYSIMPORT" != "true" ];
      then
         restmagicsum="`cat  ${passiveidx}/${EXPORTDIR}/magic 2>/dev/null`" 
      else
         restmagicsum="`cat  ${EXPORTDIR}/magic 2>/dev/null`" 
      fi
      if [ "$Migrate8k" != "true" ];
      then
         if [ "$restmagicsum" != "$magicsum" ];
         then
            logstr "[${_SELF_}]: Doing further analysis"
            if [ "$testbed" = "cluster" ];
            then
               cfgtargetinfo="$primhost-$sechost-$primip-$secip-$primcip-$seccip"
               cfgsrcinfo="$expprimhost-$expsechost-$expprimip-$expsecip-$expprimcip-$expseccip"
               logstr "Source Configuration -"
               logstr "    testbed    : $exptestbed."
               logstr "    node-names : $expprimhost/$expsechost."
               logstr "    node-ip's  : $expprimip/$expsecip."
               logstr "    node-cip's : $expprimcip/$expseccip."
               
               logstr "Target Configuration -"
               logstr "    testbed    : $testbed."
               logstr "    node-names : $primhost/$sechost."
               logstr "    node-ip's  : $primip/$secip."
               logstr "    node-cip's : $primcip/$seccip."
            else
               cfgtargetinfo="$primhost-$primip-$primcip"
               cfgsrcinfo="$expprimhost-$expprimip-$expprimcip"
               logstr "Source Configuration -"
               logstr "    testbed    : $exptestbed."
               logstr "    node-names : $expprimhost."
               logstr "    node-ip's  : $expprimip."
               logstr "    node-cip's : $expprimcip."
               logstr "Target Configuration -"
               logstr "    testbed    : $testbed."
               logstr "    node-names : $primhost."
               logstr "    node-ip's  : $primip."
               logstr "    node-cip's : $primcip."
            fi
            if [ "$cfgsrcinfo" != "$cfgtargetinfo" ];
            then
               echo "Source Information : $cfgsrcinfo"
               echo "Target Information : $cfgtargetinfo"
               logstr "[${_SELF_}]: Sorry, your backed up system looks different from current one."
               exit $MAGICCHECKFAILED
            else
               if [ "$testbed" != "$exptestbed" ];
               then
                  echo "Source Information : $cfgsrcinfo"
                  echo "Target Information : $cfgtargetinfo"
                  logstr "[${_SELF_}]: O.k, Your testbed configuration is different. Will continue."
               fi
            fi
         fi
      fi
      if [ ! -f ${EXPORTDIR}/loadversion -o ! -f ${EXPORTDIR}/patchversion ];
      then
         logstr "[${_SELF_}]: Sorry, cannot determine the load of exported data."
         exit $MAGICCHECKFAILED
      fi
      #</CheckMagic>


   #<CheckMembership>
      membership="`cat ${EXPORTDIR}/nodemembership`"
      if [ "$mynode" = "$primhost" ];
      then
         if [ "$membership" != "primary8k" ];
         then
            if [ ! -f ${EXPORTDIR}/recover ];
            then
               logstr "[${_SELF_}]: Sorry, cannot determine cluster membership."
               textncolor $BoldCyan "Hint: Check if the exported data is swapped by mistake between nodes."
               exit $MEMBERSHIPUNKNOWN
            else
               logstr "[${_SELF_}]: Recovery mode. Ignoring cluster membership."
            fi
         fi
      else
         if [ "$membership" != "secondary8k" ];
         then
            if [ "$testbed" = "$exptestbed" ];
            then
               if [ ! -f ${EXPORTDIR}/recover ];
               then
                  logstr "[${_SELF_}]: Sorry, cannot determine cluster membership."
                  exit $MEMBERSHIPUNKNOWN
               else
                  logstr "[${_SELF_}]: Recovery mode. Ignoring cluster membership."
               fi
            else
               logstr "[${_SELF_}]: $exptestbed to $testbed conversion. Will assume data from node#<$othernode>."
            fi
         fi
      fi
   #</CheckMembership>

   remoteopt=${*:-"-restore"}

   checkremote $remoteopt
   #<DetermineFallBack>
      if [ "$Migrate8k" != "true" -a "$SYSIMPORT" != "true" ];
      then
         FALLBACKDBPATH="/img/varimg/${passiveimg}/lib/rpm"
         local osv_release="${ROOTIMGDIR}/etc/osv-release"

         if [ -f "$osv_release" ]; 
         then 
            source "$osv_release"
            fbloadversion="V${OSV_VERSION_MAJOR}R${OSV_VERSION_MINOR}.${OSV_VERSION_PATCH}.${OSV_VERSION_HOTFIX}"
         else
            logwarning "[${BASH_SOURCE[1]}:${BASH_LINENO[0]}] File osv-release was not found!"
            fbloadpkg="`rpm -aq --dbpath  $FALLBACKDBPATH | grep UNSPbase  2>/dev/null`" 
            fbloadversion="`rpm -qi --dbpath $FALLBACKDBPATH $fbloadpkg | grep Version | awk '{ print $3 }' 2>/dev/null`"
         fi

         fbpatchversion="`rpm -aq --dbpath $FALLBACKDBPATH | grep UNSPps[0-9][0-9][0-9][0-9]* \
                                                           | sort | tail -1 | sed -e 's/-.*//' 2>/dev/null`"
      else
         fbloadversion="`cat ${EXPORTDIR}/loadversion`"
         fbpatchversion="`cat ${EXPORTDIR}/patchversion`"
      fi
      if [ "$Restore8k" = "true" ];
      then
         if [ "$fbloadversion" = "" ];
         then
            logstr "[${_SELF_}]: Sorry, cannot determine fallback version information."
            exit $DBRESTOREFAILED
         fi
      fi
   #</DetermineFallBack>


   #<CheckForMigration>
      handleversions ################################################################################################# dbExecuter
   #</CheckForMigration>


   #<RestoreFiles>
      RESTART_SYSLOG=false
      getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  cf_type  expcftype
      getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg  node_separation  expnodesep 
      if [ "$cftype" = "$expcftype" -a "$nodesep" = "$expnodesep" -a "$testbed" = "$exptestbed" ];
      then
         for idx in $restorelist
         do
            passiveidx="`echo $idx | cut -d':' -f1`"
            activeidx="`echo $idx | cut -d':' -f2`"
            nonimgidx="`echo $idx | cut -d':' -f3`"
            diridx="`echo $idx | cut -d':' -f4`"
            logstr "RestoreFiles: passiv = $passiveidx - active = $activeidx - nonimg = $nonimgidx - dir = $diridx .... IMPORT = $SYSIMPORT"
            if [ "$SYSIMPORT" != "true" -a "$Migrate8k" != "true" ];
            then
               cp -f -p ${passiveidx}/${diridx} ${activeidx}/${diridx} 2>/dev/null
               if [ "$diridx" = "/lib/net-snmp/snmpd.conf" ]
               then
                  date >>  $LOGFILE
                  logstr "RestoreFiles: Check for differences"
                  diff ${passiveidx}/${diridx} ${activeidx}/${diridx} >> $LOGFILE
               fi
               if osv_version.sh --major compare sys ge V9 && [ -f ${passiveidx}/${diridx} -a "${diridx}" = "/etc/rsyslog.d/0_osv_forward.conf" ];
               then
                  RESTART_SYSLOG=true
               fi
            else
               restorebkup
            fi
         done 

         isSNMPv3Lost "restoresysdata" "after restorelist line:9885"

      fi
   #</RestoreFiles>
   #<AdjustFsOnMigrate8k>
      if [ "$Migrate8k" = "true" ];
      then
         adjustfsresidue
      else
         restorefsdata
      fi
   #</AdjustFsOnMigrate8k>
   
   #<SYSLOG RESTART>
   if [ "${RESTART_SYSLOG}" = "true" ]
   then
      systemctl restart rsyslog
   fi
   #</SYSLOG RESTART>

   #<HandleEtherSet>
      if [ -f /etc/init.d/etherset ];
      then
         textncolor $BoldCyan "[${_SELF_}]: Restoring etherset script."
         {
            echo '#!/bin/sh'
            echo '# Etherset script imported by toolkit'
            echo '### BEGIN INIT INFO'
            echo '# Provides: etherset'
            echo '# Required-Start: network'
            echo '# Required-Stop:'
            echo '# Default-Start: 3 5'
            echo '# Default-Stop:'
            echo '# Description: Configure the network interfaces'
            echo '### END INIT INFO'
            echo ''
            cat  /etc/init.d/etherset | egrep -v "^[\t ]*#"
         } > /tmp/etherset
         cp /tmp/etherset /etc/init.d/etherset
         chmod 755 /etc/init.d/etherset
         chown root.root /etc/init.d/etherset
         insserv /etc/init.d/etherset
         logstr "   - Running etherset on $mynode."
         /etc/init.d/etherset 1>>$LOGFILE 2>&1
         cleanarpcache
      fi
   #</HandleEtherSet>


   if [ "$mynode" = "$primhost" ];
   then

   #<ExportSecurity>
     
      if [ "$Migrate8k" = "true" ];
      then
          export ExportSecure8k=${SOLIDHOME}/migratesecure8k
          rm -rf    $ExportSecure8k
          mkdir -p  $ExportSecure8k
          chmod 777 $ExportSecure8k
          su - solid -c "cd  ${ExportSecure8k}; $solexp 'tcp 16760' dba $(getDbaPassword) PACKET_FILTERING_RULE_T" 1>/dev/null 2>&1
          su - solid -c "cd  ${ExportSecure8k}; $solexp 'tcp 16760' dba $(getDbaPassword) SECURE_ENDPOINT_T" 1>/dev/null 2>&1

          if [ -s ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat -a "$remapauxcmd" != "" ];
          then
             logstr "migrate packet filtering rules , remapauxcmd=${remapauxcmd}"
             cat ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat | sed $remapauxcmd \
                                       > ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat.new
             cp -f ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat{.new,}
             rm -f ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat.new
          fi
          cp ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat $TARGETRULES
          savesystables
      else
         #<CollectPFRules>
          export ExportSecure8k=${SOLIDHOME}/migratesecure8k
          rm -rf    $ExportSecure8k
          mkdir -p  $ExportSecure8k
          chmod 777 $ExportSecure8k
          su - solid -c "cd ${ExportSecure8k}; $solexp 'tcp 16760' dba $(getDbaPassword) PACKET_FILTERING_RULE_T" 1>/dev/null 2>&1
          if [ -s ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat -a "$remapauxcmd" != "" ];
          then
             cat ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat | sed $remapauxcmd \
                                       > ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat.new
             cp -f ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat{.new,}
             rm -f ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat.new
          fi
          cp ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat $SRCRULES
         #</CollectPFRules>
      fi
   #</ExportSecurity>


   #<DBRestore>
      textncolor $BoldCyan "[${_SELF_}]: Db restore started."
      if [ "$SYSIMPORT" != "true" -a "$Migrate8k" != "true" ];
      then
         if [ "$imagedsys" = "true" ];
         then
            BACKUPDIR=/img/optimg/${passiveimg}/unisphere/srx3000/mmgr/backup
         else
            BACKUPDIR=/opt/unisphere/srx3000/mmgr/backup
         fi
      else
         BACKUPDIR=${EXPORTDIR}
         
      fi 
      latestbackup="`ls -at  $BACKUPDIR/backup_* 2>/dev/null | head -1`"
      if [ ! -f "$latestbackup" ];
      then
         logstr "[${_SELF_}]: Sorry the latest backup $latestbackup does not exist."
         exit $DBRESTOREFAILED
      fi

      # Defensive Check making sure that any old backup left in /opt/unisphere/srx3000/mmgr/backup/ is removed.
      # After V8 PS34 , DB restore script is always using the new format backup_all.tar.gz even if a newer backup_all.tar exists
      if [ "$Migrate8k" = "true" ]
      then
         if [ "X`basename $latestbackup`X" = "Xbackup_all.tarX" ]
         then
            if [ -f /opt/unisphere/srx3000/mmgr/backup/backup_all.tar.gz ]
            then
               BDATE=`date +%Y%M%d_%h%m%s_migration`
               mv /opt/unisphere/srx3000/mmgr/backup/backup_all.tar.gz /opt/unisphere/srx3000/mmgr/backup/backup_all_${BDATE}.tar.gz
               logstr "Moved backup_all.tar.gz to backup_all_${BDATE}.tar.gz"
            fi
         fi
      fi

      cp -f $latestbackup /opt/unisphere/srx3000/mmgr/backup/
      pushd $DBSCRDIR 1>/dev/null
      #<ChangeDBPassword>
         changedbpasswds
      #<ChangeDBPassword>

      #<CheckNodeStatus>
      if [ "$testbed" = "cluster" ];
      then
         if osv_version.sh --major compare sys lt V5; 
         then
            echo "Cluster status before restore"
            echo "-----------------------------"
            cftool -n
         else
            primclstatus="`clstatus $primhost`"
            secclstatus="`clstatus $sechost`"
            echo "   - Cluster state prior to restore $primhost:$primclstatus, $sechost:$secclstatus"  
         fi
      fi
      #<CheckNodeStatus>

      ExtendedChainName=xchcom
      ExtendedStrictChain=allcom
      if [ "$upgrademode" = "OutageFree" ];
      then
         #IPv4 case
         ${IPTABLESPATH}iptables-save>/tmp/ipts-${ExtendedStrictChain}
         if [ $? -ne 0 ];
         then
            logstr "[${_SELF_}]: Cannot save security rules."
            exit $DBRESTOREFAILED
         fi
         ${IPTABLESPATH}iptables -F $ExtendedStrictChain
         ${IPTABLESPATH}iptables -F $ExtendedChainName
         {
            ${IPTABLESPATH}iptables -nL 
            arp 
         } 1>>$LOGFILE 2>&1

         #IPv6 case
         ${IPTABLESPATH}ip6tables-save>/tmp/ipts6-${ExtendedStrictChain}
         if [ $? -ne 0 ];
         then
            logstr "[${_SELF_}]: Cannot save security rules for IPv6."
            exit $DBRESTOREFAILED
         fi
         ${IPTABLESPATH}ip6tables -F $ExtendedStrictChain
         ${IPTABLESPATH}ip6tables -F $ExtendedChainName
         {
            ${IPTABLESPATH}ip6tables -nL
            arp
         } 1>>$LOGFILE 2>&1

         DOD_ENABLED=$(cfgread dod_enabled)
	 if [ "$DOD_ENABLED" = "no" ] || [ "$DOD_ENABLED" = "No" ]
	 then
            if [ "$testbed" = "cluster" ] 
            then
               ssh $othernode "cd $DBSCRDIR;$DBSCRDIR/backup.sh all" 1>>$LOGFILE 2>&1
               if [ $? -eq 0 ];
               then
		  logstr " using backup from partner node to have latest backup in order to handle latest changes"
                  scp $othernode:/opt/unisphere/srx3000/mmgr/backup/backup_all.tar.gz $latestbackup
               else
                  logstr "   - Hmm. Will use exported backup."
               fi
	    fi
	 else
	    logstr "   - JITC - Will use exported backup  since a backup on partner is too heavy."
	 fi
	 
	 # for extra debugging uncomment the next line
	 # print_tk_debug $LOGFILE

         ${IPTABLESPATH}iptables-restore</tmp/ipts-${ExtendedStrictChain}
         if [ $? -ne 0 ];
         then
            logstr "[${_SELF_}]: Cannot restore security rules."
            exit $DBRESTOREFAILED
         fi
         ${IPTABLESPATH}ip6tables-restore</tmp/ipts6-${ExtendedStrictChain}
         if [ $? -ne 0 ];
         then
            logstr "[${_SELF_}]: Cannot restore security rules for IPv6."
            exit $DBRESTOREFAILED
         fi

          sleep 20
         /unisphere/srx3000/srx/startup/srxctrl 2 `remotestate nc` 1>/dev/null 2>&1
         if [ $? -ne 0 ];
         then
            logstr "[${_SELF_}]: Cannot bring system to state#2."
            exit $DBRESTOREFAILED
         fi
         {
            pushd $SOLIDDBHOME 
            rm -f ${SOLIDDBHOME}/*.log
            tar -xvf $latestbackup solid.db 
            chown solid.dba solid.db
            chown solid.dba $SOLIDHOME
	    pushd /software/CCL_DB
            tar -xvf $latestbackup call_log.db
            chown srx.rtpgrp call_log.db
            popd
            popd
         } 1>>$LOGFILE 2>&1
         #<Convert>
         su - solid -c "solid -x convert -C RtpDb -c /opt/solid/RtpDb" 1>>$LOGFILE 2>&1
         if [ $? -ne 0 ];
         then
            textncolor $BoldCyan "[${_SELF_}]: Db conversion failed."
            exit $DBCONVERTFAILED
         fi
         waitonsolid
         #</Convert>
         textncolor $BoldCyan "Bringing system to state#3.`date`"
         if ! srxctrl 3 `remotestate nc` 1>/dev/null 2>&1; then
            logstr "[${_SELF_}]: Cannot bring system to state#3."
            exit $DBRESTOREFAILED
         fi
      else
         $DBSCRDIR/restore.sh -f 1>>$LOGFILE 2>&1

         if [ $? -ne 0 ];
         then
            logstr "[${_SELF_}]: Db restore failed."
            exit $DBRESTOREFAILED
         fi
      fi

      #<CheckNodeStatus>
      if [ "$testbed" = "cluster" ];
      then
         #<CheckHSBState>
         textncolor $BoldCyan "Waiting for database to be fully up. `date`"
         hsbstatusfile=/tmp/hsbstatus
         >$hsbstatusfile
         chmod 777 $hsbstatusfile
         while ( true );
         do
            lsof -i :16760 1>/dev/null 2>&1
            if [ $? -ne 0 ];
            then
               echo -n "."
               sleep 2
               continue;
            fi
            su - solid -c "$solsql -x onlyresults -o $hsbstatusfile -a \
               -e \"admin command 'hsb status copy' \" \"tcp 16760\" dba $(getDbaPassword)" 1>/dev/null 2>&1
            grep -qi success $hsbstatusfile
            if [ $? -eq 0 ];
            then
               break;
            fi
            su - solid -c "RtpSolid -l" | egrep 'PRIMARY ACTIVE|SECONDARY ACTIVE' | grep -q $mynode
            if [ $? -eq 0 ];
            then
               break;
            fi
            if [ "$upgrademode" = "OutageFree" ];
            then
               {
                  echo "Note:hsb status in db."
                  cat $hsbstatusfile 
               } 1>>$LOGFILE 2>&1
               su - solid -c "RtpSolid -l" | egrep 'PRIMARY' | grep -q $mynode
               if [ $? -eq 0 ];
               then
                  break;
               fi
            fi
            echo -n "."
            sleep 8
         done 
         rm -f $hsbstatusfile
         #</CheckHSBState>

         if osv_version.sh --major compare sys lt V5; 
         then
            echo "Cluster status after restore"
            echo "----------------------------"
            cftool -n
         else
            primclstatus="`clstatus $primhost`"
            secclstatus="`clstatus $sechost`"
            echo "   - Cluster state after restore $primhost:$primclstatus, $sechost:$secclstatus"  
         fi
      fi
      #</CheckNodeStatus>
      popd 1>/dev/null

      #<ExportDbRtpParms>
         DBMIGRATIONDIR=/unisphere/srx3000/srx/dbscripts/dbmigration
         if [ -f ${DBMIGRATIONDIR}/prepareRTPparams.sh ];
         then
            textncolor $BoldCyan "Exporting RTP parms for dbupdater. `date`"
            ${DBMIGRATIONDIR}/prepareRTPparams.sh
         fi
      #</ExportDbRtpParms>

      textncolor $BoldCyan "Bringing system to state#2.`date`"
      sleep 20
      /unisphere/srx3000/srx/startup/srxctrl 2 `remotestate 2` 1>/dev/null 2>&1
      if [ $? -ne 0 ];
      then
         logstr "[${_SELF_}]: Cannot bring system to state#2."
         exit $DBRESTOREFAILED
      fi
      textncolor $BoldCyan "[${_SELF_}]: Convert solid db to current engine version."
      su - solid -c "solid -x convert -C RtpDb -c /opt/solid/RtpDb" 1>/dev/null 2>&1
      if [ $? -ne 0 ];
      then
         textncolor $BoldCyan "[${_SELF_}]: Db conversion failed."
         exit $DBCONVERTFAILED
      fi
      waitonsolid

      #<ReorganizeDB>
            textncolor $BoldCyan "Reorganizing solid db. This may take some time."
            su - solid -c "solid -x reorganize" >> $LOGFILE 2>&1
            textncolor $BoldCyan "Bringing system to state#3.`date`"
            if ! srxctrl 3 `remotestate 3` 1>/dev/null 2>&1; then
               logstr "[${_SELF_}]: Cannot bring system to state#3."
               exit $DBRESTOREFAILED
            fi
            switchsolid ${mynode}
      #</ReorganizeDB>
      sync

      #</DBRestore>


      #<BoostSolidPerf>
         solidperfsetup
      #</BoostSolidPerf>

      #<DefaultLicense>
         defaultlicense
      #<DefaultLicense>

      #<DeleteH323Endpoints>
         detecth323ep
      #</DeleteH323Endpoints>

      #<CheckSymphonia>
         if [ "$profile" != "integrated" -a ! -f /etc/init.d/symphoniad ];
         then
            textncolor $BoldCyan "[${_SELF_}]: Dropping application tables in db."
            removeappsfromdb
         fi

         if [ "$profile" = "integrated" -a "X$(isOSEE)X" = "XtrueX" ]
         then
            textncolor $BoldCyan "[${_SELF_}]: Dropping application tables in db."
            removeappsfromdb 
         fi
      #</CheckSymphonia>


      #<MigrateDb>
         if [ "$Migrate8k" = "true" ];
         then
            migratedb
         else
            #<CheckDBBlocks>
               diffbksize
               if [ $? -ne 0 ];
               then
                  if osv_version.sh --major compare sys ge V8; 
                  then
                     rebuilddb
                  fi
               fi
            #</CheckDBBlocks>
            importsyspfrules
         fi
      #</MigrateDb>


      #<CleanOldRtp>
         textncolor $BoldCyan "[${_SELF_}]: Removing old RTP from Database."
         if [ -f /unisphere/srx3000/srx/dbscripts/dbmigration/RTPDBDestroy ];
         then
            logstr " calling RTPDBDestroy .... Removing old RTP from Database "
            su - srx -c "/unisphere/srx3000/srx/dbscripts/dbmigration/RTPDBDestroy" >> $LOGFILE 2>&1
            if [ $? -ne 0 ]
            then
               logstr "[${_SELF_}]: RTPDBDestroy failed."
               exit $DBRESTOREFAILED
            fi
         fi
         su - solid -c "$solsql -a -e \"drop schema RTP_USER_40\" \"tcp 16760\" dba $(getDbaPassword)" 1>/dev/null 2>&1
      #</CleanOldRtp>


      ZMODIFIED="/opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm"
      HIQALARMTCN="/opt/SMAW/SMAWrtp/cust_conf/HiqAlarmFilters.tcn"


      #<CheckRTPParms>
      if [ "$testbed" = "cluster" ];
      then

      textncolor $BoldCyan "[${_SELF_}]: checking if RTP parms match on $mynode."

      {
         cp  -p $ZMODIFIED /tmp/zModifiedParms.parm.nodea
         rscp -p ${othernode}:$ZMODIFIED /tmp/zModifiedParms.parm.nodeb

         cp  -p $HIQALARMTCN /tmp/HiqAlarmFilters.tcn.nodea
         rscp -p  ${othernode}:$HIQALARMTCN /tmp/HiqAlarmFilters.tcn.nodeb
      } 2>/dev/null

      if [ "$testbed" != "$exptestbed" ];
      then
         echo "Note: $exptestbed to $testbed conversion."
         echo "    : Will assume data from $exptestbed."
         assumenconvert=true
      else
         assumenconvert=false
      fi

      if [ "$upgrademode" != "OutageFree" ];
      then
         for rtpfile in /tmp/zModifiedParms.parm /tmp/HiqAlarmFilters.tcn
         do
            basertpfile=`basename $rtpfile`
            diff -q ${rtpfile}.nodea ${rtpfile}.nodeb 2>/dev/null
            if [ $? -ne 0 ];
            then
               if [ "$assumenconvert" = "false" ];
               then
                  logstr "Note:The RTP parms file(${basertpfile}) differs across nodes."
                  logstr "    :We will help you recover this scenario."
                  logstr "    :Following differences were found."
                  diff --suppress-common-lines ${rtpfile}.nodea ${rtpfile}.nodeb 2>/dev/null | more
               fi
               zanswer=""
               while [ "$zanswer" = "" ];
               do
                  clearstdin
                  if [ "$assumenconvert" = "false" ];
                  then
                     echo -n "Do you want to use $mynode ${rtpfile}(y/n)?"
                     zanswer="`quietread y`"
                  else
                     zanswer="y"
                  fi
                  if [ "$zanswer" = "y" -o "$zanswer" = "Y" ];
                  then
                     rscp -p ${rtpfile}.nodea ${othernode}:/opt/SMAW/SMAWrtp/cust_conf/${basertpfile}
                     rssh $othernode "chown srx.$srxgroup /opt/SMAW/SMAWrtp/cust_conf/${basertpfile} 2>/dev/null"
                     break
                  fi
                  clearstdin
                  echo -n "Do you want to use $othernode ${basertpfile}(y/n)?"
                  zanswer="`quietread y`"
                  if [ "$zanswer" = "y" -o "$zanswer" = "Y" ];
                  then
                     cp -p ${rtpfile}.nodeb /opt/SMAW/SMAWrtp/cust_conf/${basertpfile}
                     chown srx.$srxgroup /opt/SMAW/SMAWrtp/cust_conf/${basertpfile} 2>/dev/null
                     break
                  fi
                  zanswer=""
               done
               rm -f ${rtpfile}.node*
            fi
         done
     fi

   fi
   #</CheckRTPParms>

   #<CorrelationTraps>
   cat $ZMODIFIED | grep -v "Rtp/Arm/RtpArmSupprEmptyAlarmCorrelationTraps" > ${ZMODIFIED}.new
   cp -f ${ZMODIFIED}.new $ZMODIFIED
   rm -f ${ZMODIFIED}.new
   if [ "$testbed" = "cluster" ];
   then
      rscp -p $ZMODIFIED $sechost:$ZMODIFIED 2>/dev/null
   fi
   #</CorrelationTraps>


   #<CreateRtp>
   textncolor $BoldCyan "[${_SELF_}]: creating RTP on $mynode."
   if [ -f /unisphere/srx3000/srx/dbscripts/dbmigration/RTPDBDestroy ];
   then
      su - srx -c "/unisphere/srx3000/srx/dbscripts/dbmigration/RTPDBDestroy" >> $LOGFILE 2>&1
   fi
   su - solid -c "$solsql -a -e \"drop schema RTP_USER_40 cascade\" \"tcp 16760\" dba $(getDbaPassword)" 1>>$LOGFILE 2>&1
   # savebanner
   su - srx -c "createRTP -p 40" << EOF >> $LOGFILE 2>> $LOGFILE       
y
EOF
   status=$?
   if [ $status -ne 0 ];
   then
       # safety code
       RTPchecksnapshot
       status=$?
   fi
   if [ $status -ne 0 ];
   then
      textncolor $BoldRed "Could not create rtp."
      logstr "[${_SELF_}]: May be a retry after error#?"
      switchsolid ${mynode}
      sleep 8
      #<DeleteRtp>
         if [ -d /unisphere/srx3000/srx/40 ];
         then
            textncolor $BoldCyan "[${_SELF_}]: deleting RTP on $mynode."
            if [ -f /opt/SMAW/SMAWrtp/bin/deleteRTPsnc ];
            then
              deleteRTPcmd=/opt/SMAW/SMAWrtp/bin/deleteRTPsnc
            else
              deleteRTPcmd=deleteRTP
            fi
            su - srx  -c "yes 2>/dev/null | $deleteRTPcmd" 1>>$LOGFILE 2>&1
         else
            logstr "Skiping delete RTP/Nothing to delete."
         fi
      #</DeleteRtp>

      if [ -f /unisphere/srx3000/srx/dbscripts/dbmigration/RTPDBDestroy ];
      then
	 logstr " calling RTPDBDestroy .... retry ..."
         su - srx -c "/unisphere/srx3000/srx/dbscripts/dbmigration/RTPDBDestroy" >> $LOGFILE 2>&1
      fi
      su - solid -c "$solsql -a -e \"drop schema RTP_USER_40 cascade\" \"tcp 16760\" dba $(getDbaPassword)" 1>>$LOGFILE 2>&1
      su - srx -c "createRTP -p 40" << EOF >> $LOGFILE 2>> $LOGFILE
y
EOF
   status=$?
   if [ $status -ne 0 ];
   then
       RTPchecksnapshot
       status=$?
   fi
   if [ $status -ne 0 ];
   then
      # restorebanner
      exit $CREATERTPFAILED
   fi
 fi
   # restorebanner
   switchsolid ${mynode}
   #</CreateRtp>

   #<InitPacketFilterRules>
   if [ "$Migrate8k" = "true" ];
   then
      {  
         #<DetectCustomRules>
            if [ "$CUSTOMSECURITY" = "true" ];
            then
               customsecrules $SRCRULES $TARGETRULES ${ExportSecure8k}/DBA_PACKET_FILTERING_RULE_T.dat               
            fi
         #</DetectCustomRules>
         textncolor $BoldCyan "   - Loading packet filtering rules"
         export ExportSecure8k=${SOLIDHOME}/migratesecure8k
         su - solid -c "cd ${ExportSecure8k}; $solload -L ${LOGSOLIDHOME}/solload.log -b 1000 \
                         -x nointegrity 'tcp 16760' dba $(getDbaPassword) DBA_PACKET_FILTERING_RULE_T.ctr" 1>>$LOGFILE 2>&1
         rm -rf $Export8k $Import8k
      } 1>>$LOGFILE 2>&1
   fi
   #</InitPacketFilterRules>


   #<ImportRoles>
      importroles
   #</ImportRoles>


systemctl stop cla.service >> $LOGFILE
sleep 5
systemctl start cla.service >> $LOGFILE

logstr " $(systemctl status cla.service) "

   #<DbMigration>
      if [ "$skipimport" = "false" ];
      then
         textncolor $BoldGreen "[${_SELF_}]: Executing database upgrades."
         for idx in $handletype
         do
            logstr "[${_SELF_}]: Handling $idx."
            $idx
         done
      fi
   #</DbMigration>

   #<InitSecureEndpoints>
   # Loading SECURE_ENDPOINT_T target system data after the dbExecuter, so the DB schema and data
   # would have been aligned to current version. This should change in the future if any transformation
   # on the SECURE_ENDPOINT_T data takes place in dbExecuter.
   if [ "$Migrate8k" = "true" ];
   then

      su - solid -c "cd ${ExportSecure8k}; $solload -L ${LOGSOLIDHOME}/solload.log -b 1000 \
	   -x nointegrity 'tcp 16760' dba $(getDbaPassword) DBA_SECURE_ENDPOINT_T.ctr" 1>>$LOGFILE 2>&1

      rm -rf $ExportSecure8k
   fi
   #</InitSecureEndpoints>

   #<SDMUpgrader>
   if osv_version.sh --major compare sys ge V8; 
   then
       logstr "   - Upgrading BLOB data for SDM."
       su - srx -c "/unisphere/srx3000/callp/bin/dataConversionExecuter -versionUpgrade -path ${EXPORTDIR}" 1>>$LOGFILE 2>&1
       if [ $? -ne 0 ];
       then
           textncolor $BoldRed "Could not update BLOB data for SDM."
           exit $CREATERTPFAILED
       fi
   fi
   #</SDMUpgrader>


   #<OSCMigration>
     if [ "$profile" = "integrated" -a "X$(isOSEE)X" = "XfalseX" ];
     then
         if [ "$NOAPPSINDB" = "false" ];
         then
            oscimport
         else
            textncolor $BoldCyan "[${_SELF_}]: Dropping application tables in db."
            removeappsfromdb
         fi
     fi
   #</OSCMigration>


   #<ExportCustomerSchema>
      textncolor $BoldCyan "Collecting customer schema."
      setmode $BoldPurple
      export ExportAudit8k=${SOLIDHOME}/audit8k
      mkdir -p  $ExportAudit8k/reference $ExportAudit8k/customer
      chmod -R 777 $ExportAudit8k
      chown -R solid.dba $ExportAudit8k
      schemafile=/tmp/schema
      su - solid -c "$solsql -x onlyresults -o $schemafile -a \
         -e \"select table_name,table_schema from sys_tables \" \"tcp 16760\" dba $(getDbaPassword)" 1>>$LOGFILE 2>&1
      cat $schemafile  | grep -v "^$" | awk '{ print $1":"$2 }' > ${schemafile}.delim
      for schemaidx in `cat ${schemafile}.delim`
      do
            tablename=`echo $schemaidx | awk -F':' '{ print $1 }'`
            tableschema=`echo $schemaidx | awk -F':' '{ print $2 }'`
            logstr "   - Customer Definition ${tablename}/${tableschema}" 
            su - solid -c "cd  ${ExportAudit8k}/customer;$soldd -s ${tableschema} \
               -o ${ExportAudit8k}/customer/${tablename}.sql -xFKAlterTable 'tcp 16760' dba $(getDbaPassword) $tablename" 1>>$LOGFILE 2>&1
            if [ $? -ne 0 ];
            then
               logstr "[${_SELF_}]: Sorry, Solid schema for customer could not be exported."
               exit $DBRESTOREFAILED
            fi
      done
      rm -f $schemafile ${schemafile}.delim
      setmode $Norm
   #</ExportCustomerSchema>


   #<AuditDb>
      textncolor $BoldCyan "Auditing migrated schema."
      audit8kstatus=0
      for schemaidx in `ls ${ExportAudit8k}/reference/*.sql`
      do
         baseschema=`basename $schemaidx`
         if [ -f ${ExportAudit8k}/customer/$baseschema ];
         then
            diff -ibwBq ${ExportAudit8k}/reference/$baseschema ${ExportAudit8k}/customer/$baseschema >> $LOGFILE
            if [ $? -ne 0 ];
            then
               audit8kstatus=1
               echo "   - $baseschema differs." >> $LOGFILE
            else
               echo "   - $baseschema match." >> $LOGFILE
            fi
         else
               audit8kstatus=2
               echo "   - $baseschema does not exist." >> $LOGFILE
         fi
      done
      if [ $audit8kstatus -ne 0 ];
      then
         #clearstdin
         textncolor $BoldBlue "Note: Schema information collected."
         textncolor $BoldBlue "Data for analysis available under ${ExportAudit8k}."
      else
         rm -rf $ExportAudit8k
      fi
   #</AuditDb>


   #<ReduceV4R1ips>
      reduceips
   #</ReduceV4R1ips>


   #<AddaptXCHpfr>
   #because of OSV-555 
   if osv_version.sh --major compare sys ge V9; 
   then
   textncolor $BoldBlue "Modifying some xch pfrs."
cat << EOF >/tmp/change_some_pfr.sql
update packet_filtering_rule_t set DIRECTION=3 where RULE_NAME='System_Cluster_IC_Network';
update packet_filtering_rule_t set DIRECTION=3 where RULE_NAME='System_Cluster_IC_Partner_Network_2';
update packet_filtering_rule_t set DIRECTION=3 where RULE_NAME='System_Cluster_IC_Network_2';
update packet_filtering_rule_t set DIRECTION=3 where RULE_NAME='System_Cluster_IC_Partner_Network';
update packet_filtering_rule_t set DIRECTION=3 where RULE_NAME='System_IPSEC_ESP';
update packet_filtering_rule_t set DIRECTION=3 where RULE_NAME='System_IPSEC_AH';
update packet_filtering_rule_t set DIRECTION=3 where RULE_NAME='System_SIS_Server';
update packet_filtering_rule_t set DIRECTION=3 where RULE_NAME='System_Own Node';
update packet_filtering_rule_t set DIRECTION=3 where RULE_NAME='System_Partner Node';
update packet_filtering_rule_t set DIRECTION=3 where RULE_NAME='System_BMS_IP';
commit work;
EOF
  fi
chmod 777 /tmp/change_some_pfr.sql
su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) /tmp/change_some_pfr.sql" 1>>$LOGFILE 2>&1
rm /tmp/change_some_pfr.sql

   #</AddaptXCHpfr>


   #<MigrateApplications>
      if [ "$Migrate8k" = "true" -a -f /enterprise/servicetools/install/bin/changeSFWip.sh -a "X$(isOSEE)X" = "XfalseX" ];
      then
         logstr "   - Migrating application."
         /enterprise/servicetools/install/bin/changeSFWip.sh -F -c change 1>>$LOGFILE 2>&1
      fi
      #<FixMSSettings>    
         if [ "$profile" = "integrated" -a "$NOAPPS" = "false" -a "X$(isOSEE)X" = "XfalseX" ];
         then
            importmssettings
         fi
      #</FixMSSettings>    
      #<Rebranding>
         if osv_version.sh --major compare sys ge V7 && [ "X$(isOSEE)X" = "XfalseX" ];
         then
            REBRANDROOT=/enterprise/share/tomcat/webapps/management
            if [ -d ${EXPORTDIR}/${REBRANDROOT}/rebranding ];
            then
               logstr "   - Rebranding applications. This might take a while."
               {
                  pushd $REBRANDROOT
                  cp -R -p ${EXPORTDIR}/${REBRANDROOT}/rebranding ${REBRANDROOT}/.
                  ${REBRANDROOT}/rebrand.sh 
                  popd
               } 1>>$LOGFILE 2>&1
            fi
         fi
      #</Rebranding>
   #<MigrateApplications>


   textncolor $BoldCyan "[${_SELF_}]: Creating a checkpoint."
   su - solid -c "$solsql -a -e \"admin command 'makecp -s' \" \"tcp 16760\" dba $(getDbaPassword)"

   #<SysAtState#4>
      textncolor $BoldCyan "[${_SELF_}]: Stopping the system.`date`"
      sleep 20
      /unisphere/srx3000/srx/startup/srxctrl 2 `remotestate 2` 1>>$LOGFILE 2>&1
      if [ $? -ne 0 ];
      then
         logstr "[${_SELF_}]: Cannot bring system to state#2."
         exit $DBRESTOREFAILED
      fi

      #<ReorganizeDB>
         textncolor $BoldCyan "Reorganizing solid db. This may take some time."
         chown solid.dba $SOLIDDBHOME/solid.db
         if [ "$testbed" = "cluster" ];
         then
            rssh $othernode "chown solid.dba $SOLIDDBHOME/solid.db 2>/dev/null"
         fi
         su - solid -c "solid -x reorganize" >> $LOGFILE 2>&1
      #</ReorganizeDB>

      #<BoostSolidPerf>
         solidperfclean
      #<BoostSolidPerf>

      enablearpsig 
      textncolor $BoldCyan "[${_SELF_}]: Starting up the system.`date`"
      if ! srxctrl 4 `remotestate 4` 1>>$LOGFILE 2>&1; then
         logstr "[${_SELF_}]: Cannot bring system to state#4."
         disablearpsig
         exit $DBRESTOREFAILED
      fi
      disablearpsig

      switchsolid ${mynode}
      if [ -f /etc/init.d/symphoniad -a "X$(isOSEE)X" = "XfalseX" ];
      then
         checkappstatus start local
         if [ "$testbed" = "cluster" ];
         then
            checkappstatus start remote
         fi
      fi
      #<DeleteObsoleteParms>
      #if [ "$buildid" \> "V8" ];
      #then
      #   deleteparms
      #fi
      #</DeleteObsoleteParms>
      #<AuditDropRule>
         logstr "[*] Auditing Security on node $mynode."
         ${IPTABLESPATH}iptables -n -L 9000 | tail -1 | grep DROP 1>>$LOGFILE 2>&1
         if [ $? -ne 0 ];
         then
            logstr "   - Note: Drop rule missing in chain 9000. Your security is open."
            logstr "   - Hint: run iptables -n -L -v as user root to see more data."
            logstr "   -     : Check /log/HiqLogSwError.log for unresolved rules."
         fi
         if [ "$testbed" = "cluster" ];
         then
            logstr "[*] Auditing Security on node $othernode."
            rssh $othernode "iptables -n -L 9000 | tail -1 | grep DROP 1>>$LOGFILE 2>&1"
            if [ $? -ne 0 ];
            then
               logstr "   - Note: Drop rule missing in chain 9000. Your security is open."
               logstr "   - Hint: run iptables -n -L -v as user root to see more data."
               logstr "   -     : Check /log/HiqLogSwError.log for unresolved rules."
            fi
         fi
      #</AuditDropRule>
   #</SysAtState#4>

   #<HomeDnAudit>
   if [ -x /unisphere/srx3000/srx/soap_scripts/run_homedn_audit.ksh ];
   then
      chown srx.rtpgrp /var/tmp/audit_homedns.xml 1>/dev/null 2>&1
      su - srx -c "/unisphere/srx3000/srx/soap_scripts/run_homedn_audit.ksh" 1>>$LOGFILE 2>&1
   fi
   lookbusy 32
   checkprocs

   textncolor $BoldCyan "[${_SELF_}]: Starting srx security."
   /etc/init.d/srx_security start trusted 1>>$LOGFILE 2>&1
   if [ "$testbed" = "cluster" ];
   then
      rssh $othernode "/etc/init.d/srx_security start trusted 1>>$LOGFILE 2>&1"
   fi

   if osv_version.sh --major compare sys ge V4 && osv_version.sh --major compare sys lt V7;
   then
      deletecstacustom
   fi

   textncolor $BoldCyan "[${_SELF_}]: Creating a checkpoint."
   su - solid -c "$solsql -a -e \"admin command 'makecp -s' \" \"tcp 16760\" dba $(getDbaPassword)"
   su - solid -c "$solsql -a -e \"admin command 'status' \" \"tcp 16760\" dba $(getDbaPassword)"

   grep -q "/dev/shm" $SOLINI
   if [ $? -eq 0 ];
   then
      logstr "Checking solid.ini: error"
   else
      logstr "Checking solid.ini: ok"
   fi

   if osv_version.sh --major compare sys lt V8; 
   then
      textncolor $BoldCyan "[${_SELF_}]: Provisioning treatments during upgrade."
      if [ -f /unisphere/srx3000/callp/tools/ms_tr_upgrade.sh ];
      then
         pgrep soapServer 1>/dev/null 2>&1
         if [ $? -eq 0 ];
         then
            logstr "   - Checking soapserver : o.k."
            su - srx -c "/unisphere/srx3000/callp/tools/ms_tr_upgrade.sh" 1>>$LOGFILE 2>&1
         else
            logstr "   - Checking soapserver : not started."
         fi
      fi
   fi

   else
      if [ "$LIVE8kUPGRADE" = "true" ];
      then
         logstr "[${_SELF_}]: Completing update on $mynode."
         if [ -f /etc/init.d/heartbeat ];
         then
            pgrep heartbeat 1>/dev/null 2>&1
            if [ $? -ne 0 ];
            then
               logstr "   - Starting heartbeat"
               /etc/init.d/heartbeat start 1>>$LOGFILE 2>&1
            fi
         fi
         if [ ! -d /unisphere/srx3000/srx/40 ];
         then
             logstr "   - Recreating RTP for $mynode."
             changedbpasswds
	     sleep 20
             /unisphere/srx3000/srx/startup/srxctrl 2 nc
             chown solid.dba $SOLIDDBHOME/solid.db
             srxctrl 3 nc
             LIVE8kUPGRADE=false
             if [ "$mynode" = "$primhost" ];
             then
                othernode=$sechost
             else
                othernode=$primhost
             fi
            #  savebanner
             su - srx  -c "yes | addtoRTP" 1>/dev/null 2>&1
             if [ $? -ne 0 ];
             then
                logstr "[${_SELF_}]: May be a retry after error#?"
                su - srx -c "RtpSolid -X" 
                sleep 8
                DROPRTPNODE=/tmp/droprtpnode
                {
                   echo "set catalog RTPDB;"
                   echo "delete from RTP_CREATED_NODES where RTP_UNAME='$mynode';"
                   echo "commit work;"
                } > $DROPRTPNODE
                su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $DROPRTPNODE" 1>>$LOGFILE 2>&1
                su - srx  -c "yes | addtoRTP" 1>/dev/null 2>&1
                if [ $? -ne 0 ];
                then
                   logstr "[${_SELF_}]: Sorry could not run addtoRTP."
                   textncolor $BoldRed "[${_SELF_}]: <$mynode>:Failed."
                   exit $DBRESTOREFAILED
                fi
             fi
            #  restorebanner
             LIVE8kUPGRADE=true
         fi
         
         enablearpsig
         /unisphere/srx3000/srx/startup/srxctrl -Q oprtt 
         if ! srxctrl 4 nc 1>>$LOGFILE 2>&1; then
            textncolor $BoldRed "[${_SELF_}]: <$mynode>:Failed."
            disablearpsig
            exit $DBRESTOREFAILED
         fi
         disablearpsig
		 
	 # for extra debugging uncomment the next line
         # print_tk_debug $LOGFILE

      fi
   fi

   #<RestorePSAP912>
   # Check if we are in PSAP mode
   if [ "${OSV_EMERGENCY_MODE}" = "PSAP" ];
   then
     logstr "[${_SELF_}]: PSAP912: OSV in PSAP mode. Checking for exported files."
     if [ -d ${PSAP912_EXPORTDIR} ];
     then
       logstr "[${_SELF_}]: PSAP912: Running import utility in ${PSAP912_EXPORTDIR}"
       su - srx -c "cd ${PSAP912_EXPORTDIR}; ${PSAP912_EXPORTDIR}/${PSAP912_IMPORTCMD}" 1>>$LOGFILE 2>&1
     else
       logstr "[${_SELF_}]: PSAP912: module configuration files not found in ${PSAP912_EXPORTDIR}."
     fi
   else # Not PSAP
     logstr "[${_SELF_}]: PSAP912: OSV not in PSAP mode." 
   fi
   #</RestorePSAP912>



   if [ "$NOAPPS" = "true" -a "X$(isOSEE)X" = "XfalseX" ];
   then

   if osv_version.sh --major compare sys ge V4 && [ "$profile" = "integrated" ];
   then
      if [ "$mynode" = "$primhost" ];
      then
         if [ "$NOAPPSINDB" = "false" ];
         then
            echo "    --------------------------------------------------------------------------- "
            echo "    //////////////////// Applications Migration /////////////////////////////// "
            echo "    --------------------------------------------------------------------------- "
            echo "   |Note: You have to install applications separately.                         |"
            if [ -f /etc/hiq8000/response.cfg ];
            then
            echo "   |    : The response.cfg has been setup for you at                           |"
            echo "   |    :      - /etc/hiq8000/response.cfg on each node.                       |"
            echo "   |    : This response.cfg is set up for upgrades.Use it for install.         |"
            fi
            echo "   |    : Download the latest DVD/patchset for applications.                   |"
            echo "   |    : Consult install instructions in the release notes for DVD/patchset.  |" 
            echo "    --------------------------------------------------------------------------- "
         fi
      fi
   fi

   fi


   textncolor $BoldCyan "[${_SELF_}]: <$mynode>:Success."

   else # if [ "$instmode" = "normal" ];
   
      textncolor $BoldCyan "[${_SELF_}]: instmode<$instmode>, hence nothing to restore."
      
   fi
   #<Normal installs>
   snmpV3restore
   cloudlinkRestore
   adaptkeyboard
}

# ----------------------------------------------------------------
# function: findusb
# args    : none
# description:
#   Well this is tricky. We have usb's that are formatted on windows
#   or linux or on timbaktoo os. We have to give our best shot.
#   We look for all devices  except  and try to see if they
#   are mountable. If we find any usb that has node.cfg then we say
#   hooray!. The complexity is compunted by sub partitioning the
#   drive, in which case we have to search all partitions.
# ----------------------------------------------------------------

findusb( )
{
   logdebug "Function findusb called with arguments [${*}]"
   
   accessmode=$1
   count=1
   while ( true )
   do
      logdebug "Trying to detect the configuration path, try #${count}"
      
      floppy="/dev/fd0"
      ideiso="/dev/hda /dev/hdb /dev/hdc /dev/hdd /dev/hde /dev/sr0 /dev/sr1"
      scsilist=`sg_map -i | awk '{ print $2 }' | grep -v "/dev/sda" | grep "^/dev/"`
      fdisklist=`fdisk -l 2>/dev/null | grep -v "/dev/sda" | grep "^/dev" | grep -v grep | awk '{ print $1 }'`
      auxfdisklist=`fdisk -l 2>/dev/null | grep -v "/dev/sda" | sed -e 's/^Disk //g' | grep "^/dev" | \
                            grep -v grep | awk '{ print $1 }' | sed -e 's/://g'`
      disklist="${CFGMNTPATH} ${scsilist} ${fdisklist} ${auxfdisklist} ${floppy} ${ideiso}"
      
      logdebug "Searching for configuration path in all possible locations [${disklist}]"
      
      # START - Search all possible paths
      for i in $disklist
      do
         logdebug "Searching for configuration path in [${i}]"
	 
	 #<FRN2661-NodeCfgOnFS>
         MNTDEVICE=""
         if [ "$i" != "$CFGMNTPATH" ];
         then
            mountdev=true
            _mount | sort | uniq | grep -e "$i[ \t]*"
            status=$?
            if [ $status -ne 0 ];
            then
               selfmount=true
               MNTPATH=/mnt
               MNTDEVICE=$i    
               mount $i $MNTPATH  1>/dev/null 2>&1
               status=$?
            else
               MNTENTRY=`_mount  | grep -e \"$i[ \t]*\"`
               MNTPATH=`echo ${MNTENTRY} | awk '{ print $3 }'`
               mount $MNTPATH 1>/dev/null 2>&1
               if [ $? -eq 0 ];
               then
                  selfmount=true
               else
                  selfmount=false
               fi
            fi
         else
            mountdev=false
            MNTPATH=$i
            status=0
            selfmount=false
         fi
         #</FRN2661-NodeCfgOnFS>
         if [ $status -eq 0 -a -f "$MNTPATH/node.cfg.primary" ];
         then
            primary="$MNTPATH/node.cfg.primary"
            CFGPATH=$primary
            cp -f $primary /etc/hiq8000/node.cfg.toolkit8k
	    logdebug "Node.cfg file found in [${i}]"
	    
            break;
         elif [ $status -eq 0 -a -f "$MNTPATH/node.cfg.secondary" ];
         then
            secondary="$MNTPATH/node.cfg.secondary"
            CFGPATH=$secondary
            cp -f $secondary /etc/hiq8000/node.cfg.toolkit8k
	    logdebug "Node.cfg file found in [${i}]"
	    
            break;
         fi
         if [ "$selfmount" = "true" ];
         then
            umount $MNTPATH  1>/dev/null 2>&1
         fi
      done
      # END - Search all possible paths
      
      
      if [ "$primary" != "" -o "$secondary" != "" ];
      then
          if [ "$mountdev" = "true" -a "$selfmount" = "false" -a "$CHECK4USB" = "false" ];
          then
             textncolor $BoldRed "Note: Its possible usb stick was mounted by the user."
             textncolor $BoldRed "    : Its users responsibility to unmount before pulling out the usb stick."
             textncolor $BoldRed "    : Loss of exported data might occur if usb stick is pulled out before unmounting."
             textncolor $BoldRed "    : Press enter to continue." 
             clearstdin
             zanswer="`quietread y`"
          fi
          textncolor $BoldCyan "Found data(${primary}${secondary})"


          ### ACCESS MODE: SAVE ###
	  if [ "$accessmode" = "save" ]; 
          then
             textncolor $BoldCyan "Saving files :- "
             rm -rf ${EXPORTDIR}
             mkdir -p $MNTPATH/patch
             if [ "$HW" = "true" ];
             then
                touch $MNTPATH/patch/hwupdate
                if [ $? -ne 0 ];
                then
                   textncolor $BoldRed "Failed to copy hwupdate to device. Check device content or device itself."
                   exit $NOSPACEONDEVICE
                fi
             else
                rm -f $MNTPATH/patch/hwupdate
             fi
             origcksum="`md5sum ${EXPORTFILE} | awk '{ print $1 }'`"
             cp ${EXPORTFILE} $MNTPATH/patch
             rm -f  $MNTPATH/remaposv.cfg
             sync
             if [ -f /etc/hiq8000/remaposv.cfg ];
             then
                origremapcksum="`md5sum /etc/hiq8000/remaposv.cfg | awk '{ print $1 }'`"
                cp /etc/hiq8000/remaposv.cfg $MNTPATH/.
                sync
                usbremapcksum="`md5sum $MNTPATH/remaposv.cfg 2>/dev/null | awk '{ print $1 }'`"
                if [ "$origremapcksum" != "$usbremapcksum" ];
                then
                   textncolor $BoldRed "Failed to copy to device. Check device content or device itself."
                   exit $NOSPACEONDEVICE
                fi
             fi
             status=$?
             sync
             usbcksum="`md5sum $MNTPATH/patch/export.tar 2>/dev/null | awk '{ print $1 }'`"
             {
                echo "Built export.tar cksum : $origcksum"
                echo "Usb   export.tar cksum : $usbcksum"
             } >> $LOGFILE
             if [ "$selfmount" = "true" ];
             then
                if [ "$CFGMNTPATH" = "" ];
                then
                   logstr "   - Usb was mounted by toolkit."
                fi
                umount $MNTPATH  1>/dev/null 2>&1
                if [ "$MNTDEVICE" != "" ];
                then
                   logstr "   - Verifying, read back after close."
                   mount $MNTDEVICE $MNTPATH
                   if [ $? -eq 0 ];
                   then
                      vusbcksum="`md5sum $MNTPATH/patch/export.tar 2>/dev/null | awk '{ print $1 }'`"     
                      if [ "$vusbcksum" != "$usbcksum" ];
                      then
                         textncolor $BoldRed "Failed to copy to device. Check device content or device itself."
                         exit $NOSPACEONDEVICE
                      fi
                   else
                      umount $MNTPATH 1>/dev/null 2>&1
                      textncolor $BoldRed "Failed to remount device. Check device content or device itself."
                      exit $NOSPACEONDEVICE
                   fi
                   umount $MNTPATH 1>/dev/null 2>&1
                fi
             fi
             if [ $status -ne 0 -o "$origcksum" != "$usbcksum" ];
             then
                textncolor $BoldRed "Failed to copy to device. Check device content or device itself."
                exit $NOSPACEONDEVICE
             fi
             rm -f $EXPORTFILE
          else ### ACCESS MODE: SAVE ###
             
	     ### ACCESS MODE: RESTORE ###
         if [ "$accessmode" = "restore" ];
         then
	     
             ###########################################################################     
			 # Check in the migration scenario of OSEE V8R1 to V9 and above,
             # if the node.cfg in MNTPATH differs from the system's. If they do we need to abort.
             diff -s -q /etc/hiq8000/node.cfg ${CFGPATH} 1>/dev/null 2>&1
             local diffexitcode=$?

             logdebug "Diff of system and imported node.cfg: $(diff -s -q /etc/hiq8000/node.cfg ${CFGPATH}; echo "Diff exit code: [${diffexitcode}]")"
             logdebug "MD5 checksum of system[$(md5sum /etc/hiq8000/node.cfg)] and imported node.cfg[$(md5sum ${CFGPATH})]"

             if [ "X$(isOSEE)X" = "XtrueX" -a ${diffexitcode} -ne 0 -a "X${Migrate8k}X" = "XtrueX" ]
             then
                 textncolor $BoldRed "You are trying to migrate to an OSEE V9 (or later) system,
while using an unsuitable node.cfg file [${CFGPATH}].
You should copy the system's /etc/hiq8000/node.cfg to ${CFGPATH} prior invoking the migrate8k program.
Aborting..."
                 exit $FAIL
             fi #  if [ "X$(isOSEE)X" = "XtrueX" -a ${diffexitcode} -ne 0 ]
			 ###########################################################################
		
		if [ -f $MNTPATH/patch/export.tar ];
                then
		
                   textncolor $BoldCyan "Restoring files :- "
                   rm -rf ${EXPORTDIR}
		   
		   logdebug "Copying $MNTPATH/patch/export.tar to $EXPORTFILE"
                   cp -f $MNTPATH/patch/export.tar $EXPORTFILE 2>/dev/null
		   
		   if [ -f /etc/hiq8000/remaposv.cfg ]
		   then
		   	logstr "   - Removing Solution entities mapping file"
			logdebug "Solution entities mapping file contents: $(echo; cat /etc/hiq8000/remaposv.cfg)"
                   	rm -f /etc/hiq8000/remaposv.cfg
		   fi
                   
		   # In case of migration to target OSEE V9 and above, nothing should be
		   # taken from remaposv.cfg, as these endpoints are already configured to the 
		   # system in first boot reconfiguration with the vApp.iso
		   if [ -f $MNTPATH/remaposv.cfg -a "X$(isOSEE)X" = "XfalseX" ]
                   then
                      cp -f $MNTPATH/remaposv.cfg /etc/hiq8000/remaposv.cfg
                      storedmagic=`cat /etc/hiq8000/remaposv.cfg | grep "^#Magic" | tail -1 | awk -F ':' '{ print $2 }'`
                      remapmagic=`cat  /etc/hiq8000/remaposv.cfg | grep -v "^#" | md5sum | awk '{ print $1 }'`
                      if [ "$storedmagic" != "" -a "$storedmagic" != "$remapmagic" ];
                      then
                         logstr "   - Detected Solution entities mapping file in configuration path."
                         cat /etc/hiq8000/remaposv.cfg >> $LOGFILE
                         cat /etc/hiq8000/remaposv.cfg> /etc/hiq8000/remaposv.cfg.new
                         cp  -f /etc/hiq8000/remaposv.cfg{.new,}
                         rm -f /etc/hiq8000/remaposv.cfg.new
			 
			 logdebug "File /etc/hiq8000/remaposv.cfg contents: $(echo; cat /etc/hiq8000/remaposv.cfg)"
                      else
                         logdebug "Removing file /etc/hiq8000/remaposv.cfg, contents: $(echo; cat /etc/hiq8000/remaposv.cfg)"
			 rm -f /etc/hiq8000/remaposv.cfg
                      fi
                   fi
                   
		   # Do not import the OSV licenses in OSEE V9 and above
		   if [ -d /opt/unisphere/srx3000/cla/import -a "X$(isOSEE)X" = "XfalseX" ]
                   then
                      logstr "   - Openscape Voice system license restoration from exported data in ${MNTPATH}"
		      logdebug "Copying exported licenses [$MNTPATH/*H8K*lic, $MNTPATH/*OpenScape*Voice*lic] to /opt/unisphere/srx3000/cla/import"
		      logdebug "License files: $(echo; ls -l $MNTPATH/*H8K*lic; ls -l $MNTPATH/*OpenScape*Voice*lic)"
		      licenses_found=0
		      
		      for licfile in $(find -L ${MNTPATH} -maxdepth 1 -name '*H8K*lic' | xargs)
		      do
		          licenses_found=1 && \
			  cp -vf "${licfile}" /opt/unisphere/srx3000/cla/import/ && \
			  logstr "   * Restored license file ${licfile}"
		      done

		      for licfile in $(find -L ${MNTPATH} -maxdepth 1 -name '*OpenScape*Voice*lic' | xargs)
		      do
                          licenses_found=1 && \
			  cp -vf "${licfile}" /opt/unisphere/srx3000/cla/import/ && \
			  logstr "   * Restored license file ${licfile}"
		      done

                      # OSV-9542:
                      # In this phase, bond1 interface is down.
                      # So if signaling interface is used as default gateway, license import will fail.
                      # To overcome this issue, save *.lic files to a temporary place and try again after join8k
                      # Hint: Search for "Reimporting any valid licenses" message in upgrade8k to track the next attempt.
                      [ "${LIVE8kUPGRADE}" = "true" ] && \
                      mkdir -p /repository/license    && \
                      find -L ${MNTPATH} -maxdepth 1 -type f \( -name \*OpenScape\*.lic -o -name \*H8K\*.lic \) -exec cp {} /repository/license/ \;
                   fi
                   
		   # Do not import UC applications licenses in OSEE V9 and above
		   # as the OSVE system does not host applications any more.
		   if [ -d /enterprise/common/conf/license -a "X$(isOSEE)X" = "XfalseX" ]
                   then
                      logstr "   - Enterprise Applications license restoration from exported data in ${MNTPATH}"
		      logdebug "Copying [$MNTPATH/*/*OpenScape*lic] to /enterprise/common/conf/license"
		      logdebug "License files: $(echo; find -L ${MNTPATH} -name '*OpenScape*lic' ! -name '*OpenScape*Voice*lic' -exec ls -l {} \;)"
		      
                      uc_licenses_found=0
		      for licfile in $(find -L ${MNTPATH} -name '*OpenScape*lic' ! -name '*OpenScape*Voice*lic' | xargs)
		      do
		          uc_licenses_found=1 && \
			  cp -vf ${licfile} /enterprise/common/conf/license && \			  
			  logdebug "Setting owneship to [sym:sym] and read permissions to all users for file [${licfile}]" && \
			  chown sym:sym "${licfile}" && chmod a+r "${licfile}"
		      done
                   fi
		   
		   
		   # Extract the exported user data
		   logdebug "Extracting the export TAR archive to /software"
                   pushd /software 1>/dev/null 2>&1
                       tar -zxf $EXPORTFILE
                       status=$?
                       rm -f $EXPORTFILE
                   popd 1>/dev/null 2>&1
		   
                   
		   if [ "$selfmount" = "true" ];
                   then
                      logstr "   - USB drive was mounted by toolkit."
                      umount $MNTPATH  1>/dev/null 2>&1
                   fi
		   
                else # if [ -f $MNTPATH/patch/export.tar ];
		
                   if [ "$selfmount" = "true" ];
                   then
                      logstr "   - USB drive was mounted by toolkit."
                      umount $MNTPATH  1>/dev/null 2>&1
                   fi
		   
                   textncolor $BoldCyan "[${_SELF_}]: Nothing to import, the patch/export.tar archive was not found."
		   
                   exit $NOEXPORTONDEVICE
		   
                fi
		
                if [ $status -ne 0 ];
                then
                   textncolor $BoldRed "[${_SELF_}]: Failed to extract the exported data from device!"
		   textncolor $BoldRed "Check your exported content and the disk usage in /software filesystem, you may be out of free space."
                   exit $NOSPACEONDEVICE
                fi
          else ### ACCESS MODE: RESTORE ###
             
	     ### ACCESS MODE: CHECK ###
	     if [ "$accessmode" = "check" ];
             then
                if [ -f $MNTPATH/patch/export.tar ];
                then
                   checkstatus=$SUCCESS
                else 
                   checkstatus=$NOEXPORTONDEVICE
                fi
                if [ "$selfmount" = "true" ];
                then
                   logstr "   - USB drive was mounted by toolkit."
                   umount $MNTPATH  1>/dev/null 2>&1
                fi
                exit $checkstatus
             else ### ACCESS MODE: CHECK ###
                
		### ACCESS MODE: ZEN ###
		if [ "$accessmode" = "zen" ];
                then
                   zenbuildid="`fcfgread $CFGPATH srx_build_id | awk -F'.' '{ print $1 }'`"
		   logstr " zenbuildid found is $zenbuildid"
                   zen $CFGPATH
                   checkstatus=$?
                   if [ "$LIVE8kUPGRADE" = "true" ];
                   then
                      for liveidx in `find ${MNTPATH} -maxdepth 1 -mindepth 1 \
                                      -name "node.cfg.primary" -o             \
                                      -name "node.cfg.secondary"`
                      do
                         cp $liveidx /repository/upload/.
                      done
                      for liveidx in `find ${MNTPATH}/patch -maxdepth 1 -mindepth 1 \
                                      -name "${zenbuildid}*.tar" -o                 \
                                      -name "${zenbuildid}*.spa" -o                 \
                                      -name "dev.8kps"           -o                 \
                                      -name "*.rpm"`
                      do
                         cp $liveidx /repository/upload/.
                      done
                   fi
                   for liveidx in `find ${MNTPATH} -maxdepth 1 -mindepth 1 -name "*.lic"` 
                   do
                      cp $liveidx /repository/upload/.
                   done
                   if [ "$selfmount" = "true" ];
                   then
                      logstr "   - USB drive was mounted by toolkit."
                      umount $MNTPATH  1>/dev/null 2>&1
                   fi
                   if [ $? -eq 0 ];
                   then
                      if osv_version.sh --major compare "$zenbuildid" lt V6;
                      then
                         logstr "   - Your target version should be V6 or greater."
                         checkstatus=$FAIL
                      fi
                   fi
                   exit $checkstatus
                else ### ACCESS MODE: ZEN ###
                   
		   ### ACCESS MODE: NONE ###
		   if [ "$selfmount" = "true" ];
                   then
                      umount $MNTPATH  1>/dev/null 2>&1
                   fi
		   ### ACCESS MODE: NONE ###
		   
                fi
             fi
          fi

          fi
          break;
      else
          if [ $count -eq 8 ];
          then
             logstr "Could not find usb stick ..."
             textncolor $BoldPurple "   - Quit Looking for a usb which contains node.cfg.primary or node.cfg.secondary"
             textncolor $BoldPurple "   - place node.cfg.primary or node.cfg.secondary on your usb sticks."
             textncolor $BoldPurple "   - This will solve your problem."
             exit $NOUSBSTICK
          else
             logstr "Could not find usb stick in $count attempt. Will try again ..."
             count=`expr $count + 1`
             sleep 16
             continue
          fi
      fi
done
sync

}

# ---------------------------------------------------------------
# function: exportroles
# args    : None
# description:
#    exports rtp data of users and roles.
# ---------------------------------------------------------------

exportroles( )
{
      rm -f /tmp/rtproles /tmp/admusers
      pgrep -x solid  1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         #[1]. Get current version
         su - solid -c "$solsql -a -e \"select RTP_TABLE_NAME,RTP_CURR_SUFFIX from RTP_TABLE_MGMT\" \"tcp 16760\" dba $(getDbaPassword)" 1>${EXPORTDIR}/rtptablemgmt 2>&1
         rtprolesuffix="`grep RTP_ADM_ROLES ${EXPORTDIR}/rtptablemgmt | awk '{ print $2 }'`"
         admuserssuffix="`grep RTP_ADM_USERS ${EXPORTDIR}/rtptablemgmt | awk '{ print $2 }'`"
         #[2]. Export roles
         su - solid -c "$solexp -o  /tmp/rtproles 'tcp 16760' dba $(getDbaPassword) RTP_ADM_ROLES${rtprolesuffix}" 1>/dev/null 2>&1
         if [ $? -eq 0 ];
         then
            logstr "   - Successfully exported rtproles."
            cp -p -f /tmp/rtproles ${EXPORTDIR}/rtproles
            rm -f /tmp/rtproles
         else
            rm -f ${EXPORTDIR}/rtproles 
            logstr "   - Skipping exporting rtproles."
         fi
         #[2]. Export users
         su - solid -c "$solexp -o  /tmp/admusers 'tcp 16760' dba $(getDbaPassword) RTP_ADM_USERS${rtprolesuffix}" 1>/dev/null 2>&1
         if [ $? -eq 0 ];
         then
            logstr "   - Successfully exported rtpusers."
            cp -p -f /tmp/admusers ${EXPORTDIR}/admusers
            rm -f /tmp/admusers
         else
            rm -f ${EXPORTDIR}/admusers
            logstr "   - Skipping exporting rtproles."
         fi
      else
         logstr "   - Skipping exporting rtproles."
      fi
}

# ---------------------------------------------------------------
# function: exportfileparam
# args    : None
# description:
#    export some parameters from the files that sould be changed with package uptates
#    if files don'e exist in target system or source system, does nothing
# ---------------------------------------------------------------
 
exportfileparam( ){

for file in "${parameter_files[@]}"
   do
      if [ -z ${EXPORTDIR} ]; then
         EXPORTDIR=/software/export
      fi

      mkdir -p /software/export

      if [ -f $file ]; then
      
         logstr "[${_SELF_}]: Exporting file $file to ${EXPORTDIR}"

         real_path=$(readlink -f $file) #some files are symlinks

         cp -r --parents $real_path ${EXPORTDIR}"/"
         if [ "$?" -ne 0 ]; then
            logstr "[${_SELF_}]: Exporting of file $file failed. Skipping..."
         fi
         mv -f ${EXPORTDIR}"/"$real_path ${EXPORTDIR}"/"$file

      else
         logstr "[${_SELF_}]: File $file is missing, skipping..."
      fi
   done

}

# ---------------------------------------------------------------
# function: sshdconfig_add_ciphers_macs
# args    : None
# description:
#   Exports sshd configuration and appends ciphers / macs
#   in case they're not available in sshd_config
# ---------------------------------------------------------------

sshdconfig_add_ciphers_macs( )
{
   exported_sshd_config_file=${EXPORTDIR}/etc/ssh/sshd_config
   local ciphers=""
   local macs=""
   if [ -f ${exported_sshd_config_file} ]
   then
      ciphers=$( grep -i ciphers ${exported_sshd_config_file} )
      macs=$( grep -i macs ${exported_sshd_config_file} )
   else
      logstr "[${_SELF_}]: File /etc/ssh/sshd_config is missing..."
   fi
   if [ "$ciphers" = "" -o "$macs" = "" ]
   then
      echo "Trying to retrieve SSHd Ciphers and Macs from the running configuration..."
      sshd_running_config=$( sshd -T )
      if [ "$ciphers" = "" ]
      then
         ciphers=$( echo "${sshd_running_config}" | grep -i ciphers | awk '{print $2}' )
         echo "Ciphers $ciphers" >> ${exported_sshd_config_file}
      fi
      if [ "$macs" = "" ]
      then
         macs=$( echo "${sshd_running_config}" | grep -i macs | awk '{print $2}' )
         echo "MACs $macs" >> ${exported_sshd_config_file}
      fi
   fi
   if [ "$ciphers" = "" -o "$macs" = "" ]
   then
      echo "Unable to retrieve Ciphers / Macs..."
   fi
}

# ---------------------------------------------------------------
# function: exportdata
# args    : None
# description:
#   saves system data of current active image onto usb.
# ---------------------------------------------------------------

exportdata( ) 
{
   SYSEXPORT=true
   #<SupportNonImaged>
      if [ "$singleimaged" != "true" ];
      then
         BACKUPDIR=/img/optimg/${activeimg}/unisphere/srx3000/mmgr/backup
      else
         BACKUPDIR=/opt/unisphere/srx3000/mmgr/backup
      fi
   #</SupportNonImaged>
   rm -rf   ${EXPORTFILE} ${EXPORTDIR} /etc/hiq8000/remaposv.cfg $BACKUPDIR/backup_all.tar
   mkdir -p ${EXPORTDIR}
   savesysdata "$ARGLIST"
   #<Check4Backup>
      if [ "$mynode" = "$primhost" -o "$RECOVER8k" = "true" ];
      then
         latestbackup="`ls -at  $BACKUPDIR/backup_* 2>/dev/null | head -1`"
         if [ ! -f "$latestbackup" ];
         then
            logstr "[${_SELF_}]: Sorry the latest backup $latestbackup does not exist."
            exit $DBEXPORTFAILED
         else
            bkdirname="`dirname $latestbackup`"
            bkfilename="`basename $latestbackup`"
            cp -p $latestbackup ${EXPORTDIR}/${bkfilename}
         fi
         #<InterestingEp's>
            detectgateways
         #</InterestingEp's>
      fi
   #</Check4Backup>

   #<CollectSecRules>
      ${IPTABLESPATH}iptables -n -L -v > ${EXPORTDIR}/iptables
      ${IPTABLESPATH}ip6tables -n -L -v > ${EXPORTDIR}/ip6tables
   #</CollectSecRules>

   #<CollectRoles>
      exportroles
   #</CollectRoles>
   
   #<ExportFiles>
      for idx in $restorelist
      do
         passiveidx="`echo $idx | cut -d':' -f1`"
         activeidx="`echo $idx | cut -d':' -f2`"
         nonimgidx="`echo $idx | cut -d':' -f3`"
         diridx="`echo $idx | cut -d':' -f4`"
         logstr "exportfiles: passiv = $passiveidx - active = $activeidx - nonimg = $nonimgidx - dir = $diridx"
         bkfilename="${nonimgidx}/${diridx}"
         bkdirname="`dirname $bkfilename`"
         mkdir -p ${EXPORTDIR}/${bkdirname}
         cp -f -p ${bkfilename} ${EXPORTDIR}/${bkdirname} 2>/dev/null
      done

      isSNMPv3Lost "exportdata" "after restorelist line:11452"

      for idx in $savelist
      do
         if [ -e $idx ];
         then
            cp -r --parents $idx ${EXPORTDIR}
         else
            logstr "exportfiles: Something is wrong with $idx in savelist"
         fi
      done

      if [ "$HW" = "true" -a -f /etc/sec/setkey.conf.old_liveupgrade ]
      then
         cp -p /etc/sec/setkey.conf.old_liveupgrade ${EXPORTDIR}/seckeys
      fi

   exportfileparam
   #</ExportFiles>

   #<ExportSSHdCiphersMacs>
   sshdconfig_add_ciphers_macs # this function should be called after exportfileparam
   #</ExportSSHdCiphersMacs>

   #<Dos2UnixCert>
   for certsidx in `cat ${EXPORTDIR}/certs 2>/dev/null`
   do
      if [ "$certsidx" != "" -a -d $certsidx ];
      then
         for cfile in `find $certsidx -maxdepth 1 -mindepth 1 -type f -size -64k -name \*`
         do
            dos2unix ${EXPORTDIR}/$cfile >>$LOGFILE 2>&1
         done
      fi
   done
   #</Dos2UnixCert>

   #<ExportOSCData>
      if [ "$profile" = "integrated" -a "X$(isOSEE)X" = "XfalseX" ];
      then
          oscexport
      fi
   #</ExportOSCData>

   #<Export License alf file>
   if osv_version.sh --major compare sys ge V8; 
   then
      cp -p --parents /unisphere/srx3000/callp/bin/*.alf ${EXPORTDIR}
   fi
   #</Export License alf file>
   
   pushd /software 1>/dev/null 2>&1
   textncolor $BoldCyan "[${_SELF_}]: Creating final archive for $mynode."
   rm -rf   $EXPORTBKDIR
   mkdir -p ${EXPORTBKDIR}/${mynode}/patch 
   rm -f ${EXPORTBKDIR}/${mynode}/remaposv.cfg
   if [ -f ${EXPORTDIR}/remaposv.cfg ];
   then
      cp ${EXPORTDIR}/remaposv.cfg ${EXPORTBKDIR}/${mynode}/.
   fi
   {
      find /repository/upload -maxdepth 1 -type f \( -name \*OpenScape\*.lic -o -name \*H8K\*.lic \) -exec cp -f {} ${EXPORTBKDIR}/${mynode}/. \; 
      find /repository/media -maxdepth 1 -type f \( -name \*OpenScape\*.lic -o -name \*H8K\*.lic \) -exec cp -f {} ${EXPORTBKDIR}/${mynode}/. \; 
   } 2>/dev/null
   if [ "$othernode" != "" ];
   then
      mkdir -p ${EXPORTBKDIR}/${othernode}/patch
   fi
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "[${_SELF_}]: Creating final archive repository for <$mynode> : failed."
      textncolor $BoldRed "Hint: Check permissions for $EXPORTBKDIR."
      exit $FAIL
   fi
   tar -zcvf $EXPORTFILE export 1>/dev/null 2>&1
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "[${_SELF_}]: Creating final archive for <$mynode> : failed."
      textncolor $BoldRed "Hint: Check space under $EXPORTBKDIR."
      exit $FAIL
   fi
   popd 1>/dev/null

   cp $EXPORTFILE ${EXPORTBKDIR}/${mynode}/patch/.
   if [ $? -ne 0 ];
   then
      textncolor $BoldRed "[${_SELF_}]: Copying final archive for <$mynode> : failed."
      textncolor $BoldRed "Hint: Check space under $EXPORTBKDIR."
      exit $FAIL
   fi
   if [ "$mynode" = "$primhost" ];
   then
      cp /etc/hiq8000/node.cfg ${EXPORTBKDIR}/${mynode}/node.cfg.primary
   else
      cp /etc/hiq8000/node.cfg ${EXPORTBKDIR}/${mynode}/node.cfg.secondary
   fi
   latestps=${latestps:-"None"}
   {
      echo "Export created on `date`" 
      echo "Build: $buildid"
      echo "Patchset: $latestps"
      echo "PrimaryNode:$primhost"
      echo "SecondaryNode:$sechost"
   } > ${EXPORTBKDIR}/date
   sync

   if [ "$LOCAL4USB" = "false" ];
   then
      findusb "save"
   fi

   getcfgvar ${EXPORTDIR}/etc/hiq8000/node.cfg srx_build_id expbuildid

   #<CheckSAMischef>
      sarunning=""
      ZMOD=/opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm
      grep -q "Srx/Main/SurvivalAuthority" $ZMOD 1>/dev/null 2>&1
      if [ $? -eq 0 ];
      then
         sarunning=`grep "Srx/Main/SurvivalAuthority" $ZMOD | awk -F'=' '{ print $2 }' | sed -e 's/ //g'` 
      else
         EXPSADIR=/etc/opt/SMAW
         if osv_version.sh --major compare "$expbuildid" lt V4; 
         then
            sarunning=`                                                              \
                 grep survival-authority ${EXPSADIR}/SMAWsf/SA_die.cfg 2>/dev/null | \
                 awk '{ print $2 }' | sed -e 's/[ \t]*//g'                           \
            `
         else
            if osv_version.sh --major compare "$expbuildid" lt V5; 
            then
            sarunning=`                                                              \
                 grep survival-authority ${EXPSADIR}/SMAWsf/SaQuery.cfg 2>/dev/null |\
                 awk '{ print $2 }' | sed -e 's/[ \t]*//g'                           \
            `
            fi
         fi
      fi
      if [ "$sarunning" != "" ];
      then
         sainstalled=`cfgread survival_authority`
         if [ "$sarunning" != "$sainstalled" ];
         then
            textncolor $BoldRed "Your setting in node.cfg for $mynode does not match customer settings."
            textncolor $BoldRed "Make sure to check the following settings in your node.cfg."
            logstr "   - Survival Authority in node.cfg : $sainstalled"
            logstr "   - Survival Authority used        : $sarunning"
            echo -n "Press enter when done ..."
            answer="`quietread yes`"
            echo ""
         fi
      fi
   #</CheckSAMischef>
   
   #<CleanLocalDir>
   if [ "$LOCAL4USB" = "true" ];
   then
      rm -rf $EXPORTDIR
      rm $EXPORTFILE
   fi
   #</CleanlLocalDir>
   #<OSEE V8R1 export DLS db>
   if [ "x$(isV8OSEE)x" = "xtruex" ]
   then
     /enterprise/share/tomcat/webapps/DeploymentService/database/dbexport.sh ${EXPORTBKDIR}/${mynode}/dls_db.zip 1>>$LOGFILE 2>&1
     if [ $? -ne 0 ]
     then
        textncolor $BoldRed "error on exporting DLS database"
        exit $FAIL
     fi
   fi
   #</OSEE V8R1 export DLS db>

   echo                 "/////////////////////////////////////"
   textncolor $BoldCyan "[${_SELF_}]: Data exported successfully."
   echo                 "/////////////////////////////////////"
   textncolor $BoldPurple   "Done."
}

# ---------------------------------------------------------------
# function: set_tos
# args    : None
# description:
#    set the TOS for the cross-connect channel. This is normally set with /etc/init.d/hiQPolicy but
#    during live upgrade on node 1 hiQPolicy is not run as it is called through bz_node_com_test.
#    
#
set_tos()
{

   DEFAULT_XCHAN_CONTROL_TOS=0x98                   # default TOS value for the heartbeat traffic - to convert to DSCP, shift right by 2 bits
   DEFAULT_XCHAN_DATA_TOS=0x58                      # default TOS value for other xconnect data - to convert to DSCP, shift right by 2 bits
   HEARTBEAT_PORT=47022

   CONTROL_TOS="`cfgread ci_control_tos`"
   if [ "X${CONTROL_TOS}X" = "XX" ]
   then
      CONTROL_TOS=$DEFAULT_XCHAN_CONTROL_TOS
   fi
   
   DATA_TOS="`cfgread ci_data_tos`"
   if [ "X${DATA_TOS}X" = "XX" ]
   then
      DATA_TOS=$DEFAULT_XCHAN_DATA_TOS
   fi

   CONTROL_TOS=`expr $(($CONTROL_TOS / 4))`
   DATA_TOS=`expr $(($DATA_TOS / 4))`

   PARTNER_XCHAN_IP=`cfgread nafo3 | awk '{print $5}'`

   ${IPTABLESPATH}iptables -t mangle -A POSTROUTING -d $PARTNER_XCHAN_IP -j DSCP --set-dscp $DATA_TOS
   ${IPTABLESPATH}iptables -t mangle -A POSTROUTING -d $PARTNER_XCHAN_IP -p udp --dport $HEARTBEAT_PORT -j DSCP --set-dscp $CONTROL_TOS


  logdebug "set tos for DSCP"
}
# ---------------------------------------------------------------
# function: importdata
# args    : None
# description:
#   restores system data of current active image from usb.
# ---------------------------------------------------------------

importdata( ) 
{
   logdebug "Function importdata called"
   
   #<CheckUpgradeMode>
      if [ "$upgrademode" = "OutageFree" ];
      then

         if [ -x /usr/local/bin/update_system_configuration ]
         then
            # check if there are any changes need to be performed by update_system_configuration
            sysctl_changes=`/usr/local/bin/update_system_configuration -p`
            changes_sysctl_need=$?
            
            loginfo "Changes to be applied by update_system_configuration: \n ${sysctl_changes} "
            if [ ${changes_sysctl_need} -ne 0 ]
            then
               loginfo "applying sysctl changes through update_system_configuration"
               /usr/local/bin/update_system_configuration -a
            fi

         fi 
         textncolor $BoldPurple "[${_SELF_}]: Note, you are upgrading $mynode in outage free mode."
         LIVE8kUPGRADE=true
         if ! srxctrl 3 `remotestate 3`  1>>$LOGFILE 2>&1; then
            textncolor $BoldRed "[${_SELF_}]: Could not bring system to state#3."
            exit $FAIL
         fi
      else
         logdebug "Packet filtering rules: $(echo; iptables-save)"
	 logdebug "Setting packet filtering rules policies to ACCEPT for INPUT, OUTPUT, FORWARD chains and flushing all rules from filter table..."
	 
	 #<RemoveOldSecurityRules>
            ${IPTABLESPATH}iptables -P INPUT ACCEPT 
            ${IPTABLESPATH}iptables -P OUTPUT ACCEPT 
            ${IPTABLESPATH}iptables -P FORWARD ACCEPT 
            ${IPTABLESPATH}iptables -F

            ${IPTABLESPATH}ip6tables -P INPUT ACCEPT
            ${IPTABLESPATH}ip6tables -P OUTPUT ACCEPT
            ${IPTABLESPATH}ip6tables -P FORWARD ACCEPT
            ${IPTABLESPATH}ip6tables -F
         #</RemoveOldSecurityRules>
	 
	 logdebug "Packet filtering rules: $(echo; iptables-save)"
      fi
   #</CheckUpgradeMode>


   # Search all possible locations for exported data to restore
   findusb "restore"
   
   
   ################################################
   ### Restore the exported data to this system ###
   if [ "$hipath8k" = "true" ];
   then
      restoresysdata "$ARGLIST"
       
      #<ShowCustomRules>
         if [ "$Migrate8k" = "true" -a -f /log/custom.rules ];
         then
            setmode $BoldBlue
            cat /log/custom.rules
            setmode  $Norm
         fi
      #</ShowCustomRules>
   else
      if [ "X$(isOSEE)X" = "XfalseX" ]
      then
         offboardoscimport
      fi
   fi
   ################################################
   
   
   ################################################
   #<CheckUpgradeMode>
      if [ "$upgrademode" = "OutageFree" ];
      then
         textncolor $BoldPurple "[${_SELF_}]: Note, you are upgrading $mynode in outage free mode."
         LIVE8kUPGRADE=true
         if ! srxctrl 4 `remotestate 4`  1>>$LOGFILE 2>&1; then
            textncolor $BoldRed "[${_SELF_}]: Could not bring system to state#4."
            exit $FAIL
         fi
      fi
   #</CheckUpgradeMode>
   ################################################
   
   
   ################################################
   #<RebuildSecurity>
      if osv_version.sh --major compare sys ge V7; 
      then
         if [ -x /usr/local/bin/osv_install_security ];
         then
            /usr/local/bin/osv_install_security -u
         fi
      fi
   #</RebuildSecurity>
   #<AddDCSPValues>
   if [ "X${upgrademode}X" = "XOutageFreeX" -a "X${testbed}X" = "XclusterX" -a "X${primary}X" != "XX" ]
   then
      set_tos
   fi
   #</AddDSCPValues>
   ################################################
   

   if [ "$IMPORTPASSWD" = "true" ];
   then
      textncolor $BoldPurple "[${_SELF_}]: Note, your passwords were imported."
   fi
   textncolor $BoldCyan "[${_SELF_}]: Data imported successfully."
}

# ------------------------------------------------------------
# function: savebanner
# args    : None
# description:
#   save the banner file prior to RTP op's.
# ------------------------------------------------------------

# savebanner( )
# {
#    SSHDCFG=/etc/ssh/sshd_config
#    if [ -f $SSHDCFG ];
#    then
#       bannerfile="`cat $SSHDCFG | egrep \"^Banner[ \t]*\" | awk '{ print $2 }'`"
#       if [ "$bannerfile" != "" -a -f "$bannerfile" ];
#       then
#          logstr "   - Saving banner:$bannerfile."
#          rm -f ${bannerfile}.prepare8k
#          mv -f $bannerfile{,.prepare8k}
#          >${bannerfile}
#          if [ "$testbed" = "cluster" ];
#          then
#            rssh  ${othernode} -o ConnectTimeout=8 "rm -f ${bannerfile}.prepare8k;mv -f $bannerfile{,.prepare8k};>${bannerfile}" 1>/dev/null 2>&1
#          fi
#       # else
#          # if [ -f /etc/issue ];
#          # then
#          #    logstr "   - Saving banner:/etc/issue."
#          #    rm -f /etc/issue.prepare8k
#          #    mv /etc/issue{,.prepare8k}
#          #    >/etc/issue
#          #    if [ "$testbed" = "cluster" ];
#          #    then
#          #       rssh  ${othernode} -o ConnectTimeout=8 "rm -f /etc/issue.prepare8k;mv -f /etc/issue{,.prepare8k};>/etc/issue" 1>/dev/null 2>&1
#          #    fi
#          # fi
#       fi
#    fi
# }

# ------------------------------------------------------------
# function: restorebanner
# args    : None
# description:
#   restore the banner file prior to RTP op's.
# ------------------------------------------------------------

# restorebanner( ) 
# {
#    SSHDCFG=/etc/ssh/sshd_config
#    if [ -f $SSHDCFG ];
#    then
#       bannerfile="`cat $SSHDCFG | egrep \"^Banner[ \t]*\" | awk '{ print $2 }'`"
      # if [ "$bannerfile" != "" -a -f "$bannerfile" -a -f "${bannerfile}.prepare8k" ];
      # then
      #     logstr "   - Restoring banner:$bannerfile."
      #     rm -f $bannerfile
      #     mv -f $bannerfile{.prepare8k,} 
      #     if [ "$testbed" = "cluster" ];
      #     then
      #        rssh  ${othernode} -o ConnectTimeout=8 "mv -f $bannerfile{.prepare8k,}" 1>/dev/null 2>&1
      #     fi
      # else
      #    if [ -f /etc/issue.prepare8k ];
      #    then
      #       logstr "   - Restoring banner:/etc/issue."
      #       mv /etc/issue{.prepare8k,}
      #    fi
      #    if [ "$testbed" = "cluster" ];
      #    then
      #       rssh  ${othernode} -o ConnectTimeout=8 "mv -f /etc/issue{.prepare8k,}" 1>/dev/null 2>&1
      #    fi
      # fi
#    fi
# }

# ------------------------------------------------------------
# function: deletertp
# args    : None
# description:
#   delete's rtp for cip change.
# ------------------------------------------------------------

deletertp( )
{
   if [ "$mynode" = "$primhost" ];
   then
      textncolor $BoldCyan "[${_SELF_}]: Bringing system to state#3.`date`"
      if ! srxctrl 3 `remotestate 3`  1>>$LOGFILE 2>&1; then
           logstr "[${_SELF_}]: Cannot bring system to state#2."
           exit $FAIL
      fi
      switchsolid ${mynode}

      #<DeleteRtp>
         if [ -d /unisphere/srx3000/srx/40 ];
         then
            textncolor $BoldCyan "[${_SELF_}]: deleting RTP on $mynode."
            if [ -f /opt/SMAW/SMAWrtp/bin/deleteRTPsnc ];
            then
              deleteRTPcmd=/opt/SMAW/SMAWrtp/bin/deleteRTPsnc
            else
              deleteRTPcmd=deleteRTP
            fi
            # savebanner
            su - srx  -c "yes 2>/dev/null | $deleteRTPcmd" 1>>$LOGFILE 2>&1 
            status=$?
            # restorebanner
            if [ $status -ne 0 ];
            then
               textncolor $BoldRed "[${_SELF_}]: deleting RTP failed."
               exit $FAIL
            fi
         else
            logstr "Skiping delete RTP/Nothing to delete."
         fi
      #</DeleteRtp>
   fi
   textncolor $BoldCyan "[${_SELF_}]: Bringing system to state#2.`date`"
   sleep 20
   /unisphere/srx3000/srx/startup/srxctrl 2 `remotestate 2`  1>>$LOGFILE 2>&1
   if [ $? -ne 0 ];
   then
      logstr "[${_SELF_}]: Cannot bring system to state#2."
      exit $FAIL
   fi
   echo "2 2 /log/startup_srx.log /log/startup_rtp.log" > /unisphere/srx3000/srx/startup/srxBootParams

}

# ------------------------------------------------------------
# function: creatertp
# args    : None
# description:
#   create's rtp for cip change.
# ------------------------------------------------------------

creatertp( )
{
   if [ "$mynode" = "$primhost" ];
   then
      textncolor $BoldCyan "[${_SELF_}]: Bringing system to state#3.`date`"
      if ! srxctrl 3 `remotestate 3`  1>>$LOGFILE 2>&1; then
           logstr "[${_SELF_}]: Cannot bring system to state#3."
           exit $FAIL
      fi
      switchsolid ${mynode}

      if [ ! -d /unisphere/srx3000/srx/40 ];
      then
         #<CreateRtp>
         textncolor $BoldCyan "[${_SELF_}]: creating RTP on $mynode."
         if [ -f /unisphere/srx3000/srx/dbscripts/dbmigration/RTPDBDestroy ];
         then
	    logstr " calling RTPDBDestroy .... creating RTP on $mynode "
            su - srx -c "/unisphere/srx3000/srx/dbscripts/dbmigration/RTPDBDestroy" >> $LOGFILE 2>&1
         fi
         su - solid -c "$solsql -a -e \"drop schema RTP_USER_40 cascade\" \"tcp 16760\" dba $(getDbaPassword)" 1>>$LOGFILE 2>&1
         removertpfromdb
         # savebanner
         su - srx -c "createRTP -p 40" << EOF >> $LOGFILE
y
EOF
        status=$?
      #   restorebanner
        if [ $status -ne 0 ];
        then
           RTPchecksnapshot
           status=$?
        fi
        if [ $status -ne 0 ];
        then
           textncolor $BoldRed "[${_SELF_}]: Could not create rtp."
           exit $CREATERTPFAILED
         fi
         switchsolid ${mynode}
         #</CreateRtp>
      fi
   fi
   echo "4 4 /log/startup_srx.log /log/startup_rtp.log" > /unisphere/srx3000/srx/startup/srxBootParams
}

# ------------------------------------------------------------
# function: cipswap
# args    : None
# description:
#   swap the cip's with new configuration as in node.cfg.
# ------------------------------------------------------------

cipswap( )
{
   MASTERCFG8k=/etc/hiq8000/node.cfg
   CFG8k=/etc/hiq8000/node.cfg.toolkit8k

   if [ ! -f $CFG8k ];
   then
      textncolor $BoldCyan "[${_SELF_}]: Could not locate new node.cfg."
      exit $FAIL
   fi

   getcfgvar $MASTERCFG8k srx_build_id       oldbuildid
   getcfgvar $MASTERCFG8k cf_type            oldcftype
   nafoxch="`fcfgread $MASTERCFG8k nafo3`"
   logstr "   - Processing for source build $oldbuildid."
   if osv_version.sh --major compare "$oldbuildid" lt V5 || [ "$nafoxch" = "" ];
   then
      getcfgvar $MASTERCFG8k node_1_cip_logical oldprimcip
      getcfgvar $MASTERCFG8k node_2_cip_logical oldseccip
      getcfgvar $MASTERCFG8k cip_network        oldprimcipnw
      getcfgvar $MASTERCFG8k cip2_network       oldseccipnw
      getcfgvar $MASTERCFG8k cip_netmask        oldprimcipnm
      getcfgvar $MASTERCFG8k cip2_netmask       oldseccipnm
      getcfgvar $MASTERCFG8k cip_gateway        oldcipgw
      getcfgvar $MASTERCFG8k cip2_gateway       oldcip2gw
      getcfgvar $MASTERCFG8k cip_broadcast      oldcipbr
   else
      export oldprimcip="`echo $nafoxch   | awk '{ print $4 }'`"
      export oldseccip="`echo $nafoxch    | awk '{ print $5 }'`"
      export oldprimcipnw="`echo $nafoxch | awk '{ print $7 }'`"
      export oldseccipnw="`echo $nafoxch  | awk '{ print $10 }'`"
      export oldprimcipnm="`echo $nafoxch | awk '{ print $6 }'`"
      export oldseccipnm="`echo $nafoxch  | awk '{ print $9 }'`"
      export oldcipbr="`echo $nafoxch     | awk '{ print $8 }'`"
      export oldseccipbr="`echo $nafoxch  | awk '{ print $11 }'`"
      export oldcipgw="`fcfgread  $MASTERCFG8k xch_1_gateway`"
      export oldcip2gw="`fcfgread $MASTERCFG8k xch_2_gateway`"
   fi

   getcfgvar $CFG8k srx_build_id       newbuildid
   getcfgvar $CFG8k cf_type            newcftype
   nafoxch="`fcfgread $CFG8k nafo3`"
   logstr "   - Processing for target build $newbuildid."
   if osv_version.sh --major compare "$oldbuildid" lt V5 || [ "$nafoxch" = "" ];
   then
      getcfgvar $CFG8k node_1_cip_logical newprimcip
      getcfgvar $CFG8k node_2_cip_logical newseccip
      getcfgvar $CFG8k cip_network        newprimcipnw
      getcfgvar $CFG8k cip2_network       newseccipnw
      getcfgvar $CFG8k cip_netmask        newprimcipnm
      getcfgvar $CFG8k cip2_netmask       newseccipnm
      getcfgvar $CFG8k cip_gateway        newcipgw
      getcfgvar $CFG8k cip2_gateway       newcip2gw
      getcfgvar $CFG8k cip_broadcast      newcipbr
   else
      export newprimcip="`echo $nafoxch   | awk '{ print $4 }'`"
      export newseccip="`echo $nafoxch    | awk '{ print $5 }'`"
      export newprimcipnw="`echo $nafoxch | awk '{ print $7 }'`"
      export newseccipnw="`echo $nafoxch  | awk '{ print $10 }'`"
      export newprimcipnm="`echo $nafoxch | awk '{ print $6 }'`"
      export newseccipnm="`echo $nafoxch  | awk '{ print $9 }'`"
      export newcipbr="`echo $nafoxch     | awk '{ print $8 }'`"
      export newseccipbr="`echo $nafoxch  | awk '{ print $11 }'`"
      export newcipgw="`fcfgread  $CFG8k xch_1_gateway`"
      export newcip2gw="`fcfgread $CFG8k xch_2_gateway`"
   fi

   clusterbonddeva=`cfgread cluster_dev | awk '{ print $1 }'`
   clusterbonddevb=`cfgread cluster_dev | awk '{ print $2 }'`

   if [ "$oldcftype" != "$newcftype" ];
   then
      textncolor $BoldCyan "Cip swapping allowed only for compatible iterconnects(l2:l2 or l3:l3)."
      exit $SUCCESS
   fi

   cipfiles="
      /etc/default/cluster
      /etc/hosts
      /etc/sec/setkey.conf
      /etc/sysconfig/network/ifcfg-bondcf0
      /etc/sysconfig/network/ifroute-bondcf0
      /etc/sysconfig/network/ifcfg-bond3
      /etc/sysconfig/network/ifroute-bond3
      /unisphere/srx3000/callp/etc/sec/FILT_START.txt
      /opt/SMAW/SMAWrtp/conf/RtpClustertab
      /etc/cip.cf
      /etc/netmasks
      /etc/sysconfig/network/ifcfg-${clusterbonddeva}
      /etc/sysconfig/network/ifcfg-${clusterbonddevb}
   "

   WorkSpace=/software/workspace
   if [ "$mynode" = "$primhost" ];
   then
       textncolor $BoldCyan "[${_SELF_}]: Adjusting packet filter rules in database.`date`"
       if ! srxctrl 3 `remotestate 3`  1>>$LOGFILE 2>&1; then
           logstr "[${_SELF_}]: Cannot bring system to state#3."
           exit $DBRESTOREFAILED
       fi
       switchsolid ${mynode}
       pfsql=/tmp/pfsql
       {
          echo "update PACKET_FILTERING_RULE_T"
          echo "set LOCAL_IP_ADDR='$newprimcip',REMOTE_IP_ADDR='$newprimcipnw',REMOTE_NETMASK='$newprimcipnm'"
          echo "where RULE_NAME='Cluster_IC_Network';"

          echo "update PACKET_FILTERING_RULE_T"
          echo "set LOCAL_IP_ADDR='$newseccip',REMOTE_IP_ADDR='$newseccipnw',REMOTE_NETMASK='$newseccipnm'"
          echo "where RULE_NAME='Cluster_IC_Network_2';"

          echo "update PACKET_FILTERING_RULE_T"
          echo "set LOCAL_IP_ADDR='$newprimcip',REMOTE_IP_ADDR='$newseccipnw',REMOTE_NETMASK='$newseccipnm'"
          echo "where RULE_NAME='Cluster_IC_Partner_Network';"

          echo "update PACKET_FILTERING_RULE_T"
          echo "set LOCAL_IP_ADDR='$newseccip',REMOTE_IP_ADDR='$newprimcipnw',REMOTE_NETMASK='$newprimcipnm'"
          echo "where RULE_NAME='Cluster_IC_Partner_Network_2';"

          echo "commit work;"
       } > $pfsql
       su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $pfsql" 1>>$LOGFILE 2>&1
       
       textncolor $BoldCyan "[${_SELF_}]: Bringing system to state#2.`date`"
       sleep 20
       /unisphere/srx3000/srx/startup/srxctrl 2 `remotestate 2`  1>>$LOGFILE 2>&1
       if [ $? -ne 0 ];
       then
           logstr "[${_SELF_}]: Cannot bring system to state#2."
           exit $DBRESTOREFAILED
       fi
    fi
    rm -rf $WorkSpace
    mkdir -p $WorkSpace/oldcips $WorkSpace/newcips
    echo " ------------------------------------------------------ "
    echo "|                Cip Reconfiguration                   |"
    echo " ------------------------------------------------------ "
    echo " cip-logical:"
    echo "              `echo ${oldprimcip}   |  awk '{ printf "%16s",$1 }'`  -> ${newprimcip}"
    echo "              `echo ${oldseccip}    |  awk '{ printf "%16s",$1 }'`  -> ${newseccip}"
    echo " cip-nw     :"
    echo "              `echo ${oldprimcipnw} |  awk '{ printf "%16s",$1 }'`  -> ${newprimcipnw}"
    echo "              `echo ${oldseccipnw}  |  awk '{ printf "%16s",$1 }'`  -> ${newseccipnw}"
    echo " cip-nm     :"
    echo "              `echo ${oldprimcipnm} |  awk '{ printf "%16s",$1 }'`  -> ${newprimcipnm}"
    echo "              `echo ${oldseccipnm}  |  awk '{ printf "%16s",$1 }'`  -> ${newseccipnm}"
    echo " cip-gw     :"
    echo "              `echo ${oldcipgw}     |  awk '{ printf "%16s",$1 }'`  -> ${newcipgw}"
    echo "              `echo ${oldcip2gw}    |  awk '{ printf "%16s",$1 }'`  -> ${newcip2gw}"
    echo ""
    cp -f /etc/hiq8000/node.cfg $WorkSpace/oldcips
    for cipidx in $cipfiles
    do
          echo "            - $cipidx"
          if [ -f $cipidx ];
          then
             cat $cipidx | sed -e "s/${oldprimcipnm}/${newprimcipnm}/g" \
                               -e "s/${oldseccipnm}/${newseccipnm}/g"   \
                               -e "s/${oldprimcipnw}/${newprimcipnw}/g" \
                               -e "s/${oldseccipnw}/${newseccipnw}/g"   \
                               -e "s/${oldcipgw}/${newcipgw}/g"         \
                               -e "s/${oldcip2gw}/${newcip2gw}/g"       \
                               -e "s/${oldprimcip}/${newprimcip}/g"     \
                               -e "s/${oldseccip}/${newseccip}/g"       \
                            > ${cipidx}.cipswap
              cp -f $cipidx $WorkSpace/oldcips
              cp -f ${cipidx}.cipswap $WorkSpace/newcips/`basename ${cipidx}`
              cp ${cipidx}.cipswap $cipidx
              rm -f ${cipidx}.cipswap
           fi
    done

    #[1]. Default cluster settings.
    echo "            - /opt/SMAW/SMAWrtp/cust_conf/SrxSystemDependent.parm"
    cat /opt/SMAW/SMAWrtp/cust_conf/SrxSystemDependent.parm |                                                              \
    sed    -e "s/Srx\/Main\/node1CIPLogical.*/Srx\/Main\/node1CIPLogical              customer string = ${newprimcip}/g"   \
           -e "s/Srx\/Main\/node1CIPNetwork.*/Srx\/Main\/node1CIPNetwork              customer string = ${newprimcipnw}/g" \
           -e "s/Srx\/Main\/node1CIPNetmask.*/Srx\/Main\/node1CIPNetmask              customer string = ${newprimcipnm}/g" \
           -e "s/Srx\/Main\/CIPGateway.*/Srx\/Main\/CIPGateway                        customer string = ${newcipgw}/g"     \
           -e "s/Srx\/Main\/node2CIPLogical.*/Srx\/Main\/node2CIPLogical              customer string = ${newseccip}/g"    \
           -e "s/Srx\/Main\/node2CIPNetwork.*/Srx\/Main\/node2CIPNetwork              customer string = ${newseccipnw}/g"  \
           -e "s/Srx\/Main\/node2CIPNetmask.*/Srx\/Main\/node2CIPNetmask              customer string = ${newseccipnm}/g"  \
           -e "s/Srx\/Main\/CIP2Gateway.*/Srx\/Main\/CIP2Gateway                      customer string = ${newcip2gw}/g"    \
           -e "s/Srx\/Main\/CIPBroadcast.*/Srx\/Main\/CIPBroadcast                    customer string = ${newcipbr}/g"     \
       > /opt/SMAW/SMAWrtp/cust_conf/SrxSystemDependent.parm.cipswap
       cp -f /opt/SMAW/SMAWrtp/cust_conf/SrxSystemDependent.parm $WorkSpace/oldcips
       cp -f /opt/SMAW/SMAWrtp/cust_conf/SrxSystemDependent.parm.cipswap $WorkSpace/newcips/SrxSystemDependent.parm
       cp /opt/SMAW/SMAWrtp/cust_conf/SrxSystemDependent.parm.cipswap /opt/SMAW/SMAWrtp/cust_conf/SrxSystemDependent.parm
       rm -f /opt/SMAW/SMAWrtp/cust_conf/SrxSystemDependent.parm.cipswap

    #[2]. node.cfg
    echo "            - /etc/hiq8000/node.cfg"
    cp /etc/hiq8000/node.cfg.toolkit8k /etc/hiq8000/node.cfg
    cp -f /etc/hiq8000/node.cfg $WorkSpace/newcips

    #[3]. known hosts
    cipfiles="
      /unisphere/srx3000/srx/.ssh/known_hosts \
      /root/.ssh/known_hosts                  \
    "
    for cipidx in $cipfiles
    do
       echo "            - $cipidx"
       cat $cipidx | sed -e "s/${oldprimcip}/${newprimcip}/g"  \
                         -e "s/${oldseccip}/${newseccip}/g"    \
                   > ${cipidx}.ciprestore
       cat $cipidx | sed -e "s/${oldprimcip}/${oldprimcip},${newprimcip}/g"  \
                         -e "s/${oldseccip}/${oldseccip},${newseccip}/g"     \
                   > ${cipidx}.cipswap
       cp -f $cipidx $WorkSpace/oldcips
       cp ${cipidx}.cipswap $cipidx
       cp $cipidx $WorkSpace/newcips
       rm -f ${cipidx}.cipswap
    done
 
    echo " ------------------------------------------------------ "
    textncolor $BoldCyan "Reboot your nodes for cluster changes to take effect"
}

# ---------------------------------------------------------------
# function: detectgateways
# args    : None
# description:
#   detects all gateways in the system. Gives a crisp view of
#   setup.
# ---------------------------------------------------------------

detectgateways( )
{
    {
      echo "#//////////////////////////////////////////////////////////////////////////"
      echo "#Important Note: Do not Modify the header comment signature."
      echo "#ToolkitUpgrade-EntityManager: `date`"
      echo -n "#Rev: "
      rpm -aq UNSPmigration | tail -1
      echo "#This file is used to manage solution entities such as gateways and cmp's."
      echo "#Place it on the usb stick on same level as node.cfg.[primary|secondary]"
      echo "#During a migration you may need to move these solution entities."
      echo "#Modify the ip's below to reflect the correct mapping."
      echo "#For e.g. if a proxy 10.236.90.102 was migrated to 10.152.232.12 then place"
      echo "#gateway:ProxyName:10.236.90.102:10.152.232.12:*"
      echo "#For e.g. if a proxy fd::1 was migrated to fd::2 then place"
      echo "#gateway:ProxyName:[fd::1]:[fd::2]:*"
      echo "#Also note that entities e.g. [wise.upgrade.toolkit.com] represent fqdns."
      echo "#These will be used during migrations."
      echo "#Syntax:"
      echo "#   objecttype:associatedname:ip|fqdn:newenity:action"
      echo "#   If one of IP is is IPv6 then both IPs need to be included in brackets"
      echo "#   objecttype:"
      echo "#      gateway:      external proxy or gateway."
      echo "#      mediagateway: external media gateway."
      echo "#      management:   external management entity like cmp."
      echo "#      packetfilter: custom pfr."
      echo "#      cdrhost:      external cdr source for backup of cdr."
      echo "#   oldentity:"
      echo "#      ip or fqdn. For some objects like management/packetfilter we need" 
      echo "#      netmask too." 
      echo "#      If the IP is IPv6 then we need to include it in brackets (e.g [fd::1])."
      echo "#      We also need to include it in brackets if it is IPv4 but newentity is IPv6"
      echo "#   newentity:"
      echo "#      *: same"
      echo "#      newenity evalue - ip or fqdn. For some objects like management/packetfilter"
      echo "#      we need netmask too."
      echo "#      If the IP is IPv6 then we need to include it in brackets (e.g [fd::1])."
      echo "#      We also need to include it in brackets if it is IPv4 but oldentity is IPv6"
      echo "#   action:"
      echo "#      *: keep."
      echo "#      -: remove."
      echo "#//////////////////////////////////////////////////////////////////////////"
    } > ${EXPORTDIR}/remaposv.cfg

   #1. Detect sip gateways

   logstr "   - Detecting external signaling gateways in your system."
   gwsql=/tmp/gwsql
   gwsqlres=/tmp/gwsqlres
   rm -rf ${gwsql}*

   cat << EOF > $gwsql
select EP_NAME,IP from ENDPOINT_T 
where ACCOUNT_AUTH <> 1 and IP != '' and 
      EP_NAME != 'EP_TCG1' and EP_NAME != 'EP_TCG2' and
      EP_NAME not like '% %';
EOF

   #toolkitversion="`rpm -aq UNSPmigration | tail -1`"
   su - solid -c "$solsql -x onlyresults -o $gwsqlres 'tcp 16760' dba $(getDbaPassword) $gwsql"  1>>$LOGFILE 2>&1
    
   if [ -f "$gwsqlres" ];
   then
     cat $gwsqlres | sed -e '/^[ \t]*$/d' -e 's/^/      - /g' > ${gwsqlres}.out
     cat ${gwsqlres}.out

     {
        cat $gwsqlres | awk '{ print $2 '} | sort | uniq | grep -v "^$" > ${gwsqlres}.ip
        for idx in `cat ${gwsqlres}.ip`
        do
           nextmatch="`egrep -e \"[ ]${idx}[ ]*\" $gwsqlres | tail -1`"
           nextmatchgw="`echo $nextmatch | awk '{ print $1 }'`"
           nextmatchip="`echo $nextmatch | awk '{ print $2 }'`"
           isIPv6Addr $nextmatchip
           isipv6=$?
           if [ "$nextmatchip" != "" ];
           then
              if [ ${isipv6} -ne 0 ]
              then
                 echo gateway:${nextmatchgw}:${nextmatchip}:*:*
              else
                 echo gateway:${nextmatchgw}:[${nextmatchip}]:*:*
              fi
           fi
        done 
     } | grep -v "^$" >> ${EXPORTDIR}/remaposv.cfg
   fi
   
   #2. Detect media gateways
   logstr "   - Detecting media signaling gateways in your system."
   mgwsql=/tmp/mgwsql
   mgwsqlres=/tmp/mgwsqlres
   rm -f ${mgwsql}*

   cat << EOF > $mgwsql
select MG_NAME,MG_ADDRESS,FQDN from MEDIA_GATEWAY 
where MG_NAME not like '% %';
EOF

   su - solid -c "$solsql -x onlyresults -o $mgwsqlres 'tcp 16760' dba $(getDbaPassword) $mgwsql"  1>>$LOGFILE 2>&1

   if [ -f "$mgwsqlres" ];
   then
     cat $mgwsqlres | sed -e '/^[ \t]*$/d' -e 's/^/      - /g' > ${mgwsqlres}.out
     cat ${mgwsqlres}.out

     {
        cat $mgwsqlres | awk '{ print $2 '} | sort | uniq | egrep -e '^[0-9]' -e '^[0-9a-fA-F]{0,4}:'   | grep -v "^$" > ${mgwsqlres}.ip
        cat $mgwsqlres | awk '{ print $3 '} | sed -e 's/\[//g' -e 's/\]//g' | \
                         sort | uniq | grep -v "\[\]" | grep -v "^$" > ${mgwsqlres}.fqdn
        for idx in `cat ${mgwsqlres}.ip ${mgwsqlres}.fqdn | sort | uniq`
        do
           nextmatch="`egrep -e \"[ ]${idx}[ ]*\" $mgwsqlres | tail -1`"
           nextmatchgw="`echo $nextmatch | awk '{ print $1 }'`"
           nextmatchip="`echo $nextmatch | awk '{ print $2 }'`"
           nextmatchfqdn="`echo $nextmatch | awk '{ print $3 }'`"
           nextmatchnormalizedfqdn="`echo $nextmatchfqdn | sed -e 's/\[//g' -e 's/\]//g'`"
           if [ "$nextmatchip" != "" ];
           then
              isIPv6Addr ${nextmatchip}
              isipv6=$?
              if [ ${isipv6} -ne 0 ]
              then
                 echo "mediagateway:${nextmatchgw}:${nextmatchip}:*:*"
              else
                 echo "mediagateway:${nextmatchgw}:[${nextmatchip}]:*:*"
              fi
           fi
           if [ "$nextmatchfqdn" != ""  -a "$nextmatchip" != "$nextmatchnormalizedfqdn" ];
           then
              echo "mediagateway:${nextmatchgw}:${nextmatchfqdn}:*:*"
           fi
        done 
     } | grep -v "^$"  >> ${EXPORTDIR}/remaposv.cfg
   fi
    
   #3. detect offboard cmp's
   logstr "   - Detecting external CMP's in your system."
   pfrsql=/tmp/pfrsql
   pfrsqlres=/tmp/pfrsqlres
   rm -f ${pfrsql}*

   cat << EOF > $pfrsql
select RULE_NAME,REMOTE_IP_ADDR,REMOTE_NETMASK from PACKET_FILTERING_RULE_T 
where REMOTE_IP_ADDR != '' and RULE_NAME not like '% %';
EOF

   su - solid -c "$solsql -x onlyresults -o $pfrsqlres 'tcp 16760' dba $(getDbaPassword) $pfrsql"  1>>$LOGFILE 2>&1

   if [ -f "$pfrsqlres" ];
   then
     cat $pfrsqlres | grep SoapOffBoardAssistant | awk '{ print $2 }' | \
                      sed -e '/^[ \t]*$/d' -e 's/^/      - /g' | sort | uniq > ${pfrsqlres}.out
     cat ${pfrsqlres}.out

     {
        cat ${pfrsqlres}.out | awk '{ print $2 '} | sort | uniq | egrep -e '^[0-9]' -e '^[0-9a-fA-F]{0,4}:' | grep -v "^$" > ${pfrsqlres}.ip
        for idx in `cat ${pfrsqlres}.ip`
        do
           nextmatch="`egrep -e \"[ ]${idx}[ ]*\" $pfrsqlres | tail -1`"
           nextmatchrule="`echo $nextmatch | awk '{ print $1 }'`"
           nextmatchrulenm="`echo $nextmatch | awk '{ print $3 }'`"
           if [ "$nextmatchrule" != "" ];
           then
             isIPv6Addr $idx
             isipv6=$?
             if [ ${isipv6} -ne 0 ]
             then
                echo management:${nextmatchrule}:${idx}/${nextmatchrulenm}:*:*
             else
                if [ "X${nextmatchrulenm}X" != "XX" ]
                then
                   idx="${idx}/${nextmatchrulenm}"
                fi
                echo management:${nextmatchrule}:[${idx}]:*:*
             fi
           fi
        done
     } | grep -v "^$"  >> ${EXPORTDIR}/remaposv.cfg
   fi

   #4. detect custom pfr's

   logstr "   - Detecting managed PFR's in your system."
   if osv_version.sh --major compare sys ge V4; 
   then
         cat /var/opt/image/allrules | grep -v CSTA > /tmp/allrules
   else
         cp -f /var/opt/image/allrules /tmp/allrules
   fi

   #<V7SystemRules>
      if osv_version.sh --major compare sys ge V7; 
      then
          cat /tmp/allrules | sed -e "s/^'/'System_/g" > /tmp/allrules.system
          cat /tmp/allrules /tmp/allrules.system > /tmp/allrules.consolidate
          cp -f /tmp/allrules.consolidate /tmp/allrules
      fi
   #</V7SystemRules>
   
   pfrcmd=""
   count=0
   for cmdidx in `cat /tmp/allrules| egrep -v "Own Node|Partner Node|Node 1 BMS IP|Node 2 BMS IP" | sed -e "s/'//g"`
   do
      if [ "$count" -eq 0 ];
      then
         pfrcmd="${cmdidx}[ \t]"
      else
         pfrcmd="${pfrcmd}|${cmdidx}[ \t]"
      fi
      count=$[count+1]
   done

   egrep -vi "$pfrcmd" "$pfrsqlres" | egrep -v "Own Node|Partner Node|Node 1 BMS IP|Node 2 BMS IP" > ${pfrsqlres}.out
   {
      cat ${pfrsqlres}.out | awk '{ print $2 '} | sort | uniq | egrep -e '^[0-9]' -e '^[0-9a-fA-F]{0,4}:'  | grep -v "^$" > ${pfrsqlres}.ip
      for idx in `cat ${pfrsqlres}.ip`
      do
         nextmatch="`egrep -e \"[ ]${idx}[ ]*\" ${pfrsqlres}.out | tail -1`"
         nextmatchrule="`echo $nextmatch | awk '{ print $1 }'`"
         nextmatchrulenm="`echo $nextmatch | awk '{ print $3 }'`"
         if [ "$nextmatchrule" != "" ];
         then
            isIPv6Addr $idx
            isipv6=$?
            if [ ${isipv6} -ne 0 ]
            then
               echo packetfilter:$nextmatchrule:${idx}/${nextmatchrulenm}:*:*
            else

               if [ "X${nextmatchrulenm}X" != "XX" ]
               then
                  idx="${idx}/${nextmatchrulenm}"
               fi

               echo packetfilter:$nextmatchrule:[${idx}]:*:*
            fi
         fi
      done
   } >> ${EXPORTDIR}/remaposv.cfg
 
   #5. Custom CDR Hosts
   
   logstr "   - Detecting cdr hosts in your system."
   {
      for cdritem in Srx/Usc/Host Srx/Usc/HostBackup
      do
         grep -q "^${cdritem}[ \t]" /opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm
         if [ $? -eq 0 ];
         then
            cdrhost=`grep "^${cdritem}[ \t]" /opt/SMAW/SMAWrtp/cust_conf/zModifiedParms.parm | \
                     tail -1| awk '{ print $5 }' | sed -e 's/[ ]*//g'`
            if [ "$cdrhost" != "" ];
            then
               echo cdrhost:${cdritem}:${cdrhost}:*:*
            fi
         fi
      done
   } >> ${EXPORTDIR}/remaposv.cfg
  
   remapcksum=`cat ${EXPORTDIR}/remaposv.cfg | grep -v "^#" | md5sum | awk '{ print $1 }'`
   {
      echo "#////////////// No Changes after this line //////////////"
      echo "#Magic:${remapcksum}" 
   } >> ${EXPORTDIR}/remaposv.cfg

   rm -f /etc/hiq8000/remaposv.cfg
   cp ${EXPORTDIR}/remaposv.cfg /etc/hiq8000/remaposv.cfg
}

# ---------------------------------------------------------------
# function: detecth323ep
# args    : None
# description:
#   detects and eliminates h323 endpoints.
# ---------------------------------------------------------------

detecth323ep( ) 
{
   h323Term=0
   h323gw=1
   h323mcu=2
   textncolor $BoldCyan "[${_SELF_}]: Detecting H323 Endpoints in database."
   h323sql=/tmp/h323sql
   h323sqlres=/tmp/h323sqlres
   h323sqlaliasres=/tmp/h323sqlaliasres
   cat << EOF > $h323sql
select EP_ID from ENDPOINT_T where EP_TYPE in ($h323Term,$h323gw,$h323mcu);
EOF
   su - solid -c "$solsql -x onlyresults -o $h323sqlres 'tcp 16760' dba $(getDbaPassword) $h323sql"  1>>$LOGFILE 2>&1
   cat $h323sqlres 2>/dev/null | sed -e '/^[ \t]*$/d' -e 's/\.//g' > ${h323sqlres}.out
   {
      echo "Following H323 Endpoints detected"
      echo "---------------------------------"
      cat ${h323sqlres}.out
   } 1>>$LOGFILE 2>&1
   if [ -s ${h323sqlres}.out ];
   then
      textncolor $BoldPurple "[${_SELF_}]: Detected H323 Endpoints in database."
      epcount=0
      for idx in `cat ${h323sqlres}.out`
      do
         if [ $epcount -eq 0 ];
         then
            epidx="$idx"
         else
            epidx="$epidx,$idx"
         fi
         epcount=`expr $epcount + 1`
      done
      cat << EOF > $h323sql
delete from alias_t where ep_id in ($epidx);
commit work;
exit;
EOF
      su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $h323sql"  1>>$LOGFILE 2>&1
      cat << EOF > $h323sql
delete from endpoint_t where ep_id in ($epidx);
commit work;
exit;
EOF
      su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $h323sql"  1>>$LOGFILE 2>&1
   else
      textncolor $BoldPurple "No H323 Endpoints in database."
   fi
   rm -f ${h323sql}*
}

# ---------------------------------------------------------------
# function: detectmtls
# args    : None
# description:
#   detects mtls attributes on subscriber endpoints and removes 
#   them. Usually this is used for server authentication only.
# ---------------------------------------------------------------

detectmtls( )
{
   textncolor $BoldPurple "Detecting subscribers with MTLS attribute."
   mtlssql=/tmp/mtlssql
   cat << EOF > $mtlssql
update ENDPOINT_T
set ATTRIBUTES2=bit_and(ATTRIBUTES2 , bit_not(131072))
where ACCOUNT_AUTH='1';
commit work;
exit;
EOF
   {
      echo "Resetting subscribers with MTLS attribute." 
      su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $mtlssql"
   } 1>>$LOGFILE 2>&1
}

# ---------------------------------------------------------------
# function: fixdns
# args    : None
# description:
#   fixes illegal resolv.conf issue.eliminates all lines that
#   have illegal value during upgrade.
# ---------------------------------------------------------------

fixdns( )
{
   RESOLVCNF=/etc/resolv.conf
   cat $RESOLVCNF | sed -e "/^nameserver[ \t]*$/d"  \
                        -e "/^domain[ \t]*$/d"      \
                        -e "/^search[ \t]*$/d"      \
                        -e "/^options[ \t]*$/d"     \
                        > ${RESOLVCNF}.new
   cp ${RESOLVCNF}.new $RESOLVCNF
   rm -f ${RESOLVCNF}.new
   if osv_version.sh --major compare sys ge V4; 
   then
      grep -q "^[ \t]*options[ \t]*" $RESOLVCNF
      if [ $? -ne 0 ];
      then
         echo "options timeout:1 attempts:2" >> $RESOLVCNF
      fi
      cat $RESOLVCNF | egrep "timeout:5" | egrep -q "attempts:2"
      if [ $? -eq 0 ];
      then
         {
             cat $RESOLVCNF | sed -e "/^[ \t]*options[ \t].*$/d"
             echo "options timeout:1 attempts:2"
         } > ${RESOLVCNF}.new
         cp ${RESOLVCNF}.new $RESOLVCNF
         rm -f ${RESOLVCNF}.new
      fi
   fi
}

# ---------------------------------------------------------------
# function: dnsip
# args    : None
# description:
#   assigns dns info.
# ---------------------------------------------------------------

dnsip( )
{
   findusb "none"
   dnsswap
   checkremote "$ARGLIST"
   touch /log/dnsip.lock
   textncolor $BoldCyan "[${_SELF_}]: <$mynode>:Success - dns setup."
}

dnsipdone( )
{
   if [ -f /log/dnsip.lock ];
   then
      textncolor $BoldCyan "Lock detected.Finishing up dns ip conversion."
      rm -f /log/dnsip.lock
   fi
}

dnsswap( )
{
   DNSCONF=/etc/resolv.conf
   MASTERCFG8k=/etc/hiq8000/node.cfg
   CFG8k=/etc/hiq8000/node.cfg.toolkit8k

   getcfgvar $MASTERCFG8k name_server_ip_1 olddnsserver1
   getcfgvar $MASTERCFG8k name_server_ip_2 olddnsserver2
   getcfgvar $MASTERCFG8k domain_name      olddnsdomain1
   getcfgvar $MASTERCFG8k search_domain_1  olddnssddomain1
   getcfgvar $MASTERCFG8k search_domain_2  olddnssddomain2
   getcfgvar $MASTERCFG8k search_domain_3  olddnssddomain3

   getcfgvar $CFG8k       name_server_ip_1 newdnsserver1
   getcfgvar $CFG8k       name_server_ip_2 newdnsserver2
   getcfgvar $CFG8k       domain_name      newdnsdomain1
   getcfgvar $CFG8k       search_domain_1  newdnssddomain1
   getcfgvar $CFG8k       search_domain_2  newdnssddomain2
   getcfgvar $CFG8k       search_domain_3  newdnssddomain3

   strolddnsserver1=${olddnsserver1:-none}
   strolddnsserver2=${olddnsserver2:-none}
   strolddnsdomain1=${olddnsdomain1:-none}
   strolddnssddomain1=${olddnssddomain1:-none}
   strolddnssddomain2=${olddnssddomain2:-none}
   strolddnssddomain3=${olddnssddomain3:-none}

   strnewdnsserver1=${newdnsserver1:-none}
   strnewdnsserver2=${newdnsserver2:-none}
   strnewdnsdomain1=${newdnsdomain1:-none}
   strnewdnssddomain1=${newdnssddomain1:-none}
   strnewdnssddomain2=${newdnssddomain2:-none}
   strnewdnssddomain3=${newdnssddomain3:-none}

   echo " ------------------------------------------------------ "
   echo "|                Dns Reconfiguration                   |"
   echo " ------------------------------------------------------ "
   echo " dns-server:"
   echo "              `echo ${stroldntpserver1}   |  awk '{ printf "%16s",$1 }'`  -> ${strnewdnsserver1}"
   echo "              `echo ${stroldntpserver2}   |  awk '{ printf "%16s",$1 }'`  -> ${strnewdnsserver2}"
   echo " dns-domain:"
   echo "              `echo ${strolddnsdomain1}   |  awk '{ printf "%16s",$1 }'`  -> ${strnewdnsdomain1}"
   echo " dns-search:"
   echo "              `echo ${strolddnssddomain1} |  awk '{ printf "%16s",$1 }'`  -> ${strnewdnssddomain1}"
   echo "              `echo ${strolddnssddomain2} |  awk '{ printf "%16s",$1 }'`  -> ${strnewdnssddomain2}"
   echo "              `echo ${strolddnssddomain3} |  awk '{ printf "%16s",$1 }'`  -> ${strnewdnssddomain3}"
   echo " ------------------------------------------------------ "

   {
      nzecho "$newdnsserver1" "nameserver   $newdnsserver1"
      nzecho "$newdnsserver2" "nameserver   $newdnsserver2"
      nzecho "$newdnsdomain1" "domain       $newdnsdomain1"
      nzecho "${newdnssddomain1}${newdnssddomain2}${newdnssddomain3}" "search $newdnssddomain1 $newdnssddomain2 $newdnssddomain3"
      echo   "options timeout:1 attempts:1"
   } > /etc/resolv.conf

   cp /etc/hiq8000/node.cfg.toolkit8k /etc/hiq8000/node.cfg
}

# ---------------------------------------------------------------
# function: ntpswap
# args    : None
# description:
#   new ntp server is configured on a running system.
# ---------------------------------------------------------------

ntpswap( )
{
   NTPCONF=/etc/ntp.conf
   NTPCLUSTERCONF=/etc/ntp.conf.cluster
   MASTERCFG8k=/etc/hiq8000/node.cfg
   CFG8k=/etc/hiq8000/node.cfg.toolkit8k

   getcfgvar $MASTERCFG8k ntp_server_1 oldntpserver1
   getcfgvar $MASTERCFG8k ntp_server_2 oldntpserver2

   getcfgvar $CFG8k       ntp_server_1 newntpserver1
   getcfgvar $CFG8k       ntp_server_2 newntpserver2

   stroldntpserver1=${oldntpserver1:-none}
   stroldntpserver2=${oldntpserver2:-none}
   strnewntpserver1=${newntpserver1:-none}
   strnewntpserver2=${newntpserver2:-none}

   #<ServerInfo>
      if [ "$newntpserver1" != "" ];
      then
         server1cfg="server    $newntpserver1"
      else
         server1cfg="#primary ntp server <none>"
      fi
      if [ "$newntpserver2" != "" ];
      then
         server2cfg="server    $newntpserver2"
      else
         server2cfg="#secondary ntp server <none>"
      fi
      #OSV-23599
      ntpkey1="`grep "^server $newntpserver1" /etc/ntp.conf | grep -o 'key.*'`"
      ntpkey2="`grep "^server $newntpserver2" /etc/ntp.conf | grep -o 'key.*'`"
   #<ServerInfo>

   echo " ------------------------------------------------------ "
   echo "|                Ntp Reconfiguration                   |"
   echo " ------------------------------------------------------ "
   echo " ntp-server:"
   echo "              `echo ${stroldntpserver1}   |  awk '{ printf "%16s",$1 }'`  -> ${strnewntpserver1}"
   echo "              `echo ${stroldntpserver2}   |  awk '{ printf "%16s",$1 }'`  -> ${strnewntpserver2}"
   echo " ------------------------------------------------------ "

   {
       echo "server    127.127.1.0"
       echo "fudge     127.127.1.0 stratum 10"
       echo "$server1cfg burst iburst maxpoll 16 $ntpkey1"
       echo "$server2cfg burst iburst maxpoll 16 $ntpkey2"
       echo "peer      0.0.0.0 prefer"
       echo "driftfile /var/lib/ntp/drift/ntp.drift"
       echo "disable   stats"
       echo "statsdir  /var/ntp/ntpstats/"
       echo "filegen   peerstats file peerstats type day enable"
       echo "filegen   loopstats file loopstats type day enable"
       echo "filegen   clockstats file clockstats type day enable"
       echo "enable    monitor stats"
       echo "logconfig =syncall +clockall"
   } > ${NTPCLUSTERCONF}.new
   cp ${NTPCLUSTERCONF}.new ${NTPCLUSTERCONF}
   rm -f ${NTPCLUSTERCONF}.new

   {
      echo $server1cfg
      echo $server2cfg
   } > ${NTPCONF}.new
   cp ${NTPCONF}.new ${NTPCONF}
   rm -f ${NTPCONF}.new
   FILTERTXT=/unisphere/srx3000/callp/etc/sec/FILT_START.txt
   cat $FILTERTXT |                                        \
       sed -e "s/${oldntpserver1}/${newntpserver1}/g"  \
           -e "s/${oldntpserver2}/${newntpserver2}/g"  \
       > ${FILTERTXT}.new
   cp ${FILTERTXT}.new $FILTERTXT
   rm -f ${FILTERTXT}.new
   
   #<PfNtpRules>
   if [ "$mynode" = "$primhost" ];
   then
      switchsolid ${mynode}
      pfsql=/tmp/pfntp
      rm -f $pfsql
      if [ "$oldntpserver1" != "" ];
      then
         {
            echo "update PACKET_FILTERING_RULE_T"
            echo "set REMOTE_IP_ADDR='$newntpserver1'"
            echo "where RULE_NAME='NTP_Server_1' or RULE_NAME='NTP_Server_1_spt';"
            echo "commit work;"
         } > $pfsql
      else
         {
            echo "INSERT INTO PACKET_FILTERING_RULE_T"
            echo "(  PACKET_FILTERING_RULE_ID,RULE_NAME,LOCAL_IP_ADDR,REMOTE_FQDN,REMOTE_IP_ADDR,REMOTE_NETMASK,"
            echo "   DIRECTION,LOCAL_PORT_BEGIN,LOCAL_PORT_END,REMOTE_PORT_BEGIN,"
            echo "   REMOTE_PORT_END,TRANSPORT_PROTOCOL,RULE_ACTION,DESCRIPTION"
            echo ")"
            echo "VALUES("
            echo "   PACKET_FILTERING_RULE_ID_SEQ.NEXTVAL,'NTP_Server_1','','','$newntpserver1','255.255.255.255',"
            echo "   '1.','123.','0.','0.','0.','2.','1.','NTP packets from NTP Server 1'"
            echo ");"
            echo "INSERT INTO PACKET_FILTERING_RULE_T"
            echo "(  PACKET_FILTERING_RULE_ID,RULE_NAME,LOCAL_IP_ADDR,REMOTE_FQDN,REMOTE_IP_ADDR,REMOTE_NETMASK,"
            echo "   DIRECTION,LOCAL_PORT_BEGIN,LOCAL_PORT_END,REMOTE_PORT_BEGIN,"
            echo "   REMOTE_PORT_END,TRANSPORT_PROTOCOL,RULE_ACTION,DESCRIPTION"
            echo ")"
            echo "VALUES("
            echo "   PACKET_FILTERING_RULE_ID_SEQ.NEXTVAL,'NTP_Server_1_spt','','','$newntpserver1','255.255.255.255',"
            echo "   '1.','0.','0.','123.','0.','2.','1.','NTP source port from NTP Server 1'"
            echo ");"
            echo "commit work;"
         } > $pfsql
      fi
      if [ "$oldntpserver2" != "" ];
      then
         {
            echo "update PACKET_FILTERING_RULE_T"
            echo "set REMOTE_IP_ADDR='$newntpserver2'"
            echo "where RULE_NAME='NTP_Server_2' or RULE_NAME='NTP_Server_2_spt';"
            echo "commit work;"
         } >> $pfsql
      else
         {
            echo "INSERT INTO PACKET_FILTERING_RULE_T"
            echo "(  PACKET_FILTERING_RULE_ID,RULE_NAME,LOCAL_IP_ADDR,REMOTE_FQDN,REMOTE_IP_ADDR,REMOTE_NETMASK,"
            echo "   DIRECTION,LOCAL_PORT_BEGIN,LOCAL_PORT_END,REMOTE_PORT_BEGIN,"
            echo "   REMOTE_PORT_END,TRANSPORT_PROTOCOL,RULE_ACTION,DESCRIPTION"
            echo ")"
            echo "VALUES("
            echo "   PACKET_FILTERING_RULE_ID_SEQ.NEXTVAL,'NTP_Server_2','','','$newntpserver2','255.255.255.255',"
            echo "   '1.','123.','0.','0.','0.','2.','1.','NTP packets from NTP Server 2'"
            echo ");"
            echo "INSERT INTO PACKET_FILTERING_RULE_T"
            echo "(  PACKET_FILTERING_RULE_ID,RULE_NAME,LOCAL_IP_ADDR,REMOTE_FQDN,REMOTE_IP_ADDR,REMOTE_NETMASK,"
            echo "   DIRECTION,LOCAL_PORT_BEGIN,LOCAL_PORT_END,REMOTE_PORT_BEGIN,"
            echo "   REMOTE_PORT_END,TRANSPORT_PROTOCOL,RULE_ACTION,DESCRIPTION"
            echo ")"
            echo "VALUES("
            echo "   PACKET_FILTERING_RULE_ID_SEQ.NEXTVAL,'NTP_Server_2_spt','','','$newntpserver2','255.255.255.255',"
            echo "   '1.','0.','0.','123.','0.','2.','1.','NTP source port from NTP Server 2'"
            echo ");"
            echo "commit work;"
         } >> $pfsql
      fi
      su - solid -c "$solsql 'tcp 16760' dba $(getDbaPassword) $pfsql" 1>>$LOGFILE 2>&1
      rm -f $pfsql
   fi
   #</PfNtpRules>
   echo "Copying /etc/hiq8000/node.cfg"
   cp /etc/hiq8000/node.cfg.toolkit8k /etc/hiq8000/node.cfg
   textncolor $BoldCyan "Reboot your nodes for cluster changes to take effect"
   sed -i '/^server/!b;/maxpoll 16/!s/$/ maxpoll 16/' $NTPCONF
   if [ -n "$ntpkey1" ]; then sed -i '/^server '"$ntpservone"'/!b;/key/!s/$/ '"$ntpkey1"'/'  $NTPCONF; fi
   if [ -n "$ntpkey2" ]; then sed -i '/^server '"$ntpservtwo"'/!b;/key/!s/$/ '"$ntpkey2"'/'  $NTPCONF; fi
   
}

# ---------------------------------------------------------------
# function: ntpip
# args    : None
# description:
#   detects usb for node.cfg and calls ntp swap.
# ---------------------------------------------------------------

ntpip( )
{
   findusb "none"
   ntpswap
   checkremote "$ARGLIST"
   cp /etc/hiq8000/node.cfg.toolkit8k /etc/hiq8000/node.cfg
   touch /log/ntpip.lock
   textncolor $BoldCyan "[${_SELF_}]: <$mynode>:Success - ntp setup."
}

ntpipdone( )
{
   if [ -f /log/ntpip.lock ];
   then
      textncolor $BoldCyan "Lock detected.Finishing up ntp ip conversion."
      ntpq -p
      rm -f /log/ntpip.lock
   fi
}

# ---------------------------------------------------------------
# function: nodenameswap
# args    : None
# description:
#   swaps old nodename with new nodename.
# ---------------------------------------------------------------

nodenameswap( )
{
   MASTERCFG8k=/etc/hiq8000/node.cfg
   CFG8k=/etc/hiq8000/node.cfg.toolkit8k

   getcfgvar  $MASTERCFG8k node_1_name oldprimnodename
   getcfgvar  $MASTERCFG8k node_2_name oldsecnodename

   getcfgvar  $CFG8k node_1_name newprimnodename
   getcfgvar  $CFG8k node_2_name newsecnodename

   nodenamefiles="                                 \
      /etc/security/access.conf                    \
      /opt/SMAW/SMAWrtp/conf/master                \
      /etc/ssh/ssh_host_key.pub                    \
      /etc/ssh/ssh_host_rsa_key.pub                \
      /etc/ssh/ssh_host_dsa_key.pub                \
      /root/.ssh/known_hosts                       \
      /root/.ssh/id_rsa.pub                        \
      /unisphere/srx3000/srx/.ssh/known_hosts      \
      /unisphere/srx3000/srx/.ssh/id_rsa.pub       \
      /var/lib/nfs/etab                            \
      /etc/hosts.deny                              \
      /etc/httpd/httpd.conf                        \
      /etc/hosts                                   \
   "

   for nodeidx in $nodenamefiles
   do
      if [ -f $nodeidx ];
      then
         echo "   - Adjusting $nodeidx."
         cat $nodeidx | sed -e "s/$oldprimnodename[ \t]/$newprimnodename $oldprimnodename /g"   \
                            -e "s/$oldprimnodename[ \t]*,/$newprimnodename,$oldprimnodename,/g" \
                            -e "s/$oldsecnodename[ \t]/$newsecnodename $oldsecnodename /g"      \
                            -e "s/$oldsecnodename[ \t]*,/$newsecnodename,$oldsecnodename,/g"    \
                   > ${nodeidx}.swap
         cp ${nodeidx}.swap ${nodeidx}
         rm -f ${nodeidx}.swap
      fi
   done
   #<ChangeSpecifics>
      #[1]. change exports. important for rolling upgrades.
      nodenamefiles="                         \
          /etc/exports                        \
          /.rhosts                            \
          /etc/nodename                       \
          /etc/HOSTNAME                       \
          /etc/postfix/main.cf                \
          /etc/opt/SMAW/SMAWsf/rcsd.cfg       \
          /etc/opt/SMAW/SMAWsf/SaQuery.cfg    \
          /etc/opt/SMAW/SMAWsf/SA_ipmi.cfg    \
          /etc/opt/SMAW/SMAWsf/SA_down.cfg    \
          /etc/opt/SMAW/SMAWhaext/sa_down.cfg \
          /etc/opt/SMAW/SMAWhaext/sa_ipmi.cfg \
          /etc/opt/SMAW/SMAWsf/rcsd.cfg       \
      "
          
      for nodeidx in $nodenamefiles
      do
         if [ -f $nodeidx ];
         then
            echo "   - Adjusting $nodeidx."
            cat $nodeidx | sed -e "s/$oldprimnodename/$newprimnodename/g" > ${nodeidx}.swap
            cp -f ${nodeidx}.swap $nodeidx
            rm -f ${nodeidx}.swap
         fi
      done

      nodenamefiles="                                 \
         /unisphere/srx3000/srx/.ssh/authorized_keys2 \
         /root/.ssh/authorized_keys2                  \
      "

      for nodeidx in $nodenamefiles
      do
         if [ -f $nodeidx ];
         then
            echo "   - Adjusting $nodeidx."
            cat $nodeidx | sed -e "s/@$oldprimnodename/@$newprimnodename/g" > ${nodeidx}.swap
            cp -f ${nodeidx}.swap $nodeidx
            rm -f ${nodeidx}.swap
         fi
      done
   #</ChangeSpecifics>
   cp /etc/hiq8000/node.cfg.toolkit8k /etc/hiq8000/node.cfg
}

# ---------------------------------------------------------------
# function: nodename
# args    : None
# description:
#   detects usb for node.cfg and calls nodename swap.
# ---------------------------------------------------------------

nodename( )
{
   findusb "none"
   checkremote "$ARGLIST"
   nodenameswap
   touch /log/nodename.lock
   textncolor $BoldCyan "[${_SELF_}]: <$mynode>:Success - nodename setup."
}

# ----------------------------------------------------------------
# function: reduceips
# args    : none
# description:
#   removes the pf rules.
# ----------------------------------------------------------------

reduceips( )
{
  textncolor $BoldCyan  "[${_SELF_}]: Addressing Reduced Ip's."
  pfrslick="\
     h323_gk01_ip_alias
     h323_gk02_ip_alias
     sa_ip_alias
     ncs_ip_alias_1
     ncs_ip_alias_2
     sip_ip_alias_1
     sip_ip_alias_2
     sip_ip_alias_3
     sip_ip_alias_4
     sip_ipv6_alias_1
     sip_ipv6_alias_2
     sip_ipv6_alias_3
     sip_ipv6_alias_4
     csta_ip_alias_1
     csta_ip_alias_2
     lsm_ip_alias
     dqos_ip_alias_1
     dqos_ip_alias_2
     mgcp_ip_alias_1
     mgcp_ip_alias_2
     tgcp_ip_alias_1
     tgcp_ip_alias_2
     clusternode1-priv
     clusternode2-priv
  "

  nmcvip="`cfgread nmc_vip`"
  if [ "$nmcvip" = ""  -o "$nmcvip" = "0.0.0.0" ];
  then
     pfrslick="$pfrslick oam_ip_alias"
  fi
  cdcvip="`cfgread cdc_df_vip`"
  if [ "$cdcvip" = ""  -o "$cdcvip" = "0.0.0.0" ];
  then
     pfrslick="$pfrslick cdc_ip_alias"
  fi
  
  for idx in $pfrslick
  do
      grep -q $idx /etc/hosts
      if [ $? -ne 0 ];
      then
         logstr "[x]  Removing pfr for $idx."
         {
            su - solid -c "$solsql -a -e \"delete from packet_filtering_rule_t where LOCAL_IP_ADDR='$idx' \" \"tcp 16760\" dba $(getDbaPassword)"
            su - solid -c "$solsql -a -e \"delete from packet_filtering_rule_t where REMOTE_FQDN='$idx' \" \"tcp 16760\" dba $(getDbaPassword)"
            su - solid -c "$solsql -a -e \"delete from packet_filtering_rule_t where REMOTE_IP_ADDR='$idx' \" \"tcp 16760\" dba $(getDbaPassword)"
         } 1>>$LOGFILE 2>&1
      fi 
  done
} 

nodenamedone( )
{
   if [ -f /log/nodename.lock ];
   then
      textncolor $BoldCyan "Lock detected.Finishing up nodename conversion."
      echo "Node Name : `uname -n`"
      rm -f /log/nodename.lock
   fi

}

# ---------------------------------------------------------------
# function: adminip
# args    : None
# description:
# changes admin network configuration.
# ---------------------------------------------------------------

adminip( )
{
   MASTERCFG8k=/etc/hiq8000/node.cfg
   CFG8k=/etc/hiq8000/node.cfg.toolkit8k

   findusb "none"
   checkremote "$ARGLIST"

   if [ ! -f $CFG8k ];
   then
      textncolor $BoldCyan "[${_SELF_}]: Could not locate new node.cfg."
      exit $FAIL
   fi

   getallnafo $MASTERCFG8k nafo0    oldadmin

   getallnafo $CFG8k       nafo0    newadmin


   if [ "$primoldadminif}" != "$primnewadminif" -a "$secoldadminif" != "$secnewadminif" ];
   then
      textncolor $BoldCyan "[${_SELF_}]: Check your node.cfg for admin interfaces. They do not match."
      exit $FAIL
   fi

   textncolor $BoldCyan "[${_SELF_}]: Bringing system to state#2.`date`"
   sleep 20
   /unisphere/srx3000/srx/startup/srxctrl 2 `remotestate 2`  1>>$LOGFILE 2>&1
   if [ $? -ne 0 ];
   then
      logstr "[${_SELF_}]: Cannot bring system to state#2."
      exit $FAIL
   fi
   echo " ------------------------------------------------------ "
   echo "|                Cip Reconfiguration                   |"
   echo " ------------------------------------------------------ "
   echo " adminip     :"
   echo "              `echo ${primoldadminip} |  awk '{ printf "%16s",$1 }'`  -> ${primnewadminip}"
   echo "              `echo ${secoldadminip}  |  awk '{ printf "%16s",$1 }'`  -> ${secnewadminip}"
   echo " adminsn     :"
   echo "              `echo ${primoldadminsn} |  awk '{ printf "%16s",$1 }'`  -> ${primnewadminsn}"
   echo "              `echo ${secoldadminsn}  |  awk '{ printf "%16s",$1 }'`  -> ${secnewadminsn}"
   echo " adminnm     :"
   echo "              `echo ${primoldadminnm} |  awk '{ printf "%16s",$1 }'`  -> ${primnewadminnm}"
   echo "              `echo ${secoldadminnm}  |  awk '{ printf "%16s",$1 }'`  -> ${secnewadminnm}"
   echo " adminbr     :"
   echo "              `echo ${primoldadminbr} |  awk '{ printf "%16s",$1 }'`  -> ${primnewadminbr}"
   echo "              `echo ${secoldadminbr}  |  awk '{ printf "%16s",$1 }'`  -> ${secnewadminbr}"
   echo ""
   echo " ------------------------------------------------------ "


   adminbonddeva=`cfgread bonding_dev0 | awk '{ print $1 }'`
   adminbonddevb=`cfgread bonding_dev0 | awk '{ print $2 }'`
   adminfiles="                                     \
      /etc/hosts
      /etc/sysconfig/network/ifcfg-${primnewadminif} \
      /etc/sysconfig/network/ifcfg-${adminbonddeva} \
      /etc/sysconfig/network/ifcfg-${adminbonddevb} \
   "
   for adminidx in $adminfiles
   do
      cat $adminidx | sed   -e "s/${primoldadminnm}/${primnewadminnm}/g"  \
                            -e "s/${secoldadminnm}/${secnewadminnm}/g"    \
                            -e "s/${primoldadminsn}/${primnewadminsn}/g"  \
                            -e "s/${secoldadminsn}/${secnewadminsn}/g"    \
                            -e "s/${primoldadminbr}/${primnewadminbr}/g"  \
                            -e "s/${secoldadminbr}/${secnewadminbr}/g"    \
                            -e "s/${primoldadminip}/${primnewadminip}/g"  \
                            -e "s/${secoldadminip}/${secnewadminip}/g"    \
                    > ${adminidx}.swap
       cp ${adminidx}.swap $adminidx
       rm -f ${adminidx}.swap
   done

   cp /etc/hiq8000/node.cfg.toolkit8k /etc/hiq8000/node.cfg
   touch /log/adminip.lock
}

adminipdone( )
{
   if [ -f /log/adminip.lock ];
   then
      textncolor $BoldCyan "Lock detected.Finishing up admin ip conversion."
      rm -f /log/adminip.lock
   fi
}

# ---------------------------------------------------------------
# function: sigip
# args    : None
# description:
#   sets up the signaling ip's
# ---------------------------------------------------------------

sigip( )
{
   MASTERCFG8k=/etc/hiq8000/node.cfg
   CFG8k=/etc/hiq8000/node.cfg.toolkit8k
   
   textncolor $BoldCyan "Signalling ip conversion is not supported."
}

sigipdone( )
{
   if [ -f /log/sigip.lock ];
   then
      textncolor $BoldCyan "Lock detected.Finishing up signaling ip conversion."
      rm -f /log/sigip.lock
   fi
}

# ---------------------------------------------------------------
# function: billingip
# args    : None
# description:
#   new billingip's configured on a running system.
#   note: billing server ip's are configured via CMP.
#   SrxUsc.parm
#   Primary billing server:
#   Srx/Usc/Host       customer    string   = 0.0.0.0
#   Backup billing server:
#   Srx/Usc/HostBackup customer    string   = 0.0.0.0
# ---------------------------------------------------------------

billingip( )
{
   MASTERCFG8k=/etc/hiq8000/node.cfg
   CFG8k=/etc/hiq8000/node.cfg.toolkit8k

   findusb "none"
   checkremote "$ARGLIST"

   if [ ! -f $CFG8k ];
   then
      textncolor $BoldCyan "Could not locate new node.cfg."
      exit $FAIL
   fi

   getcfgvar  $MASTERCFG8k billing_server1 oldbillingserver
   getcfgvar  $MASTERCFG8k billing_client1 oldbillingclient
   getallnafo $MASTERCFG8k nafo2           oldbilling

   getcfgvar  $CFG8k billing_server1       newbillingserver
   getcfgvar  $CFG8k billing_client1       newbillingclient
   getallnafo $CFG8k nafo2                 newbilling

   if [ "$primoldbillingif}" != "$primnewbillingif" -a "$secoldbillingif" != "$secnewbillingif" ];
   then
      textncolor $BoldCyan "Check your node.cfg for billing interfaces. They do not match."
      exit $FAIL
   fi

   textncolor $BoldCyan "Bringing system to state#2.`date`"
   sleep 20
   /unisphere/srx3000/srx/startup/srxctrl 2 `remotestate 2`  1>>$LOGFILE 2>&1
   if [ $? -ne 0 ];
   then
      logstr "[${_SELF_}]: Cannot bring system to state#2."
      exit $FAIL
   fi
   echo " ------------------------------------------------------ "
   echo "|                Cip Reconfiguration                   |"
   echo " ------------------------------------------------------ "
   echo " billingip     :"
   echo "              `echo ${primoldbillingip} |  awk '{ printf "%16s",$1 }'`  -> ${primnewbillingip}"
   echo "              `echo ${secoldbillingip}  |  awk '{ printf "%16s",$1 }'`  -> ${secnewbillingip}"
   echo " billingsn     :"
   echo "              `echo ${primoldbillingsn} |  awk '{ printf "%16s",$1 }'`  -> ${primnewbillingsn}"
   echo "              `echo ${secoldbillingsn}  |  awk '{ printf "%16s",$1 }'`  -> ${secnewbillingsn}"
   echo " billingnm     :"
   echo "              `echo ${primoldbillingnm} |  awk '{ printf "%16s",$1 }'`  -> ${primnewbillingnm}"
   echo "              `echo ${secoldbillingnm}  |  awk '{ printf "%16s",$1 }'`  -> ${secnewbillingnm}"
   echo " billingbr     :"
   echo "              `echo ${primoldbillingbr} |  awk '{ printf "%16s",$1 }'`  -> ${primnewbillingbr}"
   echo "              `echo ${secoldbillingbr}  |  awk '{ printf "%16s",$1 }'`  -> ${secnewbillingbr}"
   echo ""
   echo " ------------------------------------------------------ "


   billingbonddeva=`cfgread bonding_dev2 | awk '{ print $1 }'`
   billingbonddevb=`cfgread bonding_dev2 | awk '{ print $2 }'`
   billingfiles="                                     \
      /etc/hosts
      /etc/sysconfig/network/ifcfg-${primnewbillingif}\
      /etc/sysconfig/network/ifcfg-${billingbonddeva} \
      /etc/sysconfig/network/ifcfg-${billingbonddevb} \
   "
   for billingidx in $billingfiles
   do
      cat $billingidx | sed -e "s/${primoldbillingnm}/${primnewbillingnm}/g"  \
                            -e "s/${secoldbillingnm}/${secnewbillingnm}/g"    \
                            -e "s/${primoldbillingsn}/${primnewbillingsn}/g"  \
                            -e "s/${secoldbillingsn}/${secnewbillingsn}/g"    \
                            -e "s/${primoldbillingbr}/${primnewbillingbr}/g"  \
                            -e "s/${secoldbillingbr}/${secnewbillingbr}/g"    \
                            -e "s/${primoldbillingip}/${primnewbillingip}/g"  \
                            -e "s/${secoldbillingip}/${secnewbillingip}/g"    \
                    > ${billingidx}.swap
       cp ${billingidx}.swap $billingidx
       rm -f ${billingidx}.swap
   done

   cp /etc/hiq8000/node.cfg.toolkit8k /etc/hiq8000/node.cfg
   touch /log/billingip.lock
}

billingipdone( )
{
   if [ -f /log/billingip.lock ];
   then
      textncolor $BoldCyan "Lock detected.Finishing up billing ip conversion."
      rm -f /log/billingip.lock
   fi
}


# ---------------------------------------------------------------
# function: donexchange
# args    : None
# description:
#   finish the xchange process. user runs migrate8k -done option
#   on reboot for activation.
# ---------------------------------------------------------------

donexchange( )
{
   clusteripdone
   billingipdone
   if [                                \
        -f /log/clusterip.lock -o      \
        -f /log/billingip.lock         \
      ];
   then
      creatertp
   fi
   textncolor $BoldCyan "Bringing system to state#4.`date`"
   if ! srxctrl 4 `remotestate 4`  1>>$LOGFILE 2>&1; then
      logstr "[${_SELF_}]: Cannot bring system to state#4."
      exit $FAIL
   fi
   switchsolid ${mynode}
}

# ---------------------------------------------------------------
# function: clusterip
# args    : None
# description:
#   new cip's configured on a running system.
# ---------------------------------------------------------------

clusterip( )
{
   if [ "$testbed" != "cluster" ];
   then
      textncolor $BoldCyan "Skipping ip exchange for $testbed."
      return
   fi
   findusb "none"
   cipswap
   checkremote "$ARGLIST"
   deletertp
   touch /log/clusterip.lock
   textncolor $BoldCyan "[${_SELF_}]: <$mynode>:Success - cip setup."
}

clusteripdone( )
{
   if [ -f /log/clusterip.lock ];
   then
      textncolor $BoldCyan "Lock detected.Finishing up cluster ip conversion."
      cipfiles="
         /unisphere/srx3000/srx/.ssh/known_hosts \
         /root/.ssh/known_hosts                  \
      "
      for cipidx in $cipfiles
      do
         echo "            - $cipidx"
         if [ -f ${cipidx}.ciprestore ];
         then
            cp ${cipidx}.ciprestore $cipidx
            rm -f ${cipidx}.ciprestore
         fi
      done
      rm -f /log/clusterip.lock
      textncolor $BoldCyan "[${_SELF_}]: <$mynode>:Success."
   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: localdata
# args    : None
# description:
#   uses local hard disk for export import. No need for ext usb.
# ---------------------------------------------------------------

localdata( )
{
  logdebug "Function localdata called with arguments [${*}]"
  
  if [ "$1" = "export" ];
  then
     if [ "$LOCAL4USB" = "true" -a "$CFGMNTPATH" = "" ];
     then
        export CFGMNTPATH=/software/localexport
        rm -rf $CFGMNTPATH
     fi
  else
     if [ "$LOCAL4USB" = "true" -a "$CFGMNTPATH" = "" ];
     then
        primnodename="`cfgread node_1_name`"
        secnodename="`cfgread node_2_name`"
        mynode="`uname -n`"
        if [ -d /software/toolkit -a -f /software/toolkit/date ];
        then
           expprimnodename="`cat /software/toolkit/date 2>/dev/null | grep "^PrimaryNode" | awk -F':' '{ print $2 }'`"
           expsecnodename="`cat /software/toolkit/date  2>/dev/null | grep "^SecondaryNode" | awk -F':' '{ print $2 }'`"
           logstr "   - Using active image to locate imported data."
           logstr "   - Primary   node : $expprimnodename"
           logstr "   - Secondary node : $expsecnodename"
           if [ "$primnodename" = "$mynode" ];
           then
              export CFGMNTPATH=/software/toolkit/${expprimnodename}
           else
              export CFGMNTPATH=/software/toolkit/${expsecnodename}
           fi
        else
           expprimnodename="`cat /img/softwareimg/${passiveimg}/toolkit/date 2>/dev/null | grep "^PrimaryNode" | awk -F':' '{ print $2 }'`"
           expsecnodename="`cat /img/softwareimg/${passiveimg}/toolkit/date  2>/dev/null | grep "^SecondaryNode" | awk -F':' '{ print $2 }'`"
           logstr "   - Using fallback image to locate imported data."
           logstr "   - Primary   node : $expprimnodename"
           logstr "   - Secondary node : $expsecnodename"
           if [ "$primnodename" = "$mynode" ];
           then
              export CFGMNTPATH=/img/softwareimg/${passiveimg}/toolkit/${expprimnodename}
           else
              export CFGMNTPATH=/img/softwareimg/${passiveimg}/toolkit/${expsecnodename}
           fi
        fi
     fi
  fi
  
  logdebug "Configuration path after function localdata [${CFGMNTPATH}]"
}

# ---------------------------------------------------------------
# function: checkimagedsys
# args    : None
# description:
#   checks if imaged system, if not bye bye
# ---------------------------------------------------------------

checkimagedsys( )
{
   if [ "$imagedsys" != "true" ];
   then
      exit $NONIMAGEDSYS
   fi
}

deleteparms( )
{
    if [ "$mynode" = "$primhost" ];
    then
    DELETEPARMS=/repository/deleteparms
    cat << EOF > $DELETEPARMS
#!/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>"
   }
}

eval spawn RtpAdmCli -p 40 -x

login

send_check_error "confDeleteParameter \"Srx/MobileClient/SBCTLSList\"\r"
send_check_error "confDeleteParameter \"Srx/MobileClient/ServiceContactEmail\"\r"
send_check_error "confDeleteParameter \"Srx/MobileClient/VoiceMailAccessGNF\"\r"
send_check_error "confDeleteParameter \"Srx/MobileClient/TimeoutOSMONotReachable\"\r"
send_check_error "confDeleteParameter \"Srx/Main/UseOnsDisplayForOsmo\"\r"
send_check_error "confDeleteParameter \"Srx/IpPacketPriority/EnableWmm\"\r"
send_check_error "confDeleteParameter \"Srx/MobileClient/wifiCodecPriorityList\"\r"
send_check_error "confDeleteParameter \"Srx/MobileClient/mediaSecurityModeOsv\"\r"
send_check_error "confDeleteParameter \"Srx/MobileClient/mediaSecurityModeSbc\"\r"
send_check_error "confDeleteParameter \"Srx/MobileClient/wifiVideoCodecPriorityList\"\r"
send_check_error "confDeleteParameter \"Srx/MobileClient/noDeskPhone\"\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 $DELETEPARMS
   su - srx -c "$DELETEPARMS" 1>>$LOGFILE 2>&1
   rm -f $DELETEPARMS
   fi

}


# ---------------------------------------------------------------
# function: check_system_configuration
# args    : None
# description:
#   Checks if the system is properly configured
# ---------------------------------------------------------------
check_system_configuration( ) {
	textncolor $BoldCyan "Checking system configuration state."
	
	# Check if this is an OSEE V9 or later system and the reconfiguration systemD unit file is present
	# On image upgraded systems, this systemd unit file is not present. Only reference OVAs have this service installed.
	if [ "X$(isOSEE)X" = "XtrueX" -a -f /usr/local/lib/systemd/system/osee_customer_cfg.service ]
	then
		readonly disabled_osee_cfg_status=$(systemctl status osee_customer_cfg.service | grep 'Loaded:' | grep 'disabled' 1>/dev/null 2>&1; echo $?)
		readonly disabled_osee_cfg="/sbin/osee_customer_cfg.sh.disabled"
		
		if [ ${disabled_osee_cfg_status} -eq 0 -a -f "${disabled_osee_cfg}" ]
		then
			# Already configured OSEE V9 and above
			return 0
		else
			# Unconfigured OSEE V9 and above
			return 1
		fi
	else
		# Plain OSV or image upgraded OSEE OSV V9 and above.
		return 0
	fi
}


### MAIN LOGIC
debug_info_startup_script

# Check the system configuration state, in OSEE V9 and above we should not
# continue if the system is not yet configured with the WebCDC vApp.iso
if ! check_system_configuration
then
	textncolor $BoldRed "Your system is not yet properly configured in order to apply any upgrade or migration scenario. Aborting..."
	if [ "X$(isOSEE)X" = "XtrueX" ]
	then
		textncolor $BoldRed "In order to perform any upgrade or migration scenario to your OSEE Openscape Voice node,
you need first to configure it with the WebCDC vApp.iso. Consult the OSEE installation/upgrade guide for version 9 or later."
	fi
	
	exit $FAIL
fi

ARGLIST="$*"
initvars 

# Check and setup pool of ntp servers
if [ "$1" = "-reconfigntp" ]
then
   logstr "prepare8k is called with $1, bypass getactiveinfo and call reconfigntp"
   reconfigntp
   exit $?

fi

if [ "$hipath8k" = "true" ];
then
   getactiveinfo
else
   getactiveplatinfo
fi
while [ "$#" -gt "0" ];
do
   case $1 in
      '-log')
         shift
         LOGFILE=$1
         ;;
      '-cfg')
         shift
         if [ "$1" != "" ];
         then
            if [ "$Export8kOnly" = "true" -a "`basename $1`" = "toolkit" ];
            then
               logstr "Please choose a different name. /software/toolkit is reserved for toolkit backup!."
               exit $MISSINGCFGDIR
            fi   
            if [  -d $1 ];
            then
               dirofcfgpath=$1
            else
               dirofcfgpath="`dirname $1`"
            fi
            if [ "$dirofcfgpath" = "/" ];
            then
               logstr "Sorry, do not support placing node.cfg in root partition."
               exit $ROOTPARTNOT4IMAGE
            fi
            noleadtop=${dirofcfgpath#/}
            nolead=${noleadtop%%/*}
            notrail=${dirofcfgpath#/*/}
	    
            logdebug "noleadtop[${noleadtop}], nolead[${nolead}], notrail[${notrail}]"
 
            if [ "$imagedsys" = "true" ];
            then
               if [ "${nolead}" != "img" ];
               then
                  export CFGMNTPATH="/img/${nolead}img/${activeimg}/${notrail}"
               else
                  export CFGMNTPATH="/img/${notrail}"
               fi
            else
               export CFGMNTPATH=$dirofcfgpath
            fi
            if [ ! -d $CFGMNTPATH ];
            then
              if [ -d $1 ];
              then
                 export CFGMNTPATH=$1
                 logstr "[${_SELF_}]: Using $CFGMNTPATH instead of external USB device."
              else
                 logstr "Sorry, $CFGMNTPATH does not exist."
                 exit $MISSINGCFGDIR
              fi
            fi
          else
            logstr "Sorry, $CFGMNTPATH does not exist."
            exit $MISSINGCFGDIR
          fi
         ;;
      '-local')
         export LOCAL4USB=true
         ;;
      '-quiet')
         export INTERACTIVE8k=false
         ;;
      '-hd'|'-usb')
        checkimagedsys
        shift
        isopath=$1
        dirofisopath="`dirname $1`"
        if [ "$dirofisopath" = "/" ];
        then
            logstr "Sorry, do not support placing image in root partition."
            exit $ROOTPARTNOT4IMAGE
         fi
         noleadtop=${isopath#/}
         nolead=${noleadtop%%/*}
         notrail=${isopath#/*/}
 

         if [ "${nolead}" != "img" ];
         then
            export ISOPATH="/img/${nolead}img/${activeimg}/${notrail}"
         else
            export ISOPATH="/img/${notrail}"
         fi
         #<DeltaImageSupport>
            if [ -f ${dirofisopath}/goldenimg.iso -a -f ${dirofisopath}/deltaimg.iso ];
            then
                xdelta3 -f -d -s  ${dirofisopath}/goldenimage.iso  ${dirofisopath}/deltaimage.iso $ISOPATH
                if [ $? -ne 0 ];
                then
                   exit $DELTARECOMPOSEFAILED
                fi
            fi
         #</DeltaImageSupport>
         if [ ! -f $ISOPATH ];
         then
            logstr "Sorry, $ISOPATH does not exist."
            exit $MISSINGISO
         fi
        ;;
      '-save')
        export Save8k=true
        checkimagedsys
        savesysdata
        exit $SUCCESS
        ;;
      '-restore')
        export Restore8k=true
        checkimagedsys
        restoresysdata
        exit $SUCCESS
        ;;
      '-export')
        export ExportOsv=true
        localdata "export"
        exportdata
        exit $SUCCESS
        ;;
      '-import')
        export ImportOsv=true
        localdata "import"
        SYSIMPORT=true
        IMPORTHOSTS=true
        importdata
        exit $SUCCESS
        ;;
      '-migrate')
        localdata "migrate"
        SYSIMPORT=false
        export Migrate8k=true
        importdata
        exit $SUCCESS
        ;;
      '-password')
        IMPORTPASSWD=true
        ;;
      '-nopassword')
        IMPORTPASSWD=false
        ;;
      '-config')
        IMPORTHOSTS=true
        ;;
      '-nosec')
        CUSTOMSECURITY=false
        ;;
      '-i')
         shift
         LOCKSIDE="$1"
         ;;
      '-lock')
        checkimagedsys
        if [ "$LOCKSIDE" != "" ];
        then
           checkremote "-i $LOCKSIDE -lock"
        else
           checkremote "-lock"
        fi
        if [ "$LOCKSIDE" = "primary" -o "$LOCKSIDE" = "secondary" ];
        then
           touch /img/logimg/${LOCKSIDE}/upgrade.lock
        else
           touch /log/upgrade.lock
        fi
        exit $SUCCESS
        ;;
      '-dist')
        checkremote "-dist"
        copyexports
        exit $SUCCESS
        ;;
      '-ping')
        CHECK4CLSTATUS=true
        checkremote "$ARGLIST"
        exit $SUCCESS
        ;;
      '-recover')
        logstr "   - Recovery mode!. Operations on remote node are skipped."
        RECOVER8k=true
        ;;
      '-check')
        CHECK4USB=true
        if [ "$LOCAL4USB" = "true" ];
        then
           localdata "check"
        fi
        checkremote "$ARGLIST"
        findusb "check"
        exit $SUCCESS
        ;;
      '-hw')
        HW=true
        ;;
      '-zen')
        CHECK4CFG=true
        if [ "$LOCAL4USB" = "true" ];
        then
           localdata "check"
        fi
        checkremote "$ARGLIST"
        findusb "zen"
        exit $SUCCESS
        ;;
      '-unlock')
        checkimagedsys
        if [ "$LOCKSIDE" != "" ];
        then
           checkremote "-i $LOCKSIDE -unlock"
        else
           checkremote "-unlock"
        fi

        if [ "$activeimg" = "primary" ] ;
        then
           primrootdir="/"
           secrootdir="${ROOTIMGDIR}/"
         else
           primrootdir="${ROOTIMGDIR}/"
           secrootdir="/"
         fi

        if [ -f /img/logimg/primary/upgrade.lock -a "$LOCKSIDE" = "primary" ];
        then
           if [ -f "${primrootdir}etc/osv-release" ]
           then 
             source "${primrootdir}etc/osv-release"
             primloadversion="V${OSV_VERSION_MAJOR}R${OSV_VERSION_MINOR}.${OSV_VERSION_PATCH}.${OSV_VERSION_HOTFIX}"
           else
             logwarning "[${BASH_SOURCE[1]}:${BASH_LINENO[0]}] File osv-release was not found!"
             primloadpkg="`rpm -aq --dbpath  /img/varimg/primary/lib/rpm 2>/dev/null | grep UNSPbase  2>/dev/null`" 
             primloadversion="`rpm -qi --dbpath /img/varimg/primary/lib/rpm $primloadpkg 2>/dev/null | \
                                                                  grep Version | awk '{ print $3 }' 2>/dev/null`"
           fi
           primpatchversion="`rpm -aq --dbpath /img/varimg/primary/lib/rpm 2>/dev/null | grep UNSPps[0-9][0-9][0-9][0-9]* \
                                                        | sort | tail -1 | sed -e 's/-.*//' 2>/dev/null`"
           primpatchversion=${patchversion:-"None"}
           textncolor $BoldCyan "Information: You had a lock on primary:${primloadversion}/${primpatchversion}."
           echo                 "           : Removing this lock on `uname -n`!."
        fi
        if [ -f /img/logimg/secondary/upgrade.lock -a "$LOCKSIDE" = "secondary" ];
        then
           if [ -f "${secrootdir}etc/osv-release" ]
           then 
             source "${secrootdir}etc/osv-release"
             secloadversion="V${OSV_VERSION_MAJOR}R${OSV_VERSION_MINOR}.${OSV_VERSION_PATCH}.${OSV_VERSION_HOTFIX}"
           else
             logwarning "[${BASH_SOURCE[1]}:${BASH_LINENO[0]}] File osv-release was not found!"
             secloadpkg="`rpm -aq --dbpath  /img/varimg/secondary/lib/rpm 2>/dev/null | grep UNSPbase  2>/dev/null`" 
             secloadversion="`rpm -qi --dbpath /img/varimg/secondary/lib/rpm $secloadpkg 2>/dev/null | \
                                                                  grep Version | awk '{ print $3 }' 2>/dev/null`"
           fi
           secpatchversion="`rpm -aq --dbpath /img/varimg/secondary/lib/rpm 2>/dev/null | grep UNSPps[0-9][0-9][0-9][0-9]* \
                                                        | sort | tail -1 | sed -e 's/-.*//' 2>/dev/null`"
           secpatchversion=${patchversion:-"None"}
           textncolor $BoldCyan "Information: You had a lock on secondary:${secloadversion}/${secpatchversion}."
           echo                 "           : Removing this lock on `uname -n`!."
        fi
        if [ "$LOCKSIDE" = "" ];
        then
           rm -f /img/logimg/primary/upgrade.lock /img/logimg/secondary/upgrade.lock
        else
           rm -f /img/logimg/${LOCKSIDE}/upgrade.lock 
        fi
        exit $SUCCESS
        ;;
      '-clusterip')
        CLUSTERIPXCHANGE=true
        clusterip
        exit $SUCCESS
        ;;
      '-billingip')
        BILLINGIPXCHNAGE=true
        billingip
        exit $SUCCESS
        ;;
      '-signalingip')
        SIGIPXCHNAGE=true
        sigip
        exit $SUCCESS
        ;;
      '-ntp')
        NTPXCHANGE=true
        ntpip
        exit $SUCCESS
        ;;
      '-dns')
        DNSXCHANGE=true
        dnsip
        exit $SUCCESS
        ;;
      '-nodename')
        NODENAMEXCHANGE=true
        nodename
        exit $SUCCESS
        ;;
      '-noapps')
        NOAPPS=true
        ;;
      '-noappsindb')
        NOAPPSINDB=true
        ;;
      '-done')
       donexchange
       exit $SUCCESS
       ;;
      '-live')
       LIVE8kUPGRADE=true
       ;;
      '-liveexp')
       LIVE8kUPGRADEEXP=true
       ;;
      '-noliveexp')
       NON_OUTAGE_FREE_UPGRADE_EXPORT=true
       ;; 
      '-ucdbexp')
       UC_DB_EXPORT=true
       ;; 
      *)
        logstr "Unknown option passed."
        exit $FAIL
   esac
   shift
done

checkimagedsys
prepsys
mkramdisk
mountdvd
setup
logstr "Done."
sync
exit $SUCCESS 

#</FRN2782>

