#!/bin/bash 

# -------------------------------------------------------
# file   : sync8k.sh
# purpose: Sync the currently booted OSV load image to the
# other image load.
# authors:
#	Alexandros Kardaris <alexandros.kardaris@unify.com>
#	Konstantinos Brokalakis <konstantinos.brokalakis@unify.com>
#	Konstantinos Kontopoulos <konstantinos.kontopoulos@unify.com>
#	Miltiadis Koutsokeras <miltiadis.koutsokeras@unify.com>
#	Vittal.S
#
# usage:
#	sync8k [ option ]
# Normal user options:		[-h, -d, -q, -v]
# Root user only options:	[-auto, -r, -quiet, -progress, -status, -a, -s, -live]
# -------------------------------------------------------

LANG=C

### Script setup
_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'}"

### Constants
readonly grubinstaller="/unisphere/srx3000/srx/bin/install_bootloader.sh"
readonly root_prim_part=2
readonly root_sec_part=3
readonly optimg_part=12
readonly ROOTSYS=/rootsys
readonly IMGDIR=/img/rootimg
readonly syncdir="$(dirname $0)"
readonly USER="$(id -u)"
readonly MYID=$$
readonly ARGS=$*

#///////////////////  Exit Error Codes ////////////////////////
readonly Success=0
readonly RsyncFailure=1
readonly NoDiskSpace=2
readonly ActivateFailure=3
readonly InvalidOption=4
readonly SelfChopFailure=5
readonly DbBackupFailure=6
readonly UidMisMatch=7
readonly ImgDiskNotSupported=8
readonly RsyncNotFound=9
readonly UserAbort=10
readonly InvalidDiskType=11
readonly NonImageDisk=12
readonly StrangeMountPoints=13
readonly SomethingMountedOnFallback=14
readonly Sync8kAlreadyRunning=15
readonly CleanFallbackFailure=16
readonly SyncInitiationFailure=17
readonly LockAcquisitionFailure=18
readonly Activate8kAlreadyRunning=15
readonly UnsupportedProduct=16
readonly MissingMountPoint=17
readonly MalformedMountTab=18
readonly UnknownProductType=19
readonly CannotDetectActiveLoad=20
#///////////////////  Exit Error Codes ////////////////////////

### Include files
if ! source ${_SELFDIR_}/common.inc
then
    echo "FATAL ERROR: Cannot include ${_SELFDIR_}/common.inc" 1>&2
    exit 128
fi
#Check if osv_version is available
OSV_VERSION=$(whereis -b osv_version.sh | awk '{ print $2 }')
if [ ! -f "$OSV_VERSION" ]; then
   logger --id $$ --priority user.warning "$0: osv_version.sh not found in \$PATH ($PATH), exiting!" >/dev/null 2>&1
   exit 1
fi

### Variables
PRIMARYACTIVE=0
SECONDARYACTIVE=0
syncpart=""
QuietSync8k="false"
LiveUpdate8k=${LiveUpdate8k:-false}
Fit4More="false"
LOGFILE="/log/sync8k.auto"
product="$(/sbin/cfgread product_type)"
component="$(/sbin/cfgread component_type)"


### Functions

# ----------------------------------------------
# function _mount_grep 
# arg : none
#    description : a private function for outputing the
#    mount in tabbed format and g
#
_mount( ) {

   if [ -h /etc/mtab ]
   then
      MOUNT_CMD="findmnt --fstab --evaluate"
   else
      MOUNT_CMD="mount"
   fi 
   
   ret="$(${MOUNT_CMD})"
   res=$?

   echo "$ret"
   return $res
   
}

# -------------------------------------------------------
# function: syncnexit
# args    :  none
# description: 
#    always sync file system before exit. Remember murpy.
# -------------------------------------------------------
syncnexit( ) {
   synccode=$1
   sync
   if [ "$synccode" -eq $CleanFallbackFailure ]
   then
      #<RestoreGrub>
      if [ -d /software/fbboot/boot ]
      then
         rm -rf /img/rootimg/boot
         cp -R -p /software/fbboot/boot /img/rootimg/boot
         rm -rf /software/fbboot/boot
      fi
      #</RestoreGrub>
   fi
   sync
   exit $synccode
}

# -------------------------------------------------------
# function:  log
# args    :  none
# description: 
#   log every bit.
# -------------------------------------------------------
log( ) {
   echo -n "${MYID}:${ARGS},$(date):" >> ${LOGFILE}
   if tty | egrep -q "^/dev"
   then
      echo "$1" | tee -a ${LOGFILE}
   else
      echo "$1"
      echo "$1" >> ${LOGFILE}
   fi
}

# -------------------------------------------------------
# function: syncroot
# args    :  none
# description: syncs the primary image with secondary. 
#   Here we take each mount point in the current image and
#   sync it to the corresponding mount point in the sync
#   image.
# -------------------------------------------------------
syncroot( ) {
    #<CheckLocks>
       if ! lockfile -l 30 /lock/sync8k.usg
       then
          log "${_SELF_}:Could not acquire lock. Try again."
          rm -f /lock/sync8k.usg
          exit $LockAcquisitionFailure 
       fi
       rm -f /lock/sync8k.usg /lock/sync8k.fs
    #</CheckLocks>

    lockfile -s 1 /lock/sync8k.usg
    #</InitializeStatus>
      >/lock/sync8k.dmap

      #<CheckActive>
      if grep "/var" /etc/fstab | grep -v "^/dev/${diskdev}" | grep -q 'primary'
      then
          syncpart="primary"
          syncother="secondary"
      elif grep "/var" /etc/fstab | grep -v "^/dev/${diskdev}" | grep -q 'secondary'
      then
          syncpart="secondary"
          syncother="primary"
      else
          logerror "Active image load cannot be determined, this is fatal! Aborting..."
          syncnexit ${CannotDetectActiveLoad}
      fi
      #</CheckActive>

      #<InitializeStatus>
       {
          startts="$(date -u)"
          log "Last ${_SELF_} : $startts"
          log "Note        : ${syncpart} was active during sync8k."
          log "State       : initiated"
       }  > /lock/sync8k.lock
      #</InitializeStatus>

      #<ComputeUsage>

      totaldu=0
      if [ "X${product}X" = "XHiPath8000X" ]
      then
         partitions="
            root       \
            var        \
            home       \
            cdr        \
            log        \
            opt        \
            tpa        \
            enterprise \
            software   \
            tmp        \
            global     \
            unisphere
          "
      else
         if [ "X${product}X" = "XOpenScapeX" ]
         then
         partitions="
            root       \
            var        \
            db         \
            opt        \
            software   \
            tmp
          "
         else
            echo "[${_SELF_}] Unsupported product type."
            syncnexit $UnsupportedProduct 
         fi
      fi
      for diskidx in $partitions
      do
         if [ "X${diskidx}X" = "XrootX" ]
         then
            diskusage[${diskidx}]=$(du -k -s -x / | awk '{ print $1 }')
         else
            local mountpoint_result_code=''

            if [ -x /bin/mountpoint ]
            then
               mountpoint -q /$diskidx; mountpoint_result_code=$?
            else
               cat /proc/mounts | cut -d' ' -f2 | egrep -q "^/${diskidx}$"; mountpoint_result_code=$?
            fi

            if [ ${mountpoint_result_code} -ne 0 ]
            then
               echo "[${_SELF_}] : Mountpoint($diskidx) not as expected ?."
               syncnexit $MissingMountPoint
            fi

            if [ "$diskidx" = "cdr"      -o \
                 "$diskidx" = "log"      -o \
                 "$diskidx" = "tpa"      -o \
                 "$diskidx" = "software" -o \
                 "$diskidx" = "tmp" ]
            then
               diskusage[${diskidx}]=4096
            else
               diskusage[${diskidx}]=$(du -k -s -x /${diskidx}  | awk '{ print $1 }')
            fi

         fi

         totaldu=$(expr $totaldu + ${diskusage[${diskidx}]})
         log ${diskidx}:${diskusage[${diskidx}]}
      done >> /lock/sync8k.dmap
      {
         log "total:$totaldu" 
         log "active:$syncpart"
         log "fallback:$syncother"
      } >> /lock/sync8k.dmap
      rm -f /lock/sync8k.fs
    #</ComputeUsage>
    rm -f /lock/sync8k.usg

    startts="$(date -u)"
    varstr="[*] Syncing root"
    setmeup  "${varstr}" ${#varstr} 40 
    echo -n "${cfgvarres}" |  sed -e 's/!/ /g'
    echo -n ': '
    count=0
    while ( true )
    do
      count=$(expr $count + 1)
      rm -rf /img/rootimg/* 1>>/log/sync8k.log 2>&1
      if [ $? -ne 0 ]
      then
         find /img/rootimg -type f -exec rm {} \; 1>>/log/sync8k.log 2>&1
         echo -n "."
         if [ $count -lt 16 ]
         then
            sync
            sleep 8
            continue
         fi
         echo "failed"
         log "Cannot sync active to fallback. Report failure."
         didyouknow
         syncnexit $RsyncFailure
      fi
      sync
      break;
    done

    sync

    lockfile -s 1 /lock/sync8k.usg
    echo "root" > /lock/sync8k.fs
    rm -f /lock/sync8k.usg

    rsyncexe="$(which rsync)"
    if [ "$rsyncexe" = "" ]
    then
        rsyncexe=$syncdir/rsync
    fi

    #<InitializeStatus>
       {
          startts="$(date -u)"
          echo "Last ${_SELF_} : $startts"
          echo "Note        : ${syncpart} was active during sync8k."
          echo "State       : progress"
       }  > /lock/sync8k.lock
    #</InitializeStatus>

    # pre-sync + hardlink specified dirs before the main rsync
    for pathtofix in usr/lib/locale usr/lib64/dri
    do
       if [ -d "/${pathtofix}" ]
       then
          mkdir -p /img/rootimg/${pathtofix}
          $rsyncexe -cavz -X -x --whole-file --force --sparse --delete \
             /${pathtofix}/ /img/rootimg/${pathtofix} 1>>/log/sync8k.log 2>&1
          if [ $? -ne 0 ]
          then
             log "Cannot pre-sync /${pathtofix} to fallback. Report failure."
             syncnexit $RsyncFailure
          fi
          if [ -f "$(which hardlink 2>/dev/null)" ]
          then
             hardlink /img/rootimg/${pathtofix} 1>>/log/sync8k.log 2>&1
          fi
       fi
    done

    count=0
    while ( true )
    do
       count=$(expr $count + 1)
       $rsyncexe -cavz -X -x --whole-file \
          --force --sparse                \
          --delete                        \
          --exclude=/proc                 \
          --exclude=/sys                  \
          --exclude=/media                \
          --exclude=/tmp                  \
          --exclude=/img/cdrimg/          \
          --exclude=/img/enterpriseimg/   \
          --exclude=/img/globalimg/       \
          --exclude=/img/homeimg/         \
          --exclude=/img/logimg/          \
          --exclude=/img/optimg/          \
          --exclude=/img/rootimg/         \
          --exclude=/img/softwareimg/     \
          --exclude=/img/tpaimg/          \
          --exclude=/img/tmpimg/          \
          --exclude=/img/unisphereimg/    \
          --exclude=/img/varimg/          \
          --exclude=/cdr/                 \
          --exclude=/enterprise/          \
          --exclude=/global/              \
          --exclude=/home/                \
          --exclude=/log/                 \
          --exclude=/opt/                 \
          --exclude=/software/            \
          --exclude=/tpa/                 \
          --exclude=/tmp/                 \
          --exclude=/unisphere/           \
          --exclude=/var/                 \
          --exclude=/usr/lib/locale/      \
          --exclude=/usr/lib64/dri/       \
          / /img/rootimg 1>>/log/sync8k.log 2>&1

       if [ $? -ne 0 ]
       then
         echo -n "$count."
         if [ $count -lt 8 ]
         then
            sleep 8
            continue
         fi
         echo "failed"
         log "Cannot sync active to fallback after $count attepmts. Report failure."
         syncnexit $RsyncFailure
       fi
       echo "ok"

       break

    done

    mkdir -p  $IMGDIR/proc $IMGDIR/sys $IMGDIR/media       \
              $IMGDIR/media/cdrom $IMGDIR/media/floppy     \
              $IMGDIR/media/cdrecorder $IMGDIR/media/usb   \
              $IMGDIR/img/cdrimg $IMGDIR/cdr               \
              $IMGDIR/img/enterpriseimg $IMGDIR/enterprise \
              $IMGDIR/img/globalimg $IMGDIR/global         \
              $IMGDIR/img/homeimg $IMGDIR/home             \
              $IMGDIR/img/logimg $IMGDIR/log               \
              $IMGDIR/img/optimg $IMGDIR/opt               \
              $IMGDIR/img/softwareimg $IMGDIR/software     \
              $IMGDIR/img/tpaimg $IMGDIR/tpa               \
              $IMGDIR/img/tmpimg $IMGDIR/tmp               \
              $IMGDIR/img/unisphereimg $IMGDIR/unisphere   \
              $IMGDIR/img/varimg $IMGDIR/var               \
              $IMGDIR/img/rootimg

   sync
}

# -------------------------------------------------------
# function: chkwithuser
# args    :  none
# description:
#   prompts the user to confirm.
# -------------------------------------------------------
chkwithuser( ) {
   #<SkipInput4QuietMode>
   if [ "$QuietSync8k" = "false" ]
   then
      echo "///////////////   Warning: All data on fallback will be lost. ///////////////"
      echo -n "This will erase all data on the fallback partition. Type yes to continue ?"
      read answer
      if [ "$answer" != "yes" ]
      then
         log "Aborting."
         syncnexit $UserAbort
      fi
      echo "///////////////   Warning: All data on fallback will be lost. ///////////////"
   fi
   #</SkipInput4QuietMode>

   > /log/sync8k.log
}

# -------------------------------------------------------
# function: usage
# args    :  none
# description:
#   prompts the user to usage of this script.
# -------------------------------------------------------
usage( ) {
   echo "Usage: ${_SELF_} [ -h | -q | -v | -r | -auto ]"
   echo "  When ${_SELF_} is passed without any option it syncs the active to fallback."
   echo "  Note: activate8k activates fallback on next reboot."
   echo "  ${_SELF_} -h    : display's this help."
   echo "  ${_SELF_} -q    : display's status of active and fallback images."
   echo "  ${_SELF_} -v    : display's verbose status of active and fallback images."
   echo "  ${_SELF_} -d    : display's status in release format."
   echo "  ${_SELF_} -r    : cleans up the fallback image."
   echo "  ${_SELF_} -auto : automatically sync the fallback on both nodes of cluster."
}

# -------------------------------------------------------
# function: didyouknow
# args    :  none
# description: 
#   prompts the user to largest resident files on disk.
# -------------------------------------------------------
didyouknow( ) { 
   fs="/ /var /opt /unisphere /home /enterprise /software /global /tpa /tmp /cdr"
   echo "-------------------------------------------------------"
   echo "///////////////////////////////////////////////////////"
   echo "Did you know? The following directories occupy top space."
   echo "Check if you have placed any temporary files in one of these."
   for dridx in $fs 
   do
      if [ ! -d $dridx ]
      then
         continue
      fi

		# OSV-916: Do not include in calculation the proc filesystem
		# inside NTP daemon's chroot environment
		local du_exclude=""
		if [ "X${dridx}X" = "X/varX" ]
		then
			du_exclude="--exclude=lib/ntp/proc"

			# In OSEE V9 and above (or any OSV that runs the named DNS server)
			# there is also named daemon's chroot environment that will mess
			# up the disk usage calculations. So exclude it by default, in
			# systems that do not have a running named it is a no-op, it does
			# not have any impact on the calculation
			du_exclude="${du_exclude} --exclude=lib/named/proc"
		fi

      echo "   ${dridx}:"
      dirs="$(du -x -S $dridx ${du_exclude} | sort -nr | head -5 | awk '{ print $2 }' 2>/dev/null)"
      for idx in $dirs
      do
         space=$(du -s -h $idx ${du_exclude} | head -5 | awk '{ print $1 }' 2>/dev/null)
         echo "      - $idx( $space )"
      done
   done
   echo "-------------------------------------------------------"
   echo "///////////////////////////////////////////////////////"
}
   
# -------------------------------------------------------
# function:  chkusg
# args    :
#	$1 directory of filesystem to check (/var, /home, etc.)
#	$2 source partition load to sync data from: primary or secondary
#	$3 target partition load to sync data to: secondary or primary
#	$4 ????: valuse is 'all' or 'structure' NOT USED in function AT ALL
# description: 
#   makes sure that there in enough space to do sync.
# -------------------------------------------------------
chkusg( ) {
   if [ -x /bin/mountpoint ]
   then
      mountpoint -q /${1}
   else
      cat /proc/mounts | cut -d' ' -f2 | egrep -q "^/${1}$"
   fi
   if [ $? -ne 0 ]
   then
      echo "[${_SELF_}] : Mountpoint($diskidx) not as expected ?."
      syncnexit $MissingMountPoint
   fi

   # OSV-916: Do not include in calculation the proc filesystem
   # inside NTP daemon's chroot environment
   local du_exclude=""
   if [ "X${1}X" = "XvarX" ]
   then
       du_exclude="--exclude=lib/ntp/proc"

	   # In OSEE V9 and above (or any OSV that runs the named DNS server)
	   # there is also named daemon's chroot environment that will mess
	   # up the disk usage calculations. So exclude it by default, in
	   # systems that do not have a running named it is a no-op, it does
	   # not have any impact on the calculation
	   du_exclude="${du_exclude} --exclude=lib/named/proc"
   fi

   varstr="[*] Checking disk space in ${1} "
   setmeup  "${varstr}" ${#1} 40 
   echo -n "${cfgvarres}" | sed -e 's/!/ /g'
   echo -n ': '
   dusyncpart=$(du -k -s /img/${1}img/$2/ ${du_exclude} | awk '{ print $1 }')
   dusyncother=$(du -k -s /img/${1}img/$3/ ${du_exclude} | awk '{ print $1 }')
   dfsyncother=$(df -k /img/${1}img/$3/ | grep -e "/img/${1}img" | awk '{ print $4 }')
   dfsyncother=$(expr $dfsyncother + $dusyncother)
   dfneeded=$(expr $dusyncpart + 1024 \* 10)
   if [ $dfsyncother -lt $dfneeded ]
   then
      df_mibs=$(df --block-size=MB /img/${1}img/ | grep -e "/img/${1}img" | awk '{ print $4 }')
      dusyncpart_mibs=$(du --block-size=MB -s /img/${1}img/$2/ | awk '{ print $1 }')
      dusyncother_mibs=$(du --block-size=MB -s /img/${1}img/$3/ | awk '{ print $1 }')
      echo "nok"
      echo "Please check $1 for disk space utilization. Partition available space is ${df_mibs}."
      echo "We don't have enough space to sync copy the data in ${2} load[${dusyncpart_mibs}] into ${3} load[${dusyncother_mibs}]."
      echo "The ${1} filesystem partition may have available space, but cannot contain a dual copy of the ${2} load[${dusyncpart_mibs}] in both loads."
      echo "You need to free disk space in the ${1} filesystem manually by backing up and deleting old/uneeded files that take up significant space."
      didyouknow
      syncnexit $NoDiskSpace
   else
      echo "ok"
   fi
}

# -------------------------------------------------------
# function: cleanimg
# args    :  none
# description: 
#   cleans fallback partition.
# -------------------------------------------------------
cleanimg( ) {
   varstr="[*] Cleaning fallback:${1}  "
   setmeup  "${varstr}" ${#1} 40 
   echo -n "${cfgvarres}" | sed -e 's/!/ /g'
   echo -n ': '
   count=0
   while ( true )
   do
      count=$(expr $count + 1)
      rm -rf /img/${1}img/$3/* 1>>/log/sync8k.log 2>&1
      if [ $? -ne 0 ]
      then
         find /img/${1}img/$3 -type f -exec rm {} \; 1>>/log/sync8k.log 2>&1
         echo -n "."
         if [ $count -lt 16 ]
         then
            sync
            sleep 8
            continue
         fi
         echo "failed"
         log "Cannot clean fallback. Report failure."
         syncnexit $CleanFallbackFailure
      fi
      sync
      echo "ok"
      break;
   done
   sync
}

# -------------------------------------------------------
# function: syncimg
# args    :  none
# description: 
#   sync active with fallback.
# -------------------------------------------------------
syncimg( ) {

   if [ -x /bin/mountpoint ]
   then
      mountpoint -q /${1}
   else
      cat /proc/mounts | cut -d' ' -f2 | egrep -q "^/${1}$"
   fi
   if [ $? -ne 0 ]
   then
      echo "[${_SELF_}] : Mountpoint($diskidx) not as expected ?."
      syncnexit $MissingMountPoint
   fi
   varstr="[*] Syncing ${1}  "
   setmeup  "${varstr}" ${#1} 40 
   echo -n "${cfgvarres}" | sed -e 's/!/ /g'
   echo -n ': '
   count=0
   while ( true )
   do
      count=$(expr $count + 1)
      rm -rf /img/${1}img/$3/* 1>>/log/sync8k.log 2>&1
      if [ $? -ne 0 ]
      then
         find /img/${1}img/$3 -type f -exec rm {} \; 1>>/log/sync8k.log 2>&1
         echo -n "."
         if [ $count -lt 16 ]
         then
            sync
            sleep 8
            continue
         fi
         echo "failed"
         log "Cannot sync active to fallback. Report failure."
         didyouknow
         syncnexit $RsyncFailure
      fi
      sync
      break;
   done

   lockfile -s 1 /lock/sync8k.usg
   echo "$1" > /lock/sync8k.fs
   rm -f /lock/sync8k.usg

   rsyncexe="$(which rsync)"
   if [ "$rsyncexe" = "" ]
   then
      rsyncexe=$syncdir/rsync
   fi
   count=0
   while ( true )
   do
      count=$(expr $count + 1)
      if [ "${4}" = "all" ]
      then
         $rsyncexe -cavz -X -x --force --sparse --delete --whole-file \
                                 --exclude '/var/backup/solid'        \
                                 /img/${1}img/$2/ /img/${1}img/$3 1>>/log/sync8k.log 2>&1
      else
         $rsyncexe -cavz -X -x --force --sparse --delete --delete-excluded --whole-file --include '*/' \
                                 --include '.profile'                                                  \
                                 --exclude '*'                                                         \
                                 /img/${1}img/$2/ /img/${1}img/$3 1>>/log/sync8k.log 2>&1
      fi
      if [ $? -ne 0 ]
      then
         echo -n "$count."
         if [ $count -lt 16 ]
         then
            sleep 8
            continue
         fi
         echo "failed"
         log "Cannot sync active to fallback. Report failure."
         didyouknow
         syncnexit $RsyncFailure
      fi
      echo "ok"
      break;
   done
   sync
}

# -------------------------------------------------------
# function: fstab_setup
# args    :  none
# description: 
#   setups up fstab to reflect the active partition on
#   the target fallback load.
# -------------------------------------------------------
fstab_setup( ) {
   # Primary active in fstab
   if grep -q 'primary' /etc/fstab
   then
      cat /etc/fstab                                    |  \
           sed -e "s/primary/secondary/g"                  \
               -e "s/${diskdev}2/${diskdev}_3/g"           \
               -e "s/${diskdev}3/${diskdev}2/g"            \
               -e "s/${diskdev}_3/${diskdev}3/g"           \
                     >  /etc/fstab.secondary
   fi

   # Secondary active in fstab
   if grep -q 'secondary' /etc/fstab
   then
       cat /etc/fstab                                   |    \
            sed -e "s/secondary/primary/g"                   \
                -e "s/${diskdev}3/${diskdev}_2/g"            \
                -e "s/${diskdev}2/${diskdev}3/g"             \
                -e "s/${diskdev}_2/${diskdev}2/g"            \
                          >  /etc/fstab.primary
   fi

   if [ "X${syncpart}X" = "XprimaryX" ] # Synced primary to secondary
   then
      cp /etc/fstab.secondary /img/rootimg/etc/fstab
      rm /etc/fstab.secondary
   else # Synced secondary to primary
      cp /etc/fstab.primary /img/rootimg/etc/fstab
      rm /etc/fstab.primary
   fi

   # In SLES 11 and below the /etc/mtab will get recreated during boot.
   # What happens to SLES12 symbolic link to /proc/mounts?
   rm -f /img/rootimg/etc/mtab
}

# -------------------------------------------------------
# function: activate
# args    :  none
# description: 
#   Makes sure that the versions are the same after sync.
# -------------------------------------------------------
activate( ) {
    if [ "X${activate}X" != "XX" ]
    then
        local primpatchversion=''
        local secpatchversion=''

        # Get full patchset versions
        if get_load_fullpsversion 'primary'
        then
            primpatchversion="${_LOADFULLPSVERSION_}"
        else
            log "Cannot detect the patchset version of primary image load, aborting..."
            syncnexit ${ActivateFailure}
        fi
        if get_load_fullpsversion 'secondary'
        then
            secpatchversion="${_LOADFULLPSVERSION_}"
        else
            log "Cannot detect the patchset version of secondary image load, aborting..."
            syncnexit ${ActivateFailure}
        fi

        if [ "x${primpatchversion}x" != "x${secpatchversion}x" ]
        then
            log "Looks like primary and secondary versions are not the same ..."
            log "This means that the sync of the softswitch was not successfull or not initiated."
            log "Contact support for more info."
            syncnexit ${ActivateFailure}
        fi
        echo -n "[*] Setting up the boot options : "

        # Update the boot loader setup
        ${grubinstaller} "${activate}" "/dev/${diskdev}" ${root_prim_part} ${root_sec_part} ${optimg_part} \
            'none' '' '/dev/sda' || syncnexit ${GrubInstFailure}

        echo "2 2 /log/startup_srx.log /log/startup_rtp.log" > /img/unisphereimg/${activate}/srx3000/srx/startup/srxBootParams
        echo "ok"
    fi

}

# -------------------------------------------------------
# function: setcompletion
# args    : none
#   sets completion stamp on sync8k.lock file.
# -------------------------------------------------------
setcompletion( ) {
   lockfile -s 1 /lock/sync8k.usg
   cat /lock/sync8k.lock | sed -e s/^State.*/'State       : completed'/g > /lock/sync8k.lock.new
   cp  /lock/sync8k.lock{.new,}
   cp  /lock/sync8k.lock /img/rootimg/lock/sync8k.lock
   rm -f /lock/sync8k.lock.new
   rm -f /lock/sync8k.usg

   if [ "$product" != "HiPath8000" ]
   then
      return
   fi
   SOLLOGDIR=/img/logimg/$syncother
   for idx in .solcon.txt .solsql.txt Solid_Trace_Log
   do
     touch ${SOLLOGDIR}/${idx}
     chown solid:dba ${SOLLOGDIR}/${idx}
     chmod 0660 ${SOLLOGDIR}/${idx}
   done

}

# -------------------------------------------------------
# function: backupdb
# args    :  none
# description: 
#   backs up the database.
# -------------------------------------------------------
backupdb( ) {
   if [ "$product" = "HiPath8000" ]
   then
      echo -n "[*] Syncing database : "
      ps -ef f | egrep "solid|RtpSolid" | grep -v grep 1>/dev/null 2>&1
      if [ $? -eq 0 ]
      then
         /opt/unisphere/srx3000/mmgr/job/bin/backup_restore/solid/do_solid.sh backup  1>>/log/sync8k.log 2>&1
         if [ $? -ne 0 ]
         then
            echo "failed"
            log "Sorry. Cannot do db backup. Contact support."
            syncnexit $DbBackupFailure
         fi
         mv -f /opt/unisphere/srx3000/mmgr/backup/solid.db /img/homeimg/${syncother}/solid/RtpDb
         if [ $? -ne 0 ]
         then
            echo "failed"
            log "Sorry. Cannot do db backup. Contact support."
            syncnexit $DbBackupFailure
         fi
         rm -f /img/homeimg/${syncother}/solid/RtpDb/sol*.log 2> /dev/null
         chown solid:dba /img/homeimg/${syncother}/solid/RtpDb/solid.db 
         chmod 600       /img/homeimg/${syncother}/solid/RtpDb/solid.db
         MYCCLDB=/img/softwareimg/$syncpart/CCL_DB/call_log.db
         MYCCLBKDB=/img/softwareimg/$syncpart/CCL_DB/call_log_backup.db
         OTHERCCLDB=/img/softwareimg/$syncother/CCL_DB/call_log.db
         if [ -f $MYCCLDB ]
         then
            pgrep RtpNm 1>/dev/null 2>&1
            if [ $? -eq 0 ]
            then
               su - srx -c "dispProcDump -b" 1>>/log/sync8k.log 2>&1
               if [ $? -ne 0 ]
               then
                  echo "failed"
                  log "Sorry. Cannot do ccl-db backup. Contact support."
                  syncnexit $DbBackupFailure
               fi
               mkdir -p /img/softwareimg/$syncother/CCL_DB/
               chown srx.rtpgrp /img/softwareimg/$syncother/CCL_DB/
               mv -f $MYCCLBKDB $OTHERCCLDB
               if [ $? -ne 0 ]
               then
                  echo "failed"
                  log "Sorry. Cannot do ccl-db backup. Contact support."
                  syncnexit $DbBackupFailure
               fi
            else
               cp -f -p $MYCCLDB $OTHERCCLDB   
               if [ $? -ne 0 ]
               then
                  echo "failed"
                  log "Sorry. Cannot do ccl-db backup. Contact support."
                  syncnexit $DbBackupFailure
               fi
            fi
         fi
         echo "ok"
      else
         echo "skipped"
      fi
   fi
   lockfile -s 1 /lock/sync8k.usg
   echo "db" > /lock/sync8k.fs
   rm -f /lock/sync8k.usg
}

# -------------------------------------------------------
# function: fsyncpart
# args    :  none
# description: 
#   displays layout
# -------------------------------------------------------
fsyncpart( ) {
   if [ "$product" = "HiPath8000" ]
   then
       eval "dfsda[0]=$(df -h /dev/${diskdev}2   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[1]=$(df -h /dev/${diskdev}3   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[2]=$(df -h /dev/${diskdev}5   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[3]=$(df -h /dev/${diskdev}6   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[4]=$(df -h /dev/${diskdev}7   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[5]=$(df -h /dev/${diskdev}8   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[6]=$(df -h /dev/${diskdev}9   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[7]=$(df -h /dev/${diskdev}10  | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[8]=$(df -h /dev/${diskdev}11  | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[9]=$(df -h /dev/${diskdev}12  | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[10]=$(df -h /dev/${diskdev}13 | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[11]=$(df -h /dev/${diskdev}14 | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[12]=$(df -h /dev/${diskdev}15 | grep '^/dev' | awk '{ print $5 }')"
   else
       eval "dfsda[0]=$(df -h /dev/${diskdev}2   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[1]=$(df -h /dev/${diskdev}3   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[2]=$(df -h /dev/${diskdev}5   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[3]=$(df -h /dev/${diskdev}6   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[4]=$(df -h /dev/${diskdev}7   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[5]=$(df -h /dev/${diskdev}8   | grep '^/dev' | awk '{ print $5 }')"
       eval "dfsda[6]=$(df -h /dev/${diskdev}9   | grep '^/dev' | awk '{ print $5 }')"
   fi

   log "${_SELF_}: We will sync the current active image to fallback."
   #<CheckActive>
   if grep "/var" /etc/fstab | grep -v "^/dev/${diskdev}" | grep -q 'primary'
   then
      echo "Located the active image: /dev/${diskdev}2( primary )"
      syncpart="primary"
      syncother="secondary"
      sda2active="(*)"
      if [ ${primstatus} -ne 0 ] # Cross-check
      then
         log "${_SELF_}:Sorry, Cannot contradict myself."
         log "      : syncpart($syncpart) is not mounted(?)."
         syncnexit ${ImgDiskNotSupported}
      fi
   elif grep "/var" /etc/fstab | grep -v "^/dev/${diskdev}" | grep -q 'secondary'
   then
      echo "Located the active image: /dev/${diskdev}3( secondary )"
      syncpart="secondary"
      syncother="primary"
      sda3active="(*)"
      if [ ${secstatus} -ne 0 ] # Cross-check
      then
         log "${_SELF_}:Sorry, Cannot contradict myself."
         log "      : syncpart($syncpart) is not mounted(?)."
         syncnexit ${ImgDiskNotSupported}
      fi
   else
       logerror "Booted image load cannot be determined, this is fatal! Aborting..."
       syncnexit ${CannotDetectActiveLoad}
   fi
   #</CheckActive>

   echo "///////////////////////////////////////////////////////////"
   echo "-----------------------------------------------------------"
   echo ".                                                         ."
   echo ".        Root    Root                                     ."
   echo ". swap   ImgPrim ImgSec   unisphere   more ...      var   ."
   echo ".  |       |      |         /  \                   /  \   ."
   echo ". \ /     \ /    \ /       /    \                 /    \  ."
   echo ".  |       |      |      Prim   Sec             Prim  Sec ."
   echo ". ${diskdev}1   ${diskdev}2    ${diskdev}3     ${diskdev}5        ...        ${diskdev}15    ."
   echo ".        ${sda2active}        ${sda3active}                                      ."
   echo ".                                                         ."
   echo "-----------------------------------------------------------"
   echo ".(*) on the ${diskdev} line shows active root.                   ."
   echo "///////////////////////////////////////////////////////////"
   echo  

   echo "Disk Map"
   echo "///////////////////////////////////////////////////////////"
   echo "-----------------------------------------------------------"
   echo ".  partition          mount      %used                     "
   if [ "$product" = "HiPath8000" ]
   then
   echo ".  /dev/${diskdev}2          root       ${dfsda[0]}"
   echo ".  /dev/${diskdev}3          root       ${dfsda[1]}"
   echo ".  /dev/${diskdev}5          unisphere  ${dfsda[2]}"
   echo ".  /dev/${diskdev}6          global     ${dfsda[3]}"
   echo ".  /dev/${diskdev}7          log        ${dfsda[4]}"
   echo ".  /dev/${diskdev}8          tmp        ${dfsda[5]}"
   echo ".  /dev/${diskdev}9          home       ${dfsda[6]}"
   echo ".  /dev/${diskdev}10         software   ${dfsda[7]}"
   echo ".  /dev/${diskdev}11         cdr        ${dfsda[8]}"
   echo ".  /dev/${diskdev}12         opt        ${dfsda[9]}"
   echo ".  /dev/${diskdev}13         tpa        ${dfsda[10]}"
   echo ".  /dev/${diskdev}14         enterprise ${dfsda[11]}"
   echo ".  /dev/${diskdev}15         var        ${dfsda[12]}"
   else
   echo ".  /dev/${diskdev}2          root       ${dfsda[0]}"
   echo ".  /dev/${diskdev}3          root       ${dfsda[1]}"
   echo ".  /dev/${diskdev}5          opt        ${dfsda[2]}"
   echo ".  /dev/${diskdev}6          db         ${dfsda[3]}"
   echo ".  /dev/${diskdev}7          var        ${dfsda[4]}"
   echo ".  /dev/${diskdev}8          tmp        ${dfsda[5]}"
   echo ".  /dev/${diskdev}9          software   ${dfsda[6]}"
   fi
   
   echo "-----------------------------------------------------------"
   echo "///////////////////////////////////////////////////////////"
}

# -------------------------------------------------------
# function: chkallusg
# args    :  none
# description: 
#   makes sure free space is available in every partition.
# -------------------------------------------------------
chkallusg( ) {
   if [ "$product" = "HiPath8000" ]
   then
      chkusg var        $syncpart $syncother  "all"
      chkusg home       $syncpart $syncother  "all"
      chkusg cdr        $syncpart $syncother  "structure"
      chkusg log        $syncpart $syncother  "structure"
      chkusg opt        $syncpart $syncother  "all"
      chkusg tpa        $syncpart $syncother  "structure"
      chkusg enterprise $syncpart $syncother  "all"
      chkusg software   $syncpart $syncother  "structure"
      chkusg tmp        $syncpart $syncother  "structure"
      chkusg global     $syncpart $syncother  "all"
      chkusg unisphere  $syncpart $syncother  "all"
   else
      if [ "$product" = "OpenScape" ]
      then

      chkusg var        $syncpart $syncother  "all"
      chkusg db         $syncpart $syncother  "all"
      chkusg opt        $syncpart $syncother  "all"
      chkusg software   $syncpart $syncother  "structure"
      chkusg tmp        $syncpart $syncother  "structure"

      else

      echo "[${_SELF_}] Unsupported product type."
      syncnexit $UnsupportedProduct 

      fi
   fi
}

# -------------------------------------------------------
# function: syncallimg
# args    :  none
# description: 
#   syncs all partitions.
# -------------------------------------------------------
syncallimg( ) {
   if [ "$product" = "HiPath8000" ]
   then
      syncimg var        $syncpart $syncother  "all"
      syncimg home       $syncpart $syncother  "all"
      syncimg cdr        $syncpart $syncother  "structure"
      syncimg log        $syncpart $syncother  "structure"
      syncimg opt        $syncpart $syncother  "all"
      syncimg tpa        $syncpart $syncother  "structure"
      syncimg enterprise $syncpart $syncother  "all"
      syncimg software   $syncpart $syncother  "structure"
      syncimg tmp        $syncpart $syncother  "structure"
      syncimg global     $syncpart $syncother  "all"
      syncimg unisphere  $syncpart $syncother  "all"
   else
      if [ "$product" = "OpenScape" ]
      then

      syncimg var        $syncpart $syncother  "all"
      syncimg db         $syncpart $syncother  "all"
      syncimg opt        $syncpart $syncother  "all"
      syncimg software   $syncpart $syncother  "structure"
      syncimg tmp        $syncpart $syncother  "structure"

      else

      echo "[${_SELF_}] Unsupported product type."
      syncnexit $UnsupportedProduct 

      fi
   fi
}

# -------------------------------------------------------
# function: cleanfallback
# args    :  none
# description: 
#   cleans fallback partitions.
# -------------------------------------------------------
cleanfallback( ) {
   #<CheckSysInfo>
   checksys
   if [ "$syncpart" = "" ]
   then
      fsyncpart
   fi
   if [ "$syncpart" = "" -o "$syncother" = "" ]
   then
      log "Sorry, could not determine information on fallback!."
      exit $CleanFallbackFailure
   fi
   #</CheckSysInfo>
   chkwithuser
   #<PreserveGrub>
      rm -rf /software/fbboot
      mkdir -p /software/fbboot
      cp -R -p /img/rootimg/boot /software/fbboot
      if [ $? -ne 0 ]
      then
         log "Sorry, cannot backup boot of fallback."
         exit $CleanFallbackFailure
      fi
   #</PreserveGrub>
   cleanimg root        
   #<RestoreGrub>
   if [ -d /software/fbboot/boot ]
   then
      rm -rf /img/rootimg/boot
      cp -R -p /software/fbboot/boot /img/rootimg/boot
      rm -rf /software/fbboot
   fi
   #</RestoreGrub>
   if [ "$product" = "HiPath8000" ]
   then
      cleanimg var        $syncpart $syncother  
      cleanimg home       $syncpart $syncother  
      cleanimg cdr        $syncpart $syncother  
      cleanimg log        $syncpart $syncother  
      cleanimg opt        $syncpart $syncother  
      cleanimg tpa        $syncpart $syncother  
      cleanimg enterprise $syncpart $syncother  
      cleanimg software   $syncpart $syncother  
      cleanimg tmp        $syncpart $syncother  
      cleanimg global     $syncpart $syncother  
      cleanimg unisphere  $syncpart $syncother 
   else
      if [ "$product" = "OpenScape" ]
      then

      cleanimg var        $syncpart $syncother  
      cleanimg db         $syncpart $syncother  
      cleanimg opt        $syncpart $syncother  
      cleanimg software   $syncpart $syncother  
      cleanimg tmp        $syncpart $syncother  

      fi
   fi
   export QUICKRESET8k="true"
   $ACTIVATE8k -reset
   sync
}

# -------------------------------------------------------
# function: fixlicense
# args    :  none
# description: 
#   fix license after syncs all partitions.
# -------------------------------------------------------
fixlicense( ) {
   cd /img/optimg/${syncother}/unisphere/srx3000/cla 2>/dev/null
   if [ $? -eq 0 ]
   then
      licensecount=$(find /opt/unisphere/srx3000/cla/license/ -type f ! \( -name gpcf\* -o -name alf\* \)| wc -l)
      if "$OSV_VERSION" --major compare sys lt V8 || [ $licensecount -gt 0 ];
      then
         echo "[*] Adjusting license information."
         rm -rf data/* mirror/*
         cp license/* import/  2>/dev/null
      else
         echo "[*] Making sure license information is integral."
         {
         synccla=false
         syncattempt=0
         while [ "$synccla" = "false" ]
         do
            synccla=true
            SYNCDATE=/opt/unisphere/srx3000/cla/syncdate
            touch $SYNCDATE
            usleep 10000
            synccla=true
            rsync -cavz --whole-file /img/optimg/${syncpart}/unisphere/srx3000/cla/ . 
            for claidx in $(find  /img/optimg/${syncpart}/unisphere/srx3000/cla -cnewer $SYNCDATE)
            do 
               claotheridx="$(echo $claidx | sed -e \"s/optimg\/${syncpart}/optimg\/${syncother}/g\")"
               curmd5="$(md5sum $claidx 2>/dev/null | awk '{ print $1 }')"
               fbmd5="$(md5sum $claotheridx | awk '{ print $1 }')"
               if [ "$curmd5" != "$fbmd5" ]
               then
                  synccla=false
                  usleep 10000
                  break;
               fi
            done
            rm -f $SYNCDATE
            syncattempt=$[syncattempt+1]
            if [ "$syncattempt" -gt 128 ] 
            then
               echo "[${_SELF_}]: Could not matchup cla data. Tried my best."
               break;
            fi
         done
         } 1>>$LOGFILE 2>&1
      fi
   fi
}

# -------------------------------------------------------
# function: setmeup
# args    :  none
# description: 
#   pretty space formatter.
# -------------------------------------------------------
setmeup( ) {
   varvaluetmp="$(echo ${1}| sed -e 's/ /!/g')"
   varvaluetmp=$1
   length=${#2}
   varlength=$3
   length=${#varvaluetmp}
   if [ $length -ge 0 -a $length -lt $varlength ]
   then
      spaces=$(expr $varlength - $length)
      while [ $spaces -gt 0 ]
      do
         varvaluetmp="${varvaluetmp}!"
         spaces=$(expr $spaces - 1)
      done
   fi
   cfgvarres="$varvaluetmp"
}

# -------------------------------------------------------
# function: displayprogress
# args    :  none
# description:
#   checks progress of sync8k. 
# -------------------------------------------------------
displayprogress( ) {
   rm -f /log/sync8k.out* 
   #<CheckRemote>
      if [ "$testbed" = "cluster" ]
      then
         if [ "$QuietSync8k" = "false" ]
         then
            if [ "$mynode" = "$primhost" ]
            then
               ssh $sechost "                           \
                      /unisphere/srx3000/srx/bin/${_SELF_} \
                      -quiet -progress" 1>/log/sync8k.out.partner 2>/dev/null
               status=$?
            else
               ssh $primhost "                          \
                      /unisphere/srx3000/srx/bin/${_SELF_} \
                      -quiet -progress" 1>/log/sync8k.out.partner 2>/dev/null
               status=$?
            fi
            if [ $status -ne 0 ]
            then
               log "${_SELF_}:Could not initiate sync8k."
               exit $SyncInitiationFailure
            fi
            
         fi
      fi 
   #</CheckRemote>
   #<CheckActive>
      # Cannot use detect_active_image in here, there is a sync in progress
      # Use heuristic on fstab
      if grep "/var" /etc/fstab | grep -v "^/dev/${diskdev}" | grep -q 'primary'
      then
         syncpart="primary"
         syncother="secondary"
      elif grep "/var" /etc/fstab | grep -v "^/dev/${diskdev}" | grep -q 'secondary'
      then
         syncpart="secondary"
         syncother="primary"
      else
          logerror "Booted image load cannot be determined, this is fatal! Aborting..."
          syncnexit ${CannotDetectActiveLoad}
      fi
   #</CheckActive>
   lockfile -l 4 /lock/sync8k.usg

   nsync=$(ps -ef f | grep ${_SELF_} |                                              \
          egrep -v "\-progress|\-status|\-live|\-r|\-h|vi|less|more|cat|lock" | \
          grep -v grep | wc -l)

   if [ ! -f /lock/sync8k.dmap ]
   then
      if [ "$nsync" -eq 0 ]
      then
         log "${_SELF_}:No sync is in progress."
      else
         log "${_SELF_}: sync is not yet fully active."
      fi
      rm -f /lock/sync8k.usg
      return
   fi

   if [ ! -f /lock/sync8k.fs ]
   then
      if [ "$nsync" -eq 0 ]
      then
         log "${_SELF_}:No sync is in progress."
      else
         log "${_SELF_}: sync is not yet fully active."
      fi
      rm -f /lock/sync8k.usg
      return
   fi

   nextpart="$(cat /lock/sync8k.fs 2>/dev/null)"
   if [ "$nextpart" = "" -o "$nextpart" = "db" ]
   then
      if [ "$nextpart" = "" ]
      then
         percent=0
      else
         percent=100
      fi
   else
      totalmapusg="$(cat /lock/sync8k.dmap | grep "^total" |  awk -F':' '{ print $2 }')"
      totalsynusg=0
      percent=0
      while read nextnmap
      do
        nextmappart="$(echo $nextnmap | awk -F':' '{ print $1 }')"     
        nextmapusg="$(echo $nextnmap | awk -F':' '{ print $2 }')"     
        if [ "$nextmappart" = "active"   -o \
             "$nextmappart" = "fallback" -o \
             "$nextmappart" = "total" ]
        then
           break;
        fi
        if [ "$nextmappart" = "root" ]
        then
           dusyncpart=$(du -k -s -x /img/${nextmappart}img 2>/dev/null | awk '{ print $1 }')
           totalsynusg=$(expr $dusyncpart + $totalsynusg)
        else
           dusyncpart=$(du -k -s -x /img/${nextmappart}img/${syncother} 2>/dev/null | awk '{ print $1 }')
           totalsynusg=$(expr $dusyncpart + $totalsynusg)
        fi
        if [ "$totalsynusg" -gt "$totalmapusg" ]
        then
           totalsynusg=$totalmapusg
        fi
        percent=$(expr $totalsynusg \* 100 / $totalmapusg)
        if [ "$nextmappart" = "$nextpart" ]
        then
           break;
        fi
      done < /lock/sync8k.dmap 
   fi
   if [ "$XLOGFILE" = "" ]
   then
      if [ "$LiveUpdate8k" = "true" ]
      then
         echo "/////////////////////////////////////////////"
         echo "${_SELF_}: Hit <ctrl+c> to stop live montioring."
         echo "/////////////////////////////////////////////"
      fi
      echo "${_SELF_}: $(uname -n) : ${percent}% complete."
   else
      echo "${_SELF_}: $(uname -n) : ${percent}% complete." > $XLOGFILE
   fi
   if [ -f /log/sync8k.out.partner -a "$QuietSync8k" = "false" ]
   then
      if [ "$XLOGFILE" = "" ]
      then
         cat /log/sync8k.out.partner 2>/dev/null
      else
         cat /log/sync8k.out.partner >> $XLOGFILE
      fi
   fi
   rm -f /lock/sync8k.usg
}

# -------------------------------------------------------
# function: checksys
# args    :  none
# description:
#   checks all critical errors.
# -------------------------------------------------------
checksys( ) {
   if [ $USER -ne 0 ]
   then
       echo "[${_SELF_}] You must be root to run this script with options [${ARGS}]."
       syncnexit $UidMisMatch
   fi
   rpm -q rsync 1>/dev/null
   if [ $? -ne 0 ]
   then
       log "rsync package not found.Check if you have the latest mops."
       syncnexit $RsyncNotFound
   fi

    #<CheckActive>
    if grep "/var" /etc/fstab | grep -v "^/dev/${diskdev}" | grep -q 'primary'
    then
        primstatus=0
        secstatus=1
    elif grep "/var" /etc/fstab | grep -v "^/dev/${diskdev}" | grep -q 'secondary'
    then
        primstatus=1
        secstatus=0
    else
        logerror "Active image load cannot be determined, this is fatal! Aborting..."
        syncnexit ${CannotDetectActiveLoad}
    fi
    #</CheckActive>

    if [ $primstatus -ne 0 -a $secstatus -ne 0 ]
    then
        log "Looks like you are on non imaged disk."
        log "This is not supported. Good luck."
        syncnexit ${ImgDiskNotSupported}
    fi
    if  [ $primstatus -eq 0 -a $secstatus -eq 0 ]
    then
        log "Look, you have both the active and fallback partitions mounted."
        log "This is strange.Cannot proceed with such a configuration."
        syncnexit ${StrangeMountPoints}
    fi

   #########################################################################
   # BUG: The /img/rootimg folder is always mounted and the only reason this
   # is not constantly aborting the script, is the trailing '/' in the grep.
   # Mount command output does not print trailing slashes in mount points. So
   # the code is definitelly buggy and I cannot understand why it's here...
   mount | grep -q "/img/rootimg/"
   if [ $? -eq 0 ]
   then
      log "Looks like you have something mounted on fallback image(/img/rootimg)."
      syncnexit $SomethingMountedOnFallback
   fi
   #########################################################################

   ps -eo pid,command > /tmp/ps.commands
   nsync="$(cat /tmp/ps.commands | \
           egrep "${_SELF_}[ \t]*$|${_SELF_}[ \t]*\-quiet[ \t]*$" | \
           egrep -v "cat|vi|ps|less|more|egrep|grep|ssh" | \
           awk '{ print $1 }' | \
           egrep -v "${MYID}" | \
           wc -l)"
   nactv="$(cat /tmp/ps.commands | \
           egrep "activate8k[ \t]*$|activate8k[ \t]*\-quiet[ \t]*$" | \
           egrep -v "cat|vi|ps|less|more|egrep|grep|ssh" | \
           awk '{ print $1 }' | \
           egrep -v "${MYID}" | \
           wc -l)"
   {
      cat /tmp/ps.commands | egrep "${_SELF_}|activate8k" 
   } >> $LOGFILE
   rm -f /tmp/ps.commands

   if [ $nactv -gt 0 ]
   then
      log "Looks like an instance of activate8k is running."
      ps -ef f | grep activate8k 1>>$LOGFILE 2>&1
      exit ${Activate8kAlreadyRunning}
   fi

   if [ $nsync -gt 0 ]
   then
      syncstate=nosync
      if [ -f /lock/sync8k.lock ]
      then
         cat /lock/sync8k.lock 2>/dev/null | egrep "^State" | egrep -q "progress|initiated"
         if [ $? -eq 0 ]
         then
            syncstate=progress
         fi
      fi
      if [ "X${syncstate}X" = "XprogressX" ]
      then
         log "Looks like a ${_SELF_} is already running."
         ps -ef f | grep ${_SELF_} 1>>$LOGFILE 2>&1
         exit ${Sync8kAlreadyRunning}
      fi
   fi
}

# -------------------------------------------------------
# function: query
# args    :  none
# description:
#   query the status of the current images on the disk.
# -------------------------------------------------------
query( ) {

   tmpMntPts=$([ -h /etc/mtab ] && findmnt --fstab --evaluate || mount)
   if ! egrep -q '/img/.*(primary|secondary)' <<< "$tmpMntPts"; then
      # no primary or fallback loads (e.g. SIS installation)
      log "Active:primary, Fallback:none"
      return
   fi

   if [ "x${product}x" = "xHiPath8000x" ]
   then

      # Check the loads existence by checking the /opt/SMAW directory existence? Heuristic.
      for i in primary secondary; do 
         eval ${i}Flag=$([ -d "/img/optimg/$i/SMAW/" ] && echo 1 || echo 0)
      done

      # Get the versions from the primary load
      if [ $primaryFlag -eq 1 ]
      then
         # Get the load versions first
         if get_load_buildid 'primary'
         then
             primloadversion="${_LOADVERSION_}"
         else
             primloadversion="None"
         fi

         # Get the full patchset version
         if get_load_fullpsversion 'primary'
         then
             primversion="${_LOADFULLPSVERSION_}"
         else
             primversion="None"
         fi
      fi

      # Get the versions from the secondary load
      if [ $secondaryFlag -eq 1 ]
      then
         # Get the load versions first
         if get_load_buildid 'secondary'
         then
             secloadversion="${_LOADVERSION_}"
         else
             secloadversion="None"
         fi

         # Get the full patchset version
         if get_load_fullpsversion 'secondary'
         then
             secversion="${_LOADFULLPSVERSION_}"
         else
             secversion="None"
         fi
      fi
      
      # Convert to Fit4More
      if [ "$Fit4More" = "true" ]
      then
         if [ -z "$primloadversion" ]
         then
            primversion="None"
         elif "$OSV_VERSION" compare "$primloadversion" lt V7
         then
            baseprimrev=$(echo $primloadversion | awk -F'.' '{ printf "%s%s%d", $1,"R",$2 }')
            baseprimstr=$(echo $primversion | awk -F '-' '{ print $3 }')
            baseps=$(echo $baseprimstr | awk -F'E' '{ printf "%d", $1 }')
            baseeps=$(echo $baseprimstr | awk -F'E' '{ printf "%d", $2 }')
            primversion="${baseprimrev}.${baseps}.${baseeps}"
         else
            if convert_to_fit4more 'primary'
            then
                primversion=${_LOADFIT4MOREPSVERSION_}
            else
                primversion="None"
            fi
         fi

         if [ -z "$secloadversion" ]
         then
            secversion="None"
         elif "$OSV_VERSION" compare "$secloadversion" lt V7
         then
            basesecrev=$(echo $secloadversion | awk -F'.' '{ printf "%s%s%d", $1,"R",$2 }')
            basesecstr=$(echo $secversion | awk -F '-' '{ print $3 }')
            baseps=$(echo $basesecstr | awk -F'E' '{ printf "%d", $1 }')
            baseeps=$(echo $basesecstr | awk -F'E' '{ printf "%d", $2 }')
            secversion="${basesecrev}.${baseps}.${baseeps}"
         else
            if convert_to_fit4more 'secondary'
            then
                secversion=${_LOADFIT4MOREPSVERSION_}
            else
                secversion="None"
            fi
         fi
      fi # if [ "$Fit4More" = "true" ]

   else # if [ "x${product}x" = "xHiPath8000x" ]

      primloadversion="OpenScape$component-Primary"
      secloadversion="OpenScape$component-Secondary"
      cat /etc/fstab | grep "/var" | grep -v "^/dev/${diskdev}" | grep -q primary
      if [ $? -eq 0 ]
      then
         primproduct="$(cat /etc/hiq8000/node.cfg| grep product_type | awk -F':' '{ print $2 }' | sed -e 's/ //g')"
         secproduct="$(cat  /img/rootimg/etc/hiq8000/node.cfg 2>/dev/null| grep product_type | awk -F':' '{ print $2 }' | sed -e 's/ //g')"
         primbuild="$(cat   /etc/hiq8000/node.cfg| grep srx_build_id | awk -F':' '{ print $2 }' | sed -e 's/ //g')"
         secbuild="$(cat    /img/rootimg/etc/hiq8000/node.cfg 2>/dev/null| grep srx_build_id | awk -F':' '{ print $2 }' | sed -e 's/ //g')"
      else
         primproduct="$(cat /img/rootimg/etc/hiq8000/node.cfg 2>/dev/null| grep product_type | awk -F':' '{ print $2 }' | sed -e 's/ //g')"
         secproduct="$(cat  /etc/hiq8000/node.cfg| grep product_type | awk -F':' '{ print $2 }' | sed -e 's/ //g')"
         primbuild="$(cat   /img/rootimg/etc/hiq8000/node.cfg 2>/dev/null| grep srx_build_id | awk -F':' '{ print $2 }' | sed -e 's/ //g')"
         secbuild="$(cat    /etc/hiq8000/node.cfg| grep srx_build_id | awk -F':' '{ print $2 }' | sed -e 's/ //g')"
      fi
      primproduct=${primproduct:-None}
      secproduct=${secproduct:-None}
      primbuild=${primbuild:-None}
      secbuild=${secbuild:-None}
      primversion="${primproduct}${component}-${primbuild}-primary"
      secversion="${secproduct}${component}-${secbuild}-secondary"

   fi # if [ "x${product}x" = "xHiPath8000x" ]

   if [ "$Fit4More" = "true" ]
   then
       baseprimrev=$(echo $primloadversion | awk -F'.' '{ printf "%s%s%d", $1,"R",$2 }')
       basesecrev=$(echo $secloadversion | awk -F'.' '{ printf "%s%s%d", $1,"R",$2 }')
       primversion=${primversion:-"$baseprimrev.0.0"}
       secversion=${secversion:-"$basesecrev.0.0"}
       if [ "$primversion" = "R0.0.0" ]
       then
          primversion=""
       fi
       if [ "$secversion" = "R0.0.0" ]
       then
          secversion=""
       fi
   else
       primversion=${primversion:-$primloadversion}
       secversion=${secversion:-$secloadversion}
   fi

   #<CheckActive>
   if [ ${PRIMARYACTIVE} -eq 1 ]
   then
      syncpart="primary"
      syncother="secondary"
   elif [ ${SECONDARYACTIVE} -eq 1 ]
   then
      syncpart="secondary"
      syncother="primary"
   else
       logerror "Active image load cannot be determined, this is fatal! Aborting..."
       syncnexit ${CannotDetectActiveLoad}
   fi
   #</CheckActive>

   if [ "$queryopt" = "all" ]
   then
      local primversion_display=$(echo ${primversion}| sed 's/\.x86_64//g')
      local secversion_display=$(echo ${secversion} | sed 's/\.x86_64//g')
      
      log "Detected $disktype disk."
      log "////////////////////////////////////////////////////////////"
      log "------------------------------------------------------------"
      log "Detected Versions: "
      if [ "$syncpart" = "primary" ]
      then
         log "   Active   Version: ${syncpart}/${primversion_display}"
         log "   Fallback Version: ${syncother}/${secversion_display}"
      else
         log "   Active   Version: ${syncpart}/${secversion_display}"
         log "   Fallback Version: ${syncother}/${primversion_display}"
      fi
      log "------------------------------------------------------------"
      log "////////////////////////////////////////////////////////////"
      if [ -f /lock/sync8k.lock -a -f ${IMGDIR}/lock/sync8k.lock ]
      then
         diff -q /lock/sync8k.lock ${IMGDIR}/lock/sync8k.lock 1>/dev/null 2>&1
         if [ $? -eq 0 ]
         then
            cat /lock/sync8k.lock
         fi
      fi
   else
      log "Active:$syncpart, Fallback:$syncother"
   fi
}

# -------------------------------------------------------
# function: cwsync
# args    :  none
# description:
#   cluster wide sync. Set up of auto sync on both nodes.
# -------------------------------------------------------
cwsync( ) {
   if [ "$testbed" = "cluster" ]
   then
      log "${_SELF_}:Cluster detected. Will run ${_SELF_} on both nodes."
      nohup /unisphere/srx3000/srx/bin/${_SELF_} -quiet 1>>$LOGFILE 2>>$LOGFILE &
      if [ $? -ne 0 ]
      then
         log "${_SELF_}:Could not initate ${_SELF_} on $primhost."
         exit $SyncInitiationFailure
      fi
      if [ "$mynode" = "$primhost" ]
      then
         nohup ssh -n $sechost "                                      \
                         /unisphere/srx3000/srx/bin/${_SELF_}            \
                         -quiet 1>>$LOGFILE 2>>$LOGFILE               \
                      " &
      else
         nohup ssh -n $primhost "                                     \
                         /unisphere/srx3000/srx/bin/${_SELF_}            \
                         -quiet 1>>$LOGFILE 2>>$LOGFILE               \
                      " &
      fi
      if [ $? -ne 0 ]
      then
         log "${_SELF_}:Could not initate sync8k."
         exit $SyncInitiationFailure
      fi
   else   
      log "${_SELF_}:Simplex detected. Will run ${_SELF_} on current node."
      nohup /unisphere/srx3000/srx/bin/${_SELF_} -quiet 1>>$LOGFILE 2>>$LOGFILE &
   fi
}

# -------------------------------------------------------
# function: checkprim
# args    : none
# description:
#   Checks for primary node. Allow certain commands from
#   primary node only!.
# -------------------------------------------------------
checkprim( ) {
   if [ "$mynode" = "$sechost" -a "$QuietSync8k" = "false" ]
   then
      log "${_SELF_}: This ${_SELF_} command can be run from $primhost only!."
      exit $SyncInitiationFailure
   fi
}

# -------------------------------------------------------
# function: checkactivesync
# args    : none
# description:
#   Checks if active sync is running
# -------------------------------------------------------
checkactivesync( ) {
   state="$(cat /lock/sync8k.lock 2>/dev/null | grep "^State" | awk -F ':' '{ print $2 }' | sed -e 's/[ ]*//g')"
   if [ "$state" = "completed" -o "$state" = "initiated" ]
   then
      sleep 4
      ps -eo pid,command > /tmp/ps.commands
      nsync="$(cat /tmp/ps.commands | \
              egrep "${_SELF_}[ \t]*$|${_SELF_}[ \t]*\-quiet[ \t]*$" | \
              egrep -v "cat|vi|ps|less|more|egrep|grep|ssh" | \
              awk '{ print $1 }' | \
              wc -l)"
      rm -f /tmp/ps.commands
      if [ "$nsync" -gt 0 ]
      then
         sleep 16
      fi
   fi
}

## @fn detect_active_image()
## @brief Try to detect the active image on the hard disk and set the state
## variables.
## @details CAUTION: This functions should only be called in executions where
## the system is not currently syncing images. During sync you cannot read
## values from the fstab and GRUB configuration files.
## Not working options: -a, -r, -auto, -progress, -status
## Safe script options: All the query options -q,  -v, -d
## @param $1 the block device of the hard disk to check (e.g. sda).
detect_active_image( ) {
    local blockdev="${1}"
    #<CheckActive>
    get_active_load "${blockdev}"; get_active_load_exit_code=$?
    case ${get_active_load_exit_code} in
    0) PRIMARYACTIVE=1; SECONDARYACTIVE=0 ;;
    1) PRIMARYACTIVE=0; SECONDARYACTIVE=1 ;;
    *)
        logerror "FATAL: Cannot detect the active image load of block device [${diskdev}]"
        logwarning "Make sure you are not running the query options during a currently running syncing."
        syncnexit ${CannotDetectActiveLoad}
    ;;
    esac
    #</CheckActive>
}


### Main Logic

# Usage help
if [ ${#} -gt 0 -a "X${1}X" == "X-hX" ]
then
    usage
    syncnexit ${Success}
fi

# Check Product type
if [ "X${product}X" = "XX" ]
then
   rpm -qi 'UNSPbase' 1>/dev/null 2>&1
   if [ $? -eq 0 ]
   then
      product="HiPath8000"
   else
      echo "${_SELF_}: Failed to detect product in node.cfg."
      exit ${UnknownProductType}
   fi
fi
#<CheckSupportedTypes>
   if [ "X${product}X" != "XHiPath8000X" -a "X${product}X" != "XOpenScapeX" ]
   then
      echo "${_SELF_}: Failed to detect supported product in node.cfg."
      exit ${UnknownProductType}
   fi
#</CheckSupportedTypes>
if [ "X${product}X" = "XHiPath8000X" ]
then
   ACTIVATE8k=/unisphere/srx3000/srx/bin/activate8k
else
   ACTIVATE8k=/usr/bin/activate8k
fi

# Setup lock directory and log filename
mkdir -p /lock
if [ ! -w $LOGFILE ]
then
   LOGFILE=${LOGFILE}.${USER}
fi

###############################################################################
# OSV-3530
# Check the options that non-root users can use.
# ALLOWED OPTIONS:     [-h, -d, -q, -v]
# NOT ALLOWED OPTIONS: [-auto, -r, -quiet, -progress, -status, -a, -s, -live]
if [ $USER -ne 0 ]
then
    # If the allowed options are not provided then you should be root
    logdebug "Options provided in command line [${ARGS}]"

    if ! echo "${ARGS}" | egrep -q "\-h|\-v|\-d|\-q|\-q[ \t]*none"
    then
        echo "[${_SELF_}] You must be root to run this script with options [${ARGS}]."
        syncnexit ${UidMisMatch}
    else # Execute allowed options as non-root users with sudo
        logdebug "Allowed options for non-root user found in command line"

        # Sanitize command line options, as the sync8k_sudoers allows specific command lines
        # by picking up the first command line option only. Previous logic allowed the non-root
        # users to execute the script if they mixed NOT allowed and allowed options in their
        # command line
        sudo_args="$(echo "${ARGS}" | awk '{ print $1 }')"

        case "${sudo_args}" in
        '-d'|'-q'|'-v')
            if [ -f "/etc/polkit-1/rules.d/00-jitc.rules" ];
            then
               logdebug "Executing ${_SELF_} with options [${sudo_args}] using pkexec."
               # The query options need to read boot loader configuration only readable by root.
               exec pkexec "${_SELFDIR_}/${_SELF_}" "${sudo_args:--h}"
            else
               logdebug "Executing ${_SELF_} with options [${sudo_args}] using sudo."
               # The query options need to read boot loader configuration only readable by root.
               exec sudo "${_SELFDIR_}/${_SELF_}" "${sudo_args:--h}"
            fi
            ;;

        *) usage; syncnexit ${Success} ;;
        esac
    fi
fi
###############################################################################

# Check mount tab and propose to the user the fix, in case of error.
check_mount_tab
case $? in
1) logwarning "The /etc/mtab mount tab is not setup properly!! Please apply the recommendation above manually." ;;

2) logwarning "Your system requires a reboot, please plan it as soon as possible!
${_SELF_} operations may encounter problems if the reboot is not performed in order to populate properly the /etc/mtab" ;;

3)
    logerror "Cannot detect operating system type!! This is fatal cannot continue.
Please check the status of the RPM package 'sles-release' and the contents of the files:
/etc/SuSE-release
/etc/os-release
"
    exit ${UnsupportedProduct}
;;
esac

#<CheckCfgParms>
   testbed="$(/sbin/cfgread test_bed)"
   primhost="$(/sbin/cfgread node_1_name)"
   sechost="$(/sbin/cfgread node_2_name)"
   mynode=$(uname -n)
#</CheckCfgParms>

#<CheckHwAbstraction>
# Detect disk type
if ! get_block_device_of_rootfs
then
    logerror "Cannot detect the hard disk device of this system."
    exit ${InvalidDiskType}
fi
diskdev="${_OSVROOTFSBLKDEV_}"
if [[ ${diskdev} == sd[a-z] ]]
then
    disktype='scsi'
elif [[ ${diskdev} == hd[a-z] ]]
then
    disktype='ide'
else
    logerror "[*] Block device [${diskdev}] has unknown disk type."
    exit ${InvalidDiskType}
fi
#</CheckHwAbstraction>

#<ACPIvsNone>
   hwplatform="$(/sbin/cfgread hw_platform)"
   case "$hwplatform" in
      'RX200'|'x3550M3'|'RX200S7'|'x3550M4')
         ACPIOPTS=""
         ;;
      *)
         ACPIOPTS="acpi=ht"
         ;;
   esac
#</ACPIvsNone>

#<NonTraditionalCommands>
while [ "$#" -gt "0" ]
do
   case $1 in
      '-progress')
         #<CheckProgress>
            shift
            XLOGFILE=$1
            checkprim
            displayprogress
            exit $Success
         #</CheckProgress>
         ;;
      '-status')
         #<CheckStatus>
            checkactivesync
            shift
            lockfile -s 1 /lock/sync8k.usg
            if [ -f /lock/sync8k.lock ]
            then
               cat /lock/sync8k.lock
            else
               log "${_SELF_}: No ${_SELF_} is in progress."
            fi
            rm -f /lock/sync8k.usg
            exit $Success
         #</CheckStatus>
         ;;
      '-quiet')
         #<NonInteractiveMode>
            shift
            QuietSync8k=true
         #</NonInteractiveMode>
         ;;
      '-live')
         #<LiveUpdate>
            shift
            checkprim
            export LiveUpdate8k=true
            watch -n 4 "/unisphere/srx3000/srx/bin/${_SELF_} -progress" 
            exit $Success
         #</LiveUpdate>
         ;;
      '-auto')
         #<ClusterWideSync>
            log "${_SELF_}: auto option selected."
            shift
            Sync8kAuto=true
            checkprim
            ps -eo pid,command > /tmp/ps.commands
            nsync="$(cat /tmp/ps.commands | \
                    egrep "${_SELF_}[ \t]*$|${_SELF_}[ \t]*\-quiet[ \t]*$" | \
                    egrep -v "cat|vi|ps|less|more|egrep|grep|ssh" | \
                    awk '{ print $1 }' | \
                    egrep -v "${MYID}" | \
                    wc -l)"
            rm -f /tmp/ps.commands
            if [ $nsync -gt 0 ]
            then
               echo "${_SELF_}: Sorry an active sync is already in progress."
               exit $SyncInitiationFailure
            fi
            lockfile -s 1 /lock/sync8k.usg
            rm -f /lock/sync8k.fs
            rm -f /lock/sync8k.usg
            rm -f /lock/sync8k.lock
            if [ "$testbed" = "cluster" ]
            then
               if [ "$mynode" = "$primhost" ]
               then
                  ssh -o ConnectTimeout=8 $sechost "
                     rm -f /lock/sync8k.fs;
                     rm -f /lock/sync8k.usg;
                     rm -f /lock/sync8k.lock;
                  "
               else
                  ssh -o ConnectTimeout=8 $primhost "
                     rm -f /lock/sync8k.fs;
                     rm -f /lock/sync8k.usg;
                     rm -f /lock/sync8k.lock;
                  "
               fi
            fi
            cwsync
            lockfile -s 1 /lock/sync8k.usg
            #<InitializeStatus>
             {
                 #<CheckActive>
                 # Cannot use detect_active_image in here, there is a sync in progress
                 # Use heuristic on fstab
                 if grep "/var" /etc/fstab | grep -v "^/dev/${diskdev}" | grep -q 'primary'
                 then
                     syncpart="primary"
                 elif grep "/var" /etc/fstab | grep -v "^/dev/${diskdev}" | grep -q 'secondary'
                 then
                     syncpart="secondary"
                 else
                     logerror "Booted image load cannot be determined, this is fatal! Aborting..."
                     rm -f /lock/sync8k.usg
                     syncnexit ${CannotDetectActiveLoad}
                 fi
                 #</CheckActive>

                 startts="$(date -u)"
                 echo "Last ${_SELF_} : $startts"
                 echo "Note        : ${syncpart} was active during sync8k."
                 echo "State       : initiated"
             } > /lock/sync8k.lock
            #</InitializeStatus>
            >/lock/sync8k.dmap

            rm -f /lock/sync8k.usg
            exit ${Success}
         #</ClusterWideSync>
         ;;
      *)
         break
         ;;
   esac
done
#</NonTraditionalCommands>

while getopts a:hqdvrs: result
do
   case $result in
      'a')
         activate=$OPTARG
         if [ "$activate" = "primary" -o "$activate" = "secondary" ]
         then
            echo "Activate:Looks like a valid option."
         else
            echo "Activate:Does not look like a valid option."
            syncnexit $InvalidOption
         fi
         ;;
      's')
         syncpart=$OPTARG
         if [ "$syncpart" != "" ]
         then
            if [ "$syncpart" = "primary" -o "$syncpart" = "secondary" ]
            then
               echo "Sync:Looks like a valid option."
               if [ "$syncpart" = "primary" ]
               then
                  syncother="secondary"
               else
                  syncother="primary"
               fi
               cat /etc/fstab | grep "/var" | grep -v "^/dev/${diskdev}" | grep -q $syncpart
               if [ $? -ne 0 ]
               then
                     echo "Look, you are trying to sync from an fallback to active partition."
                     echo "Its like sitting on a branch and trying to chop it."
                     echo "This is not allowed. Good luck."
                     syncnexit $SelfChopFailure
               fi
            else
               echo "Sync:Does not look like a valid option."
               syncnexit $InvalidOption
            fi
         else
            echo "Sync:Does not look like a valid option."
            syncnexit $InvalidOption
         fi
         ;;
      'q')
         detect_active_image
         queryopt=$OPTARG
         query
         syncnexit $Success
         ;;
      'd')
         detect_active_image
         Fit4More=true
         queryopt="all"
         query
         syncnexit $Success
         ;;   
      'v')
         detect_active_image
         queryopt="all"
         query
         syncnexit $Success
         ;;
      'r')
         cleanfallback
         syncnexit $Success
         ;;
      'h')
         usage
         syncnexit $Success
         ;;
      *)
        echo "Unknown parameter."
        syncnexit $InvalidOption
        ;;
   esac
done

#<CheckSysInfo>
   checksys
   if [ "$syncpart" = "" ]
   then
     fsyncpart
   fi

   if [ "$syncpart" = "" -o "$syncother" = "" ]
   then
      log "Sorry, could not determine information on fallback!."
      exit $CleanFallbackFailure
   fi
   rm -f /opt/unisphere/srx3000/mmgr/backup/* /img/optimg/$syncother/unisphere/srx3000/mmgr/backup/*
#</CheckSysInfo>

chkwithuser
chkallusg
syncroot
fstab_setup
syncallimg
fixlicense
backupdb
setcompletion
if [ "X${activate}X" != "XX" ]
then
   activate
fi
#<ResetLoadInfo>
   export QUICKRESET8k="true"
    $ACTIVATE8k -f -h 1>/dev/null 2>&1
    if [ $? -eq 0 ]
    then
       $ACTIVATE8k -f -reset
    else
       $ACTIVATE8k -reset
    fi
#<ResetLoadInfo>
sync

