#!/bin/bash
#
#    Broadcom Proprietary and Confidential.
#    Copyright © 2005-2018 Broadcom.
#    All Rights Reserved.
#    The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
#
#    Description:
#
#	This post install script will be run after firmware 
#	download has been completed.
#
#
PATH=/bin:/usr/bin:/sbin:/usr/sbin
#
# Passed in version numbers
#
TO_MAJOR=$1
TO_MINOR=$2
TO_PATCH=$3

FROM_VER=`rpm -q fabos | cut -f 2 -d '-'`
FROM_MAJOR=`echo $FROM_VER|cut -d '.' -f 1`
FROM_MINOR=`echo $FROM_VER|cut -d '.' -f 2`
FROM_PATCH_STR=`echo $FROM_VER|cut -d '.' -f 3`
FROM_PATCH=${FROM_PATCH_STR:0:1}

#################################################################################
# Attention!                                            						# 
#																				#
# Please do not remove these lines in all future merges. 
#
# This define indicates	#
# that firmware version supports optimized BE trunk deskew value 				#
C4_BE_TRUNK_DESKEW_OPTIMIZED="Version Optimizes the C4 BE trunk deskew"
C3_C4_VC_MODE_IS_WEIGHT_BASED="Version sets the vc mode as weight based"

#Security Post Feature Tags
UID_CONVERSION="Version Supports UID Conversion"
INVALID_ACCOUNTS_REMOVAL="Version Supports Invalid Accounts Removal"
DEFAULT_ACCT_PASSWD_UPDATE="Version Supports Default Account Passwd Update"
FACTORY_REMOVAL_SUPPORTED="Version Supports Factory Account Removal"
FILE_PERMISSION_UPDATE="Version Supports File Permission Update"
PASSWD_HASH_SUPPORTED="Version Supports Passwd Hash Configuration"
ROOT_ACCESS_SUPPORTED="Version Supports Root Access Feature"
ACCESS_TIME_SUPPORTED="Version Supports Access Time feature"
CIPHER_KEYS_SUPPORTED="Version Supports Cipher Keys"
LDAP_DEFAULTCIPHER_UPDATE="Version Supports Default LDAP Ciphers"
PAM_CONF_SUPPORTED="Version Supports Pam Conf Update"
AUTHSECRET_CONVERSION_SUPPORTED="Version Supports Auth Secret Update"
RBAC_UPDATE_SUPPORTED="Version Supports RBAC Update"
RBAC_UPDATE_REQUIRED="MOF change mandates merge"
SSH_HOSTKEY_CONVERSION_REQUIRED="Convert ssh hostkeys from openssh to PEM format or viceversa"
SSHD_CONFIG_HANDLING_REQUIRED="UsePrivilegeSeparation, PrintLastlog and ServerKeyBits are not supported in Openssh"
SSH_CONFIG_FIPS_RELATED="MinPrime, ServerHostKeySize is not supported in 9.0"
SSK_REKEY_LIMIT_CONVERSION_REQUIRED="Version supports RekeyLimit from OpenSSH"
IPSEC_DISABLE_REQUIRED="IPSec is deprecated in FOS 9.0 and higher release"
MAINTENANCE_SUPPORT="Version supports Maintenance account"
LDAPS_SUPPORT="Version supports LDAPS protocol"
# 8.0.1 supports above features
# But doesn't contain above feature tags
# Workaround - Look for below string in postinstall 
# to detect it supports above features
TATOOINE_SUPPORT="passwdcfg.hash"
AUTH_SECRET_CONVERT_SUPPORT="auth_secretconvert"
BSN_SUPPORT_LINK_SUPPORTED="Version Supports BSL"
C4P_BCAST_MCAST_FILTER_SUPPORTED="version supports c4plus bcast and mcast filter"
C4P_INVALID_ARB_FILTER_SUPPORTED="version supports c4plus invalid arb filter"

MNT_POSTINST="/mnt/sbin/postinst" # This is the new firmware being downloaded
POSTINST="/sbin/postinst"		  # This is the current / running firmware
#################################################################################
DEBUG=0
if [ $DEBUG = 1 ]; then
	ECHO='echo -e'
else
	ECHO=:
fi


STS_ERR=255

$ECHO Requested version is ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH}
$ECHO Current version is ${FROM_MAJOR}.${FROM_MINOR}.${FROM_PATCH}

swbd=`sin | awk ' {print $2} ' | grep SWBD | sed 's@,@@'`
if [ $swbd == "SWBD178" ]; then
	CHECKSUM=`rpm -Vf --root /mnt /boot/zImage.tree.initrd | grep zImage.tree.initrd | grep "^.\{2\}5."`
	if [ "x" != "x${CHECKSUM}" ]; then
		echo "Linux checksum failure detected!!!\n"
		return $STS_ERR
	fi
	CHECKSUM=`rpm -Vf --root /mnt /tftpboot/extn-vmlinux.64 | grep extn-vmlinux.64 | grep "^.\{2\}5."`
	if [ "x" != "x${CHECKSUM}" ]; then
		echo "DP extn-vmlinux.64 checksum failure detected!!!\n"
		return $STS_ERR
	fi
	CHECKSUM=`rpm -Vf --root /mnt /tftpboot/fcext_se | grep fcext_se | grep "^.\{2\}5."`
	if [ "x" != "x${CHECKSUM}" ]; then
		echo "DP fcext_se checksum failure detected!!!\n"
		return $STS_ERR
	fi
	# check sda device file presence
	if [ ! -e /mnt/dev/sda1 ]; then
		echo "/mnt/dev/sda1 file missing!!!\n"
		return $STS_ERR
	fi
	if [ ! -e /mnt/dev/sda2 ]; then
		echo "/mnt/dev/sda2 file missing!!!\n"
		return $STS_ERR
	fi
fi

# if /mnt/proc is not present after fwdl something bad happened.
# TODO: Should we create it here

if [ ! -d /mnt/proc ]; then
	echo "ERROR: Proc FS is missing in secondary partition."
	exit $STS_ERR
fi

# untar ras man pages
# Unzip the rasman.tar on all platforms whose CF size is greater than 256MB.
# And remove the .gz files in the platform whose CF size is less than 256MB
# which were unzipped from rasman.tar by previous firmware.
swbd=`sin | awk ' {print $2} ' | grep SWBD | sed 's@,@@'`
total_cf=`df | awk ' NR==2 { print $2 } '`
# Defect 562160: Since CF size is compared, specify the minimum size to
# untar the rasman.tar -- 256MB * 1024 == 262144K
low_cf=262144
if [ $total_cf -gt $low_cf ]; then
	if [[ -e /mnt/fabos/man/cat7/rasman.tar ]]; then
		# Clean up the raslog man page dir before untar the new rasman.tar
		/bin/rm -f /mnt/fabos/man/cat7/*.gz 2>/dev/null
		tar -xpf /mnt/fabos/man/cat7/rasman.tar -C /mnt/fabos/man/cat7/ 2>/dev/null
		> /mnt/fabos/man/cat7/rasman.tar
		/bin/chown -R root:sys /mnt/fabos/man/cat7
	else 
		echo "rasman.tar does not exist."
	fi
else
	/bin/rm -f /mnt/fabos/man/cat7/*.gz 2>&1
fi


is_fwdl_arg() {

	#
	# Reads command line args passed to firmwaredownload
	# and checks if the required argument is specified
	#
	fwdl_proc_id=`/bin/ps -ef | /bin/awk '/[f]irmwaredownload /{print $2}'`
	for arg in $(/usr/bin/tr '\0' ' ' < /proc/${fwdl_proc_id}/cmdline)
	do
            case $arg in
            (-*$1*)
		return $STS_OK
		;;
            esac
        done
        return $STS_ERR
}

#Push Manufacturing key to SP
if [ -f '/fabos/libexec/spmPublicKeyUpdate' ] ; then
	/fabos/libexec/spmPublicKeyUpdate
fi
# Removing obsolete (4.2 and early) error log file in /mnt
#
cleanup_error_log()
{
if [ -f '/mnt/var/log/el_save.0.0' ] ; then
	/bin/rm -f /mnt/var/log/el_save.* 2>&1
	/bin/rm -f /var/log/el_save.* 2>&1
fi
if [ -f '/mnt/var/log/el_common.0' ] ; then
	/bin/rm -f /mnt/var/log/el_common.* 2>&1
	/bin/rm -f /var/log/el_common.* 2>&1
fi
}

#creating httpd folder to dump the core

# Recreate the trace dump file for the appropriate platforms.  These values must
# match those in the trace .c files.
trace_create_dump_file()
{
if [ -f '/mnt/fabos/cliexec/traceCreateDb' ] ;then
	/mnt/fabos/cliexec/traceCreateDb ${SWBD##SWBD} 2>/dev/null
fi
}

if [  -d /etc/fabos/mace/logger/stage ] ; then
	if [ -d /mnt/etc/fabos/mace/logger/stage ] ; then
		/bin/rm -rf /mnt/etc/fabos/mace/logger/stage
	fi
	cp -r /etc/fabos/mace/logger/stage /mnt/etc/fabos/mace/logger/stage
fi

#
#Copying sendmail to /mnt
#
cp /etc/mail/sendmail.cf /mnt/etc/mail/sendmail.cf

#
# Removing obsolete files in /mnt 
#
cleanup_error_log
if [ `uname -m` != "ppc64" ]; then
/mnt/bin/bash /mnt/sbin/fwclean -o -s
fi
#
# Workaround for missing secd issue.
#
if [ ! -f /mnt/fabos/libexec/secd ];then
	echo Creating secd
	/bin/touch /mnt/fabos/libexec/secd
fi

# Reestablish the links of the shared libraries
#
/usr/sbin/chroot /mnt /sbin/ldconfig 2>/dev/null
#

# Remove the persistent_NPIV_config file from both partitions
# if the platform do not support agd
#
if [ ! -e /etc/fabos/factory_ag.conf ] ; then
	/bin/rm -f /etc/fabos/persistent_NPIV_config
	/bin/rm -f /mnt/etc/fabos/persistent_NPIV_config
fi
#

# Ensure the module dependencies are correct, show undefined symbols
( /usr/sbin/chroot /mnt /sbin/depmod -e -F /boot/System.map ) 2>/dev/null

# handle the login PAM configuration files to be in sync with firmware version
handle_pam_conf() {

$ECHO "Handling PAM login configuration files"

CONF_DIR=/mnt/etc/pam.d
CONSOLE_CONF=$CONF_DIR/ttylogin
NET_CONF=$CONF_DIR/netlogin
SSH_CONF=$CONF_DIR/sshd

grep "pam_radius_auth.so" $NET_CONF > /dev/null 2>&1 
radius=$?

grep "pam_radius_auth.so" $NET_CONF | grep "optional" > /dev/null 2>&1
plus_local=$?

if [ $plus_local -eq 0 ]; then
	$ECHO "RADIUS + Local configuration"
	cp $CONF_DIR/login.radius-local $CONSOLE_CONF
	cp $CONF_DIR/login.radius-local $NET_CONF
	cp $CONF_DIR/sshd.radius-local $SSH_CONF
elif [ $radius -eq 0 ] && [ $plus_local -ne 0 ]; then
	$ECHO "RADIUS configuration"
	cp $CONF_DIR/login.radius-local $CONSOLE_CONF
	cp $CONF_DIR/login.radius $NET_CONF
	cp $CONF_DIR/sshd.radius $SSH_CONF
else
	$ECHO "Local configuration"
	cp $CONF_DIR/login.noradius $CONSOLE_CONF
	cp $CONF_DIR/login.noradius $NET_CONF
	cp $CONF_DIR/sshd.noradius $SSH_CONF
fi

#also copy the netlogin script. Otherwise, PDM overwrites the changes
#we made above.
cp /fabos/libexec/netlogincp /mnt/fabos/libexec/netlogincp

#With the PDM fix, the following two lines are no longer needed.
#cat /mnt/etc/fabos/sync.conf | /bin/sed -e 's%\(/etc/pam.d/[[:alpha:]]\{1,\}\)\+$%\1  /fabos/libexec/netlogincp%g'  > /mnt/etc/fabos/sync.conf.tmp
#mv /mnt/etc/fabos/sync.conf.tmp /mnt/etc/fabos/sync.conf

sync
}

#handle the files left in *.rpmsave state
copy_rpmsave() {
fname="$1"
$ECHO "Handling $1.rpmsave files"

if [ -f $fname.rpmsave ] && [ -f $fname ]; then
	mv $fname.rpmsave $fname
	sync
fi
}

# Defect 52841 & 56397 - Hot Code Load takes so long that neighbor Hello
# messages are not sent within the 80 seconds and switch
# gets segmented. This script starts a background task as part
# of firmware download that will refresh the Hello messages
# every two seconds up until the switch reboots or until
# a minute goes by (which ever comes first)

#
# swbd
#
# Retrieve the current system platform name, of the form "SWBDn", where n
# is cardinal number, assuming a sin/hinv input stream.
#
swbd() {
    /bin/sed -n -e 's/^.*\(SWBD[[:digit:]]\{1,\}\).\+$/\1/gp'
}

#
# cpid
#
# Retrieve the current Control Processor ID
#
cpid() {
    sed -n -e 's/^Control.\+No: \([[:digit:]]\{1,\}\)$/\1/gp'
}

# Determine the system platform identifier.
SWBD=$(sin | swbd 2> /dev/null)
CPID=$(sin | cpid 2> /dev/null)


#Check for FIPS mode
checkFipsMode() {
    	# "config get" for fips mode returns value only if called from
   	# default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
    	# revert it back to its original value after "config get"
    	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
    	FABOS_SWITCHNO=0
    	retVal1=`/fabos/cliexec/config get fips.mode 2`
    	retVal2=`/fabos/cliexec/config get fips.simulate 2`
    	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
	retVal=0

	if [ $retVal1 -eq 1 ]; then
		return $retVal1
	elif [ ! -z $retVal2 ];  then
		if [ $retVal2 -eq 1 ];  then
			return $retVal2
		fi
	else 
		return $retVal
	fi
}

#
# ag_mode_enabled
#
# Check whether the switch is currently in AG mode
#
# JOE
ag_mode_enabled() {
        ag_mode=$(correcthost /fabos/link_bin/switchshow | grep -c "Access Gateway Mode")
        return $ag_mode

}



#Check for FORCE FIPS mode
checkFipsForceMode() {
    	# "config get" for fips mode returns value only if called from
   	# default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
    	# revert it back to its original value after "config get"
    	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
    	FABOS_SWITCHNO=0
    	retVal1=`/fabos/cliexec/config get fips.promallow 2`
	retVal2=`/sbin/bootenv AutoLoadTimeout 2>/dev/null`
	retVal3=`/sbin/bootenv bootdelay 2>/dev/null`

    	fipsmode=`/fabos/cliexec/config get fips.mode 2`

    	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

	bootprom=0
	if [ $retVal1 -eq 1 ] || [ $retVal2 -ne 0 ] || [ $retVal3 -ne 0 ]; then
		bootprom=1	
	fi

	rootaccount=`/bin/cat /etc/shadow | /bin/grep "^root:" | /usr/bin/cut -f8 -d ":"`	

	forcefips=0
	if [ $fipsmode -eq 1 ] && [ $bootprom -eq 1 ] && [ "$rootaccount" != "0" ]; then
		forcefips=1
	fi

	return $forcefips
}

otherhost(){
	case ${SWBD##SWBD} in
	'165' | '166' | '179' | '180')
	    printf 127.3.1.$((2 - CPID % 2))
	    ;;
	*)
	    printf 10.0.0.$((6 - CPID % 2))
	    ;;
	esac
}

correcthost() {
    # Check if active again in case active CP reboots in middle of postinst
    isActive
    if [ $ACTIVECP ]; then
	"$@"
    else
	/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 CURRENT_AD=0 "$@"
    fi
}

#
# Helper functions
#

ha_role() {
	/fabos/cliexec/hashow -l | /bin/grep ACTIVE > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		printf "ACTIVE"
	else
		printf "STANDBY"
	fi
}
isActive() {
	if [ $(ha_role) == "ACTIVE" ]; then
		ACTIVECP=1
		STANDBYCP=0
	else
		STANDBYCP=1
	fi
}

isActive

ha_state() {
    sync=`/fabos/cliexec/hashow | sed -n -e 's/^.\+\(State sync\).\+$/\1/gp'`

    if [ "$sync" != "State sync" ]; then
        printf "NOSYNC"
    else
        printf "SYNC"
    fi
}

NULL=/dev/null

ffdc_config(){
        RAS_FFDC_FILE=/etc/fabos/ras_ffdc.conf
        RAS_FFDC_FILE_MNT=/mnt/etc/fabos/ras_ffdc.conf
        slot_based=`/fabos/bin/slotshow | grep "Not supported on this platform"`

        if [ "$slot_based" == "" ]; then
               if [ $STANDBYCP -eq 1 ]; then
                       if [ -f $RAS_FFDC_FILE_MNT ]; then
				rasConfig=`correcthost_to_curr_vfid cat $RAS_FFDC_FILE | grep ENABLE| /usr/bin/awk  '{print $NF}'`
                                if [ "$rasConfig" -eq 0 ]; then
                                       sed '/%ENABLE/c\
%ENABLE 0' $RAS_FFDC_FILE_MNT  > temp && mv temp $RAS_FFDC_FILE_MNT
					/bin/cp $RAS_FFDC_FILE_MNT  $RAS_FFDC_FILE
                                        /bin/rcp $RAS_FFDC_FILE root@$(otherhost):$RAS_FFDC_FILE_MNT
                                       /bin/rcp $RAS_FFDC_FILE root@$(otherhost):$RAS_FFDC_FILE

                                fi
                        fi
                fi
        else
                if [ -f $RAS_FFDC_FILE_MNT ]; then
                         rasConfig=`cat $RAS_FFDC_FILE  | grep ENABLE | /usr/bin/awk  '{print $NF}'`
                        if [ "$rasConfig" -eq 0 ]; then
                                  sed '/%ENABLE/c \
%ENABLE 0' $RAS_FFDC_FILE_MNT  > temp && mv temp $RAS_FFDC_FILE_MNT
                        fi
                fi
        fi
}

IDENTIFY="cat /proc/ide/ide0/hda/identify"
MODEL="cat /proc/ide/hda/model"
INSMOD="/sbin/insmod /mnt/fabos/modules/wd.ko force=1"
checkId="3334 312d 3032 3330"

RSHCMD="/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CURRENT_AD=0"
RIDENTIFY="$RSHCMD $IDENTIFY"
RMODEL="$RSHCMD $MODEL"
RINSMOD="$RSHCMD $INSMOD"
RCPCMD="/bin/rcp /mnt/fabos/modules/wd.ko root@$(otherhost):/mnt/fabos/modules"

if [ -f /mnt/fabos/modules/wd.ko ];then
    FLASH=$($MODEL | grep -E "1GB|2GB|512MB" | grep -c "3625")
    if [ $FLASH -ne 0 ];then
        flash_verified=$($IDENTIFY | awk '{ if (NR == 3) { printf "%s ", $0 } if (NR == 4) { print $0 } }' | grep -c "$checkId")
        if [ $flash_verified -eq 0 ];then
            /sbin/insmod /mnt/fabos/modules/wd.ko force=1
        fi
    fi
    if [ $STANDBYCP -eq 1 ] && [ $(ha_state) == "SYNC" ] ; then
        ACTIVEFLASH=$($RMODEL | grep -E "1GB|2GB|512MB" | grep -c 3625)
        if [ $ACTIVEFLASH -ne 0 ];then
        	flash_verified=$($RIDENTIFY | awk '{ if (NR == 3) { printf "%s ", $0 } if (NR == 4) { print $0 } }' | grep -c "$checkId")
			if [ $flash_verified -eq 0 ];then
				($RCPCMD)
				($RINSMOD) > /dev/null 2>&1
			fi
		fi
	fi
fi

STS_OK=0
STS_ERR=255
CONTEXTS=""

CHASSISCMD=""
cliidx=0
export PATH=/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/link_rbin:/fabos/factory:/fabos/xtool
export VFROLEMAP=-1:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0
export CHASSIS_ROLEID=0
if /fabos/bin/fosconfig --show | grep "Virtual Fabric" | grep enabled > /dev/null 2>&1 ; then VF_ENABLED=$STS_ERR; else VF_ENABLED=$STS_OK; fi
if /fabos/bin/switchshow | grep "Analytics" > /dev/null 2>&1 ; then ANALYTICS_ENABLED=$STS_OK; else ANALYTICS_ENABLED=$STS_ERR; fi
ANALYTICS_FLAG=`/fabos/bin/configshow | grep flow.ioanalytics | grep 1 | wc -l`

cmd_chassis() {

  context_switch chassis

  if [ "$CONFIG" = "TRUE" ]; then
    echo -n . > $TTY
    cliidx=`/usr/bin/expr $cliidx + 1`
    echo "$cliidx $1 $2 $3 $4 $5 $6 $7 $8 $9" >> $cshow
    echo -e "$1 $2 $3 $4 $5 $6 $7 $8 $9:"
      echo "** $1 $2 $3 $4 $5 $6 $7 $8 $9: Command:$rc **" >> $cshow
  else
    echo -e "$1 $2 $3 $4 $5 $6 $7 $8 $9:"
    $1 $2 $3 $4 $5 $6 $7 $8 $9
  fi
}

#
# check_vf_enabled
#
# Check whether VF is enabled
# both Active and Standby have this information
#
check_vf_enabled() {
    $CHASSISCMD /fabos/bin/fosconfig --show | grep "Virtual Fabric" | grep enabled > /dev/null 2>&1

    if [ $? -eq 0 ]; then
        return $STS_ERR
    else
        return $STS_OK
    fi

}

#
# both Active and Standby have the information of
# VF and logical switches configured.
## VF case: on Standby CP, in order to login to each logical switch, 
# we need to set CHASSIS_ROLEID FABOS_SWITCHNO CURRENT_VF in rsh.
#
correcthost_to_curr_vfid() {
    # Check if active again in case active CP reboots in middle of postinst
    isActive
    if [ $ACTIVECP ] ; then
        # for_all_context already did "context_switch --switch vfid"
        "$@"
    else
        if [ $VF_ENABLED -eq $STS_OK ]; then
            # VF disabled
            /usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CURRENT_AD=0 "$@"
        else
            # VF enabled, for_all_context changed glb_ls_id and glb_vf_id to each logical switch's
            /usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 FABOS_SWITCHNO=$glb_ls_id CURRENT_VF=$glb_vf_id CURRENT_AD=0 "$@"
        fi
    fi
}

correcthost_all_vfs() {
    # Check if active again in case active CP reboots in middle of postinst
    isActive
    if [ $VF_ENABLED -ne $STS_OK ]; then
        # VF is enabled
        if [ $ACTIVECP ] ; then
            for_all_contexts correcthost_to_curr_vfid $@
        else
            # this is the standby cp, examine the configuration of the
            # active cp
            for_all_contexts_standby correcthost_to_curr_vfid $@
        fi
    else
        correcthost_to_curr_vfid $@
    fi
    if [ $? -eq 0 ]; then
        return $STS_OK
    else
        return $STS_ERR
    fi
}

correcthost_to_DS() {
    # Check if active again in case active CP reboots in middle of postinst
    isActive
    if [ $ACTIVECP ] ; then
        # for_all_context already did "context_switch --switch vfid"
	current_context=$CURRENT_VF;
	context_switch $def_vf_id;
        "$@"
	context_switch $current_context;
    else
        if [ $VF_ENABLED -eq $STS_OK ]; then
            # VF disabled
            /usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CURRENT_AD=0 "$@"
        else
            # VF enabled
            /usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 FABOS_SWITCHNO=0 CURRENT_VF=$def_vf_id CURRENT_AD=0 "$@"
        fi
    fi
}

context_switch()
{
    if [ "$1" != "chassis" ]
    then
        eval $(/fabos/cliexec/lscfg_util --switch $1)
    else
        eval $(/fabos/cliexec/lscfg_util --chassis)
        #export CHASSIS_ROLEID=0
    fi
    export ROLE_ID=root
}

# Helper function. It sets the global variable CONTEXTS to be a list of fabric
# IDs.  Typical usage is seen in the function for_all_contexts, where we use
# CONTEXTS if it is defined, and otherwise call this function. This means we
# only need to do the configshow once for each run of preinst, rather than once
# for each test that wants to run in all contexts
get_all_contexts(){
    CONTEXTS=$($CHASSISCMD /fabos/cliexec/configshow -all | sed -n 's/Fabric ID =//p')
    #echo "$CONTEXTS"
}

glb_ls_id=-1
glb_vf_id=255
def_vf_id=128


# Helper function. Loop over the valid fabric IDs running the test that is
# passed as a parameter. As soon as one test fails then return $STS_ERR. If
# all pass then return $STS_OK.
# WARNING. This command will change to a random context (The first one that
# fails the test or the last context if all pass). Random terms in case someone
# is searching this file, VF Virtual Fabric AD setcontext FID context and
# wants to find this warning
for_all_contexts(){
    for FID in ${CONTEXTS:-$(get_all_contexts)} ; do
        context_switch $FID
        glb_vf_id=$CURRENT_VF; glb_ls_id=$FABOS_SWITCHNO
        if "$@"
        then    $ECHO -n "$FID-passed "
        else    $ECHO -n "$FID-failed "
                return $STS_ERR
        fi
    done
    return $STS_OK
}

for_all_contexts_standby(){
    rval=$STS_OK
    /bin/ln -s /fabos/cliexec/lscfg_util /fabos/link_sbin/lscfg_test 2> /dev/null
    local_flag=$?
    export PATH=/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/link_rbin:/fabos/factory:/fabos/xtool
    lscfg_test --all | grep -e "[0-9]" | grep -v "Total" |
    while read glb_ls_id glb_vf_id role
    do
        context_switch $glb_vf_id
        if "$@"
        then    $ECHO -n "$glb_vf_id-passed "
        else    $ECHO -n "$glb_vf_id-failed "
            # note the following return just return from the "|" subshell
            return $STS_ERR
        fi
    done
    if [ $? -ne $STS_OK ]; then rval=$STS_ERR; fi
    if [ $local_flag -eq 0 ];then /bin/rm /fabos/link_sbin/lscfg_test 2> /dev/null; fi
    return $rval
}

#
# Helper functions (END)
#


# Take the list of ports that are in the FULL state and send a Hello
# But this needs to be done repeatedly because it could be awhile
# before the other steps of firmwaredownload are completed.
# This part will create a background task that resends the Hello messages
# every 2 seconds. This will be done for up to a minute.
#
# Input:
#    $iface_list - a list of port numbers
#

send_hellos()
{
 nohup /bin/bash <<'TO_HERE'
 ports=$iface_list
 declare -i reps=0

 while [ $reps -lt 30 ]
 do

  date

  for portnum in $ports
  do
   echo fspfHATest hloto $portnum
   ./fspfHATest hloto $portnum
  done

  sleep 2

  reps=$(($reps+1))

 done

TO_HERE

}

#This function is being used only by copyAllConfigurationFiles 
#There is no need for the caller to call this function instead call 
#CONFIGSHOW_ADV function


CONFIGSHOW() {
	if [ $ACTIVECP ] ; then
		if [ "$1" = "-chassis"  ]; then 
			cat /tmp/config_chassis
		elif [ "$1" = "-a" ] || [ "$1" = "-all" ] ; then
			cat /tmp/config_all
		else
			if [ $VF_ENABLED -ne $STS_OK ]; then
				cat /tmp/config_$CURRENT_VF
			else 
				cat /tmp/config_128
			fi
		fi
	else
		if [ "$1" = "-chassis"  ]; then 
			cmd="/fabos/cliexec/configshow -chassis"
			glb_ls_id=-1;
			glb_vf_id=255;
		elif [ "$1" = "-a" ] || [ "$1" = "-all" ] ; then
			glb_ls_id=-1;
			glb_vf_id=255;
			cmd="/fabos/cliexec/configshow -all"
		else
			cmd="/fabos/cliexec/configshow"
		fi
	
		if [ $VF_ENABLED -eq $STS_OK ]; then
			# VF disabled
			/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CURRENT_AD=0 "$cmd"
		else
			# VF enabled, for_all_context changed glb_ls_id and glb_vf_id to each logical switch's
			/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 FABOS_SWITCHNO=$glb_ls_id CURRENT_VF=$glb_vf_id CURRENT_AD=0 "$cmd"
		fi
	fi

}


# copy all the configuration to tmp files before pre-install script runs.
# this avoids anyone to run RSH

copyAllConfigurationFiles() {
    get_all_contexts
    # checks for active or standby
    if [ $ACTIVECP ] ; then
	#VF enable
	if [ $VF_ENABLED -ne $STS_OK ]; then
	    # iterating through all the FIDs
	    for FID in ${CONTEXTS}; do
		context_switch $FID
		/fabos/cliexec/configshow -fid $FID > /tmp/config_$FID
	    done
	else
	    # in non FD enviorenment there will be only one configuration - no all, no chassis
	    /fabos/cliexec/configshow > /tmp/config_128
	    
	fi
	/fabos/cliexec/configshow -chassis  > /tmp/config_chassis
	/fabos/cliexec/configshow -all  > /tmp/config_all
    else
	# VF is enabled on standby

	if [ $VF_ENABLED -ne $STS_OK ]; then

	    /bin/ln -s /fabos/cliexec/lscfg_util /fabos/link_sbin/lscfg_test 2> /dev/null
	    local_flag=$?
	    export PATH=/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/link_rbin:/fabos/factory:/fabos/xtool
	    lscfg_test --all | grep -e "[0-9]" | grep -v "Total" |
	    while read glb_ls_id glb_vf_id role
	    do
	        context_switch $glb_vf_id
		CONFIGSHOW > /tmp/config_$glb_vf_id
	    done
	    CONFIGSHOW "-chassis" > /tmp/config_chassis
	    CONFIGSHOW "-all" > /tmp/config_all
	    
	    # deleting the soft link created by ln command above
	    if [ $local_flag -eq 0 ];then 
		/bin/rm /fabos/link_sbin/lscfg_test 2> /dev/null;
	    fi
	else
	    CONFIGSHOW > /tmp/config_128
	    CONFIGSHOW -chassis > /tmp/config_chassis
	    CONFIGSHOW -all > /tmp/config_all
	fi
    fi    
}

# calling to copy configuration files to /tmp directory
copyAllConfigurationFiles


# Remove serviceexec logs generated by maintenance user
remove_svcexec_log()
{
	if ls /var/log/svcexec.log* 1> /dev/null 2>&1; then
		rm -rf /var/log/svcexec.log* 2>/dev/null
		rm -rf /mnt/var/log/svcexec.log* 2>/dev/null
	fi
}

# Need to check VF enabled and do the same for all logical switches.
remove_snmp_trap_change()
{
	/fabos/cliexec/config remove trackChanges.status
	/fabos/cliexec/config remove trackChanges.snmp-trap
	/fabos/cliexec/configcommit ;
}

remove_secrpc() {
	/fabos/cliexec/config remove secrpc.enabled
	/fabos/cliexec/configcommit ;
}

# Need to remove deprecated rpcd config keys
remove_rpcd() {
	/fabos/cliexec/config remove rpcd.callback.enabled
	/fabos/cliexec/config remove rpcd.callback.secret
	/fabos/cliexec/config remove rpcd.enabled
	/fabos/cliexec/config remove rpcd.ssl.enabled
	check_vf_enabled
	if [ $? -ne $STS_OK ]; then
		for_all_contexts remove_secrpc
	else
		remove_secrpc
	fi
}

remove_portswap_keys()
{
		value=`cat /etc/fabos/fabos.0.conf | grep -i "port.portSwapEnabled"`
		correcthost_all_vfs /fabos/cliexec/config remove port.portSwapEnabled
		/fabos/cliexec/configcommit ;
}

#
# check whether the two input files are the same by comparing the checksum
# returns 0 if the files are same. Otherwise 1.
#
comp_file()
{
	f1="$1"
	f2="$2"
	result=1
	if [ -f $f1 ] && [ -f $f2 ]; then
		sum1=`md5sum $f1 |cut -f 1 -d ' '`
		sum2=`md5sum $f2 |cut -f 1 -d ' '`
		$ECHO "$f1: $sum1, $f2: $sum2"
		if [ $sum1 = $sum2 ]; then
			result=0
		fi
	fi
	return $result
}

cp_or_rm_alpa_files()
{
	if [ $ACTIVECP ]; then
		ag_mode=`/fabos/link_bin/switchshow | grep -c "Access Gateway Mode"`

		if [ "$ag_mode" -eq 0 ]; then
			/bin/rm -f /etc/fabos/persistent_NPIV_config_6_4
			/bin/rm -f /mnt/etc/fabos/persistent_NPIV_config_6_4
			/bin/rm -f /etc/fabos/fcid_virt_config
			/bin/rm -f /mnt/etc/fabos/fcid_virt_config
		fi

		if [ "$ag_mode" -eq 1 ]; then
			/bin/cp /etc/fabos/persistent_NPIV_config_6_4 /mnt/etc/fabos/persistent_NPIV_config_6_4
			/bin/cp /etc/fabos/fcid_virt_config /mnt/etc/fabos/fcid_virt_config
		fi
	fi
}

# 
# Handle all pre 5.3 versions 
#
# Update Telnet in inetd.conf as neccessary

TELNET_ENTRY=`/bin/grep "^telnet    " /mnt/etc/inetd.conf | /usr/bin/cut -d' ' -f 1`
if [ "$TELNET_ENTRY" != "" ]; then
	/bin/cat /mnt/etc/inetd.conf | /bin/sed -e 's/^#telnet  /telnet /g' > /mnt/etc/inetd.conf
fi


checksmmsuser()
{
	file="$1"
	hassmmsuser=`cat $file | grep "smmsp:" | wc -l`
    if [ $hassmmsuser -eq 0 ]; then
		echo 'smmsp:*:25:25:sendmail:/home/smmsp:/bin/false'>>$file;
	fi
}

checksmmsgrp()
{
file="$1"
hassmmsgrp=`cat $file | grep "smmsp:" | wc -l`
if [ $hassmmsgrp -eq 0 ]; then
echo 'smmsp::25:smmsp'>>$file
fi
}


#Set the SNMP config key to default when upgrade to 8.1.0
if [ $TO_MAJOR -ge 8 -a $TO_MINOR -ge 1 ]; then
	/fabos/cliexec/config set snmp.64mibCap.BROCADE-MAPS-MIB 6 0x7
	/fabos/cliexec/configcommit
fi


#Set the SNMP FCMGMT key to default when upgrade to 8.1.0
fcmgmt=$((16#`/fabos/cliexec/config get snmp.64mibCap.FCMGMT-MIB 6`))
if [ $TO_MAJOR -ge 7 -a $TO_MINOR -ge 4 ] || [ $TO_MAJOR -ge 8 -a $TO_MINOR -ge 0  ]; then
		a=$((fcmgmt&0x1))
		b=$((fcmgmt&0x2))  
		c=$((fcmgmt&0x40))  
		d=$((fcmgmt&0x10))
	fcmgmt_orig=$(printf '%x' $((a|b|c|d)))
	/fabos/cliexec/config set snmp.64mibCap.FCMGMT-MIB 6 $fcmgmt_orig
	/fabos/cliexec/configcommit
fi	

if [ -f /etc/group ]; then
correcthost_to_curr_vfid /bin/chmod 644 /etc/group
fi
if [ -f /mnt/etc/group ]; then
correcthost_to_curr_vfid /bin/chmod 644 /mnt/etc/group
fi

 
#copying login config files from primary to seconday partition
#overwriting on the files, if any, copied by the rpm
cp /etc/passwd /mnt/etc/passwd
cp /etc/shadow /mnt/etc/shadow
cp /etc/group /mnt/etc/group
cp /etc/fabos/user.db /mnt/etc/fabos/user.db

# check for smmsp user and group and in the files and add entry if needed.
# the smmsp user is needed for the new sendmail package that is installed as
# part of f/w that has linux 2.6 kernel.
checksmmsuser /etc/passwd
checksmmsuser /etc/passwd.default
checksmmsgrp /etc/group
checksmmsgrp /etc/group.default
checksmmsuser /mnt/etc/passwd
checksmmsuser /mnt/etc/passwd.default
checksmmsgrp /mnt/etc/group
checksmmsgrp /mnt/etc/group.default

#log the FWDL from & to versions
cp /var/log/user.log /mnt/var/log/user.log
echo -e "\n`date` - FWDL from $FROM_MAJOR.$FROM_MINOR to $TO_MAJOR.$TO_MINOR\n" >> /mnt/var/log/user.log

if [ ! -e /mnt/etc/fabos/mii.cfg ]; then
	if [ -e /mnt/etc/fabos/mii.0.cfg ]; then
		cp /mnt/etc/fabos/mii.0.cfg /etc/fabos/mii.cfg
		cp /mnt/etc/fabos/mii.0.cfg /mnt/etc/fabos/mii.cfg
	elif [ -e /mnt/etc/fabos/mii.1.cfg ] ; then
		cp /mnt/etc/fabos/mii.1.cfg /etc/fabos/mii.cfg
		cp /mnt/etc/fabos/mii.1.cfg /mnt/etc/fabos/mii.cfg
	fi
fi


#UID_CONVERSION="Version Supports UID Conversion"
uid_conversion()
{
	new_fw_is_SV=$(grep -c "UID_CONVERSION" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "UID_CONVERSION" $POSTINST)    # grep in postinst of Current fw

	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
	if [ $new_fw_is_SV -eq 0 ]; then
		new_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	fi	
	if [ $cur_fw_is_SV -eq 0 ]; then
		cur_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $POSTINST) # grep in postinst of Current fw
	fi	
	
	if [ $cur_fw_is_SV -eq 0 ]; then
		#Forward Conversion
		if [ $new_fw_is_SV -gt 0 ]; then
			#Password Conversion - UID Forward Conversion
			/mnt/fabos/libexec/passwd_convert /mnt/etc/passwd FWDL_CONVERSION UID_FORWARD_CONVERSION > /dev/null 2>&1
			/bin/cp /mnt/etc/passwd /etc/passwd > /dev/null 2>&1
			#Group Conversion - UID Forward Conversion
			/mnt/fabos/libexec/group_convert /mnt/etc/group FWDL_CONVERSION UID_FORWARD_CONVERSION > /dev/null 2>&1
			/bin/cp /mnt/etc/group /etc/group > /dev/null 2>&1

			#Permission correction for home directories
			pkgname=`/bin/rpm -qf /fabos/users/user --root /mnt`
			/usr/sbin/chroot /mnt /bin/rpm --setugids $pkgname > /dev/null 2>&1
			if [ $? -ne 0 ]; then
				#Udrole update
				/usr/sbin/chroot /mnt /bin/chown -R udrole:udrole /fabos/users/udrole
				#Permission correction for home directories
				/usr/sbin/chroot /mnt /bin/chown -R basicswitchadmin:basicswitchadmin /fabos/users/basicswitchadmin
				/usr/sbin/chroot /mnt /bin/chown -R fabricadmin:fabricadmin /fabos/users/fabricadmin
				/usr/sbin/chroot /mnt /bin/chown -R operator:operator /fabos/users/operator
				/usr/sbin/chroot /mnt /bin/chown -R securityadmin:securityadmin /fabos/users/securityadmin
				/usr/sbin/chroot /mnt /bin/chown -R switchadmin:switchadmin /fabos/users/switchadmin
				/usr/sbin/chroot /mnt /bin/chown -R user:user /fabos/users/user
				/usr/sbin/chroot /mnt /bin/chown -R zoneadmin:zoneadmin /fabos/users/zoneadmin
				/bin/grep "^factory" /mnt/etc/passwd > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					if [ -d /mnt/fabos/users/diag ]; then
						/usr/sbin/chroot /mnt /bin/chown -R factory:factory /fabos/users/diag
					fi
				fi
			fi
		fi
	fi
}

#INVALID_ACCOUNTS_REMOVAL="Version Supports Invalid Accounts Removal"
invalid_accounts_conversion()
{
	new_fw_is_SV=$(grep -c "INVALID_ACCOUNTS_REMOVAL" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "INVALID_ACCOUNTS_REMOVAL" $POSTINST)    # grep in postinst of Current fw

	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
	if [ $new_fw_is_SV -eq 0 ]; then
		new_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	fi	
	if [ $cur_fw_is_SV -eq 0 ]; then
		cur_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $POSTINST) # grep in postinst of Current fw
	fi	
	

	if [ $cur_fw_is_SV -eq 0 ]; then
		#Forward Conversion
		if [ $new_fw_is_SV -gt 0 ]; then
			#Password Conversion - Invalid roles removal
			/mnt/fabos/libexec/passwd_convert /mnt/etc/passwd FWDL_CONVERSION INVALID_ROLES_REMOVAL > /dev/null 2>&1
			/bin/cp /mnt/etc/passwd /etc/passwd > /dev/null 2>&1
			#Group Conversion - Invalid roles removal
			/mnt/fabos/libexec/group_convert /mnt/etc/group FWDL_CONVERSION INVALID_ROLES_REMOVAL > /dev/null 2>&1
			/bin/cp /mnt/etc/group /etc/group > /dev/null 2>&1
		fi
	fi
}

#DEFAULT_ACCT_PASSWD_UPDATE="Version Supports Default Account Passwd Update"
default_account_passwd_update()
{
	#******Password Conversion
	new_fw_is_SV=$(grep -c "DEFAULT_ACCT_PASSWD_UPDATE" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "DEFAULT_ACCT_PASSWD_UPDATE" $POSTINST)    # grep in postinst of Current fw

	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
	if [ $new_fw_is_SV -eq 0 ]; then
		new_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	fi	
	if [ $cur_fw_is_SV -eq 0 ]; then
		cur_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $POSTINST) # grep in postinst of Current fw
	fi	
	
	if [ $cur_fw_is_SV -eq 0 ]; then
		#Forward Conversion
		if [ $new_fw_is_SV -gt 0 ]; then

			#Password Conversion - Replace defacct passwd with "x"
			/mnt/fabos/libexec/passwd_convert /mnt/etc/passwd FWDL_CONVERSION DEFACCTPASSWD_REMOVAL > /dev/null 2>&1
			/bin/cp /mnt/etc/passwd /etc/passwd > /dev/null 2>&1

		fi
	fi
}

#FACTORY_REMOVAL_SUPPORTED="Version Supports Factory Account Removal"
factory_conversion()
{
	#******Factory Conversion
	new_fw_is_SV=$(grep -c "FACTORY_REMOVAL_SUPPORTED" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "FACTORY_REMOVAL_SUPPORTED" $POSTINST)    # grep in postinst of Current fw

	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
	if [ $new_fw_is_SV -eq 0 ]; then
		new_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	fi	
	if [ $cur_fw_is_SV -eq 0 ]; then
		cur_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $POSTINST) # grep in postinst of Current fw
	fi

	factory_group=$(/bin/grep -c "^factory:" /etc/group)
	factory_shadow=$(/bin/grep -c "^factory:" /etc/shadow)
	factory_passwd=$(/bin/grep -c "^factory:" /etc/passwd)	

	if [ $cur_fw_is_SV -gt 0 -a  $new_fw_is_SV -eq 0 ]; then
		# Backward Conversion - this "factory_conversion" function has changes for factory removal
		# and hence has no role in backward conversion scenario
		return
	fi

	#Forward Conversion (current fw is non supporting version, the new firmware is supporting version)
	if [ $cur_fw_is_SV -eq 0 -a $new_fw_is_SV -gt 0 ] || [ $factory_group -gt 0 -o $factory_shadow -gt 0 -o $factory_passwd -gt 0 ]; then

			if [ $VF_ENABLED -eq $STS_OK ]; then
				# VF disabled
				RSH_CMD="/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CURRENT_AD=0"
			else
				# VF enabled, for_all_context changed glb_ls_id and glb_vf_id to each logical switch's
				RSH_CMD="/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 FABOS_SWITCHNO=$glb_ls_id CURRENT_VF=$glb_vf_id CURRENT_AD=0"
			fi
		
			#Factory removal - /shadow /opasswd 
			#Remove "factory" account entry from /etc/shadow, opasswd
			if [ $ACTIVECP ]; then
				/bin/sed '/^factory:/d'  /etc/shadow > /tmp/shadow
				cat /tmp/shadow > /etc/shadow
				rm /tmp/shadow

				/bin/sed '/^factory:/d'  /etc/fabos/opasswd > /tmp/opasswd
				cat /tmp/opasswd > /etc/fabos/opasswd
				rm /tmp/opasswd
			else
				$RSH_CMD "/bin/sed '/^factory:/d'  /etc/shadow > /tmp/shadow"
				$RSH_CMD "cat /tmp/shadow > /etc/shadow"
				$RSH_CMD "rm /tmp/shadow"

				$RSH_CMD "/bin/sed '/^factory:/d'  /etc/fabos/opasswd > /tmp/opasswd"
				$RSH_CMD "cat /tmp/opasswd > /etc/fabos/opasswd"
				$RSH_CMD "rm /tmp/opasswd"
			fi

			correcthost_to_curr_vfid /fabos/cliexec/config save /etc/shadow
			correcthost_to_curr_vfid /fabos/cliexec/config save /etc/opasswd
			correcthost_to_curr_vfid /fabos/sbin/sshutil delusrpubkey factory>/dev/null 2>&1

			#Password Conversion - Factory removal
			/mnt/fabos/libexec/passwd_convert /mnt/etc/passwd FWDL_CONVERSION FACTORY_REMOVAL > /dev/null 2>&1
			/bin/cp /mnt/etc/passwd /etc/passwd > /dev/null 2>&1

			#Group Conversion - Factory removal
			/mnt/fabos/libexec/group_convert /mnt/etc/group FWDL_CONVERSION FACTORY_REMOVAL > /dev/null 2>&1
			/bin/cp /mnt/etc/group /etc/group > /dev/null 2>&1

			#Factory removal from Userdb
			/mnt/fabos/libexec/dummy_trigger /mnt/etc/fabos/user.db FWDL_CONVERSION FACTORY_REMOVAL > /dev/null 2>&1
	fi
}

#FILE_PERMISSION_UPDATE="Version Supports File Permission Update"
file_permission_modifications()
{
	#File Permission Updates
	#Change file ppermisson to security config files after upgrade to 8.0.1 or above.
	
	filelist_perm_400="/etc/fabos/certs/sw0/pvt_key"

	filelist_perm_600="/etc/shadow \
	/etc/passwd \
	/etc/fabos/opasswd \
	/etc/ssh_config \
	/etc/sshd_config \
	/etc/fabos/user.db \
	/etc/fabos/pwron_fips_status \
	/etc/fabos/pki/switch.0.csr \
	/etc/fabos/pki/switch.0.key \
	/etc/fabos/pki/switch.0.crt \
	/etc/fabos/pki/switch.0.pp \
	/etc/fabos/pki/switch.0.rootcrt \
	/etc/fabos/pki/tp/switch.0.csr \
	/etc/fabos/pki/tp/switch.0.key \
	/etc/fabos/pki/tp/switch.0.crt \
	/etc/fabos/pki/tp/switch.0.pp \
	/etc/fabos/pki/tp/switch.0.rootcrt \
	/root/.ssh/known_hosts \
	/etc/ssh_host_dsa_key /etc/ssh_host_dsa_key.pub /etc/ssh_host_rsa_key /etc/ssh_host_rsa_key.pub /etc/ssh_host_ecdsa_key /etc/ssh_host_ecdsa_key.pub \
	/root/.ssh/id_dsa /root/.ssh/id_dsa.pub /root/.ssh/id_rsa /root/.ssh/id_rsa.pub /root/.ssh/id_ecdsa /root/.ssh/id_ecdsa.pub \
	/etc/fabos/fips_selftests.conf \
	/etc/fabos/tacplus.conf \
	/etc/fabos/ldap.conf \
	/etc/raddb/server \
	/etc/fabos/auth.0.conf /etc/fabos/auth.1.conf /etc/fabos/auth.2.conf /etc/fabos/auth.3.conf \
	/etc/fabos/auth.4.conf /etc/fabos/auth.5.conf /etc/fabos/auth.6.conf /etc/fabos/auth.7.conf \
	/etc/fabos/authutil.0.conf /etc/fabos/authutil.1.conf /etc/fabos/authutil.2.conf /etc/fabos/authutil.3.conf \
	/etc/fabos/authutil.4.conf /etc/fabos/authutil.5.conf /etc/fabos/authutil.6.conf /etc/fabos/authutil.7.conf \
	/etc/fabos/fabos.0.conf /etc/fabos/fabos.1.conf /etc/fabos/fabos.2.conf /etc/fabos/fabos.3.conf /etc/fabos/fabos.4.conf \
	/etc/fabos/fabos.5.conf /etc/fabos/fabos.6.conf /etc/fabos/fabos.7.conf /etc/fabos/fabos.8.conf /etc/fabos/fabos.9.conf \
	/etc/fabos/fabos.10.conf /etc/fabos/fabos.11.conf /etc/fabos/fabos.12.conf /etc/fabos/fabos.13.conf \
	/etc/fabos/fabos.14.conf /etc/fabos/fabos.15.conf /etc/fabos/fabos.chassis.conf"

	if [ $VF_ENABLED -eq $STS_OK ]; then
		# VF disabled
		RSH_ENV="ROLE_ID=root LOGIN_ID=root CURRENT_AD=0"
	else
		# VF enabled, for_all_context changed glb_ls_id and glb_vf_id to each logical switch's
		RSH_ENV="ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 FABOS_SWITCHNO=$glb_ls_id CURRENT_VF=$glb_vf_id CURRENT_AD=0"
	fi
	if [ $ACTIVECP ]; then
		isActiveCp=1
	else
		isActiveCp=0
	fi

 for i in $filelist_perm_400; do
        if [ -f $i ]; then
                /bin/chmod 400 $i
        fi
        if [ -f /mnt/$i ]; then
                /bin/chmod 400 /mnt/$i
        fi
done

if [ $isActiveCp -eq 0 ]; then
	#Change file permission in Otherhost main partition
	/usr/bin/rsh -n $(otherhost) "export TEMP_VAR=\"$filelist_perm_400\";for files in \$TEMP_VAR; do if [ -f \$files ]; then $RSH_ENV /bin/chmod 400 \$files; fi; done;unset TEMP_VAR"
		
	#Change file permission in Otherhost mnt partition
	/usr/bin/rsh -n $(otherhost) "export TEMP_VAR=\"$filelist_perm_400\";for files in \$TEMP_VAR; do if [ -f \$files ]; then $RSH_ENV /bin/chmod 400 /mnt/\$files; fi; done; unset TEMP_VAR"
fi

for i in $filelist_perm_600; do
        if [ -f $i ]; then
                /bin/chmod 600 $i
        fi
        
        if [ -f /mnt/$i ]; then
                /bin/chmod 600 /mnt/$i
        fi
done

if [ $isActiveCp -eq 0 ]; then
	# Change file permission in otherhost main partition
	/usr/bin/rsh -n $(otherhost) "export TEMP_VAR=\"$filelist_perm_600\";for files in \$TEMP_VAR; do if [ -f \$files ]; then $RSH_ENV /bin/chmod 600 \$files; fi; done;unset TEMP_VAR"
	
	# Change file permission in otherhost mnt partition
	/usr/bin/rsh -n $(otherhost) "export TEMP_VAR=\"$filelist_perm_600\";for files in \$TEMP_VAR; do if [ -f \$files ]; then $RSH_ENV /bin/chmod 600 /mnt/\$files; fi; done; unset TEMP_VAR"
fi
}

#PASSWD_HASH_SUPPORTED="Version Supports Passwd Hash Configuration"
passwd_hash_conversion()
{
	#******Passwd hash Conversion
	new_fw_is_SV=$(grep -c "PASSWD_HASH_SUPPORTED" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "PASSWD_HASH_SUPPORTED" $POSTINST)    # grep in postinst of Current fw

	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
	if [ $new_fw_is_SV -eq 0 ]; then
		new_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	fi	
	if [ $cur_fw_is_SV -eq 0 ]; then
		cur_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $POSTINST) # grep in postinst of Current fw
	fi	

	if [ $cur_fw_is_SV -eq 0 ]; then
		#Forward Conversion
		if [ $new_fw_is_SV -gt 0 ]; then
			#Password hash update
			#Update hash=md5 and manual=1
			correcthost_to_curr_vfid /fabos/cliexec/config set passwdcfg.hash 5 md5
			correcthost_to_curr_vfid /fabos/cliexec/config set passwdcfg.manualHashChange 2 1 
			correcthost_to_curr_vfid /fabos/cliexec/config update
		fi
	fi
}

#ROOT_ACCESS_SUPPORTED="Version Supports Root Access Feature"
root_access_update()
{
	#******Root access update	
	new_fw_is_SV=$(grep -c "ROOT_ACCESS_SUPPORTED" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "ROOT_ACCESS_SUPPORTED" $POSTINST)    # grep in postinst of Current fw

	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
	if [ $new_fw_is_SV -eq 0 ]; then
		new_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	fi	
	if [ $cur_fw_is_SV -eq 0 ]; then
		cur_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $POSTINST) # grep in postinst of Current fw
	fi	

	#Forward Conversion
	if [ $cur_fw_is_SV -eq 0 ]; then
		if [ $new_fw_is_SV -gt 0 ]; then	
			#Root access update
			#Setting root access to "all" in case of upgrade
			SUPPLIER_ID=`correcthost_to_curr_vfid /fabos/bin/chassisshow | /bin/awk '/ID/ {print $2}'`
			if [ "${SUPPLIER_ID:-0}" == "BRD0000HU" ]; then
				sed '/root:/s/\(.*\)::/\1:0:/' /etc/shadow > /tmp/shadow_temp
				cat /tmp/shadow_temp
                        	/bin/cp /tmp/shadow_temp /etc/shadow
                        	/fabos/cliexec/config save /etc/shadow

				sed '/root:/s/\(.*\)::/\1:0:/' /mnt/etc/shadow > /tmp/shadow_temp
                        	/bin/cp /tmp/shadow_temp /mnt/etc/shadow
                        	/fabos/cliexec/config save /mnt/etc/shadow
				/bin/rm /tmp/shadow_temp
				correcthost_to_curr_vfid /fabos/cliexec/config set root.access 5 none
			else
				correcthost_to_curr_vfid /fabos/cliexec/config set root.access 5 all
			fi
			correcthost_to_curr_vfid /fabos/cliexec/config update
		fi
	fi
}

remove_ciphersuite_keys()
{
	if [ $CURRENT_VF -ne $def_vf_id ]; then
		correcthost_to_curr_vfid /fabos/cliexec/config remove cipher.https
		correcthost_to_curr_vfid /fabos/cliexec/config remove cipher.ssh
		correcthost_to_curr_vfid /fabos/cliexec/config remove kex.ssh
		correcthost_to_curr_vfid /fabos/cliexec/config remove mac.ssh
		correcthost_to_curr_vfid /fabos/cliexec/config remove cipher.radius
		correcthost_to_curr_vfid /fabos/cliexec/config remove cipher.ldap
		correcthost_to_curr_vfid /fabos/cliexec/configcommit
	fi
}

remove_ciphersuite_keys_in_all_contexts()
{
    # Check for Virtual Fabrics
    if [ $VF_ENABLED -ne $STS_OK ]; then
        if [ $ACTIVECP ]; then
            CHASSISCMD="cmd_chassis";
            current_context=$CURRENT_VF ;
            for_all_contexts remove_ciphersuite_keys ;
            context_switch $current_context ;
        else
            for_all_contexts_standby remove_ciphersuite_keys ;
        fi
    fi
}

#CIPHER_KEYS_SUPPORTED="Versions Supports Cipher Keys"
cipher_key_update()
{
	#******Cipherkey removal	
	new_fw_is_SV=$(grep -c "CIPHER_KEYS_SUPPORTED" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "CIPHER_KEYS_SUPPORTED" $POSTINST)    # grep in postinst of Current fw

	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
	if [ $new_fw_is_SV -eq 0 ]; then
		new_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	fi	
	if [ $cur_fw_is_SV -eq 0 ]; then
		cur_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $POSTINST) # grep in postinst of Current fw
	fi	

	#Forward Conversion
	if [ $cur_fw_is_SV -eq 0 ]; then
		if [ $new_fw_is_SV -gt 0 ]; then	
			#Cipherkey removal
			#
			# remove the configkeys from all the contexts except default switch
			# this change is to support transition from switch configuration to chassis specific
			#
			remove_ciphersuite_keys_in_all_contexts;
		fi
	fi
}

#LDAP_DEFAULTCIPHER_UPDATE="Version Supports Default LDAP Ciphers"
ldap_cipher_update()
{
	#******Setting the LDAP ciphers 
	new_fw_is_SV=$(grep -c "LDAP_DEFAULTCIPHER_UPDATE" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "LDAP_DEFAULTCIPHER_UPDATE" $POSTINST)    # grep in postinst of Current fw

	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
	if [ $new_fw_is_SV -eq 0 ]; then
		new_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	fi	
	if [ $cur_fw_is_SV -eq 0 ]; then
		cur_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $POSTINST) # grep in postinst of Current fw
	fi	

	#Forward Conversion
	if [ $cur_fw_is_SV -eq 0 ]; then
		if [ $new_fw_is_SV -gt 0 ]; then	
			#Setting the LDAP ciphers to DEFAULT
			checkFipsMode
			retVal=$?
			if [ $retVal -eq 0 ]; then
				correcthost_to_curr_vfid /fabos/cliexec/config set cipher.ldap 5 'DEFAULT:!PSK'
			fi
			correcthost_to_curr_vfid /fabos/cliexec/config update
		fi
	fi
}

#SSH_HOSTKEY_CONVERSION_REQUIRED="Convert ssh hostkeys from openssh to PEM format during downgrade"
ssh_hostkey_conversion() {
	new_fw_is_SV=$(grep -c "SSH_HOSTKEY_CONVERSION_REQUIRED" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "SSH_HOSTKEY_CONVERSION_REQUIRED" $POSTINST)    # grep in postinst of Current fw
	if [ $ACTIVECP ]; then
		isActiveCp=1
	else
		isActiveCp=0
	fi
	#Downgrade conversion
	if [ $cur_fw_is_SV -gt 0 ]; then
		if [ $new_fw_is_SV -eq 0 ]; then
			ssh_host_keys_list="/etc/ssh_host_rsa_key \
					/etc/ssh_host_dsa_key \
					/etc/ssh_host_ecdsa_key"
			for i in $ssh_host_keys_list; do
				if [ -f $i ]; then
					new_format_key_present=$(/bin/grep -c "BEGIN OPENSSH" $i)
					if [ $new_format_key_present -gt 0 ]; then
						if [ $isActiveCp -eq 0 ]; then
							correcthost_to_curr_vfid "/usr/bin/ssh-keygen -p -f $i -P '' -N '' -m 'PEM' > /dev/null 2>&1"
						else
							/usr/bin/ssh-keygen -p -f $i -P '' -N '' -m 'PEM' > /dev/null 2>&1
						fi
                    					correcthost_to_curr_vfid /fabos/cliexec/config save $i
					fi
				fi
			done
		fi
	fi

}

ipsec_disable_conversion() {
	CHKCONFIG=`/usr/bin/which chkconfig`
	SPMD_FILE=/var/run/spmd.pid
	new_fw_is_ipsec=$(grep -c "IPSEC_DISABLE_REQUIRED" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_ipsec=$( grep -c "IPSEC_DISABLE_REQUIRED" $POSTINST)    # grep in postinst of current fw
	#Upgrade Scenario
	if [ $new_fw_is_ipsec -gt 0 ] && [ $cur_fw_is_ipsec -eq 0 ]; then
		if [ $STANDBYCP -eq 1 ]; then
			if [[ $(ls $SPMD_FILE 2>null) ]]; then
				content=`cat $SPMD_FILE  | wc -c 2>/dev/null`
				if [ $content -gt 0 ]; then
					/fabos/abin/ipsecconfig --disable >& /dev/null
				fi
				return $STS_OK
			fi
		fi
		ipsec_state=`$CHKCONFIG | grep ipsec | sed -n 's/.*\(on\|off\).*/\1/p'`
		if [ "$ipsec_state" != "off" ] ; then
			$CHKCONFIG ipsec off >& /dev/null
		fi
	fi
}

SSHD_CONFIG_FILE=/etc/sshd_config
SSHD_CONFIG_FILE_MNT=/mnt/etc/sshd_config
TMP_SSHD=/tmp/sshd_tmp
TMP_SSHD_COPY=/tmp/sshd_tmp_copy
SSH_CONFIG_FILE_MNT=/mnt/etc/ssh_config
TMP_SSH=/tmp/ssh_tmp

ssh_rekeylimit_conversion() {
	new_fw_is_SV=$(grep -c "SSK_REKEY_LIMIT_CONVERSION_REQUIRED" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "SSK_REKEY_LIMIT_CONVERSION_REQUIRED" $POSTINST)    # grep in postinst of Current fw
	#Forward conversion
	if [ $cur_fw_is_SV -eq 0 -a $new_fw_is_SV -gt 0 ]; then
		ret=$(grep -c "RekeyInterval" $SSHD_CONFIG_FILE_MNT)
		if [ $ret -gt 0 ]; then
			/bin/sed "s/RekeyInterval/RekeyLimit default/" $SSHD_CONFIG_FILE_MNT > $TMP_SSHD
			/bin/mv $TMP_SSHD $SSHD_CONFIG_FILE_MNT
		fi
	#Backward conversion
	elif [ $new_fw_is_SV -eq 0 -a $cur_fw_is_SV -gt 0 ]; then
		ret=$(grep -c "RekeyLimit" $SSHD_CONFIG_FILE_MNT)
		if [ $ret -gt 0 ]; then
			/bin/sed "s/RekeyLimit default/RekeyInterval/" $SSHD_CONFIG_FILE_MNT > $TMP_SSHD
			/bin/mv $TMP_SSHD $SSHD_CONFIG_FILE_MNT
		fi
	fi
}

sshd_config_handling() {
	new_fw_is_SV=$(grep -c "SSHD_CONFIG_HANDLING_REQUIRED" $MNT_POSTINST)
	cur_fw_is_SV=$(grep -c "SSHD_CONFIG_HANDLING_REQUIRED" $POSTINST)

	## Serverkeybits , PrintLastlog and UsePrivilegeSeparation not required in fw_version >=v9.0
	## Forward conversion
	if [ $cur_fw_is_SV -eq 0 -a $new_fw_is_SV -gt 0 ]; then
		Printlastlog=$(grep -c "PrintLastLog" $SSHD_CONFIG_FILE_MNT)
		usepriv_sep=$(grep -c "UsePrivilegeSeparation" $SSHD_CONFIG_FILE_MNT)
		if [ $Printlastlog -gt 0 ]; then
			/bin/sed '/PrintLastLog/d' $SSHD_CONFIG_FILE_MNT > $TMP_SSHD
			/bin/mv $TMP_SSHD $SSHD_CONFIG_FILE_MNT
		fi
		if [ $usepriv_sep -gt 0 ]; then
			/bin/sed '/UsePrivilegeSeparation/d' $SSHD_CONFIG_FILE_MNT > $TMP_SSHD
			/bin/mv $TMP_SSHD $SSHD_CONFIG_FILE_MNT
		fi
	
		serverkeybits=$(grep -c "ServerKeyBits" $SSHD_CONFIG_FILE_MNT)
		if [ $serverkeybits -gt 0 ]; then
			/bin/sed '/ServerKeyBits/d' $SSHD_CONFIG_FILE_MNT > $TMP_SSHD
			/bin/mv $TMP_SSHD $SSHD_CONFIG_FILE_MNT
		fi
	## Backward conversion
	## UsePrivilegeSeparation and printlaslog entry gets added from openssh package when fwdl to <= v9.0,
	## Not adding those entries here, if present.
	elif [ $new_fw_is_SV -eq 0 -a $cur_fw_is_SV -gt 0 ]; then
		Printlastlog=$(grep -c "PrintLastLog" $SSHD_CONFIG_FILE_MNT)
		usepriv_sep=$(grep -c "UsePrivilegeSeparation" $SSHD_CONFIG_FILE_MNT)
		if [ $usepriv_sep -eq 0 ]; then
			/bin/echo 'UsePrivilegeSeparation no' >> $SSHD_CONFIG_FILE_MNT
		fi
		if [ $Printlastlog -eq 0 ]; then
			/bin/echo 'PrintLastLog no' >> $SSHD_CONFIG_FILE_MNT
		fi
		
	fi
}

ssh_fips_config_handling() {
	new_fw=$(/bin/grep -c "SSH_CONFIG_FIPS_RELATED" $MNT_POSTINST)
	cur_fw=$(/bin/grep -c "SSH_CONFIG_FIPS_RELATED" $POSTINST)

	if [ $cur_fw -eq 0 -a $new_fw -gt 0 ]; then
		minprime=$(/bin/grep -c "MinPrime" $SSHD_CONFIG_FILE_MNT)
		ssh_minprime=$(/bin/grep -c "MinPrime" $SSH_CONFIG_FILE_MNT)
		ssh_serverhostkeysize=$(/bin/grep -c "ServerHostKeySize" $SSH_CONFIG_FILE_MNT)
		if [ $minprime -gt 0 ]; then
			/bin/sed '/MinPrime/d' $SSHD_CONFIG_FILE_MNT > $TMP_SSHD
			/bin/mv $TMP_SSHD $SSHD_CONFIG_FILE_MNT
		fi
		if [ $ssh_minprime -gt 0 ]; then
			/bin/sed '/MinPrime/d' $SSH_CONFIG_FILE_MNT > $TMP_SSH
			/bin/mv $TMP_SSH $SSH_CONFIG_FILE_MNT
		fi
		if [ $ssh_serverhostkeysize -gt 0 ]; then
			/bin/sed '/ServerHostKeySize/d' $SSH_CONFIG_FILE_MNT > $TMP_SSH
			/bin/mv $TMP_SSH $SSH_CONFIG_FILE_MNT
		fi
	fi
}

handle_pam_conf_v2() {

CONF_DIR=/mnt/etc/pam.d
CONSOLE_CONF=ttylogin
NET_CONF=netlogin
SSH_CONF=sshd

CHASSISCMD="cmd_chassis"
check_vf_enabled
if [ $? -ne $STS_OK ]; then
	# vf is enabled
	AUTHSPECMODE=`$CHASSISCMD correcthost_to_curr_vfid /fabos/bin/configshow -all | grep authspec.mode | sed -e "s/authspec.mode://g"`
else
	# echo "NON-VF" ;
	AUTHSPECMODE=`correcthost_to_curr_vfid /fabos/bin/configshow -all | grep authspec.mode | sed -e "s/authspec.mode://g"`
fi

#Refer secAuthTypeConf_t in include/security/public.h file for enum definitions for each auth spec mode

#Local only

if [ $AUTHSPECMODE -eq 0 ]; then
	/bin/cp $CONF_DIR/login.noradius $CONF_DIR/$NET_CONF
	/bin/cp $CONF_DIR/login.noradius $CONF_DIR/$CONSOLE_CONF
	/bin/cp $CONF_DIR/sshd.noradius $CONF_DIR/$SSH_CONF
#Radius only
elif [ $AUTHSPECMODE -eq 1 ]; then
	/bin/cp $CONF_DIR/login.radius $CONF_DIR/$NET_CONF
	/bin/cp $CONF_DIR/login.radius $CONF_DIR/$CONSOLE_CONF
	/bin/cp $CONF_DIR/sshd.radius $CONF_DIR/$SSH_CONF
#Radius local backup
elif [ $AUTHSPECMODE -eq 3 ]; then
	/bin/cp $CONF_DIR/login.radius-local $CONF_DIR/$NET_CONF
	/bin/cp $CONF_DIR/login.radius-local $CONF_DIR/$CONSOLE_CONF
	/bin/cp $CONF_DIR/sshd.radius-local $CONF_DIR/$SSH_CONF
#Radius local
elif [ $AUTHSPECMODE -eq 5 ]; then 
	/bin/cp $CONF_DIR/login.radius-local2 $CONF_DIR/$NET_CONF
	/bin/cp $CONF_DIR/login.radius-local2 $CONF_DIR/$CONSOLE_CONF
	/bin/cp $CONF_DIR/sshd.radius-local2 $CONF_DIR/$SSH_CONF
#Ldap only
elif [ $AUTHSPECMODE -eq 6 ]; then 
	/bin/cp $CONF_DIR/login.adldap $CONF_DIR/$NET_CONF
	/bin/cp $CONF_DIR/login.adldap $CONF_DIR/$CONSOLE_CONF
	/bin/cp $CONF_DIR/sshd.adldap $CONF_DIR/$SSH_CONF
#Ldap local
elif [ $AUTHSPECMODE -eq 7 ]; then 
	/bin/cp $CONF_DIR/login.adldap-local2 $CONF_DIR/$NET_CONF
	/bin/cp $CONF_DIR/login.adldap-local2 $CONF_DIR/$CONSOLE_CONF
	/bin/cp $CONF_DIR/sshd.adldap-local2 $CONF_DIR/$SSH_CONF
#Ldap local backup
elif [ $AUTHSPECMODE -eq 8 ]; then 
	/bin/cp $CONF_DIR/login.adldap-local $CONF_DIR/$NET_CONF
	/bin/cp $CONF_DIR/login.adldap-local $CONF_DIR/$CONSOLE_CONF
	/bin/cp $CONF_DIR/sshd.adldap-local $CONF_DIR/$SSH_CONF
#Tacacs+ only
elif [ $AUTHSPECMODE -eq 13 ]; then 
	/bin/cp $CONF_DIR/login.tacplus $CONF_DIR/$NET_CONF
	/bin/cp $CONF_DIR/login.tacplus $CONF_DIR/$CONSOLE_CONF
	/bin/cp $CONF_DIR/sshd.tacplus $CONF_DIR/$SSH_CONF
#Tacacs+ local
elif [ $AUTHSPECMODE -eq 14 ]; then 
	/bin/cp $CONF_DIR/login.tacplus-local2 $CONF_DIR/$NET_CONF
	/bin/cp $CONF_DIR/login.tacplus-local2 $CONF_DIR/$CONSOLE_CONF
	/bin/cp $CONF_DIR/sshd.tacplus-local2 $CONF_DIR/$SSH_CONF
#Tacacs+ local backup
elif [ $AUTHSPECMODE -eq 15 ]; then 
	/bin/cp $CONF_DIR/login.tacplus-local $CONF_DIR/$NET_CONF
	/bin/cp $CONF_DIR/login.tacplus-local $CONF_DIR/$CONSOLE_CONF
	/bin/cp $CONF_DIR/sshd.tacplus-local $CONF_DIR/$SSH_CONF
fi
}

#PAM_CONF_SUPPORTED="Version Supports Pam Conf Update"
pam_conf_conversion()
{
	#******Handle Pam conf
	new_fw_is_SV=$(grep -c "PAM_CONF_SUPPORTED" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "PAM_CONF_SUPPORTED" $POSTINST)    # grep in postinst of Current fw

	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
	if [ $new_fw_is_SV -eq 0 ]; then
		new_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	fi	
	if [ $cur_fw_is_SV -eq 0 ]; then
		cur_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $POSTINST) # grep in postinst of Current fw
	fi	
	
	if [ $cur_fw_is_SV -eq 0 ]; then
		#Forward Conversion
		if [ $new_fw_is_SV -gt 0 ]; then
			handle_pam_conf_v2
		fi
	fi
}

#AUTHSECRET_CONVERSION_SUPPORTED="Version Supports Auth Secret Update"
authsecret_conversion()
{
	#******Authsecret Conversion
	new_fw_is_SV=$(grep -c $AUTH_SECRET_CONVERT_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c $AUTH_SECRET_CONVERT_SUPPORT $POSTINST)    # grep in postinst of Current fw
	
	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support

	if [ $cur_fw_is_SV -eq 0 ]; then
		#Forward Conversion
		if [ $new_fw_is_SV -gt 0 ]; then
			/mnt/fabos/libexec/auth_secretconvert 7.4 8.0 > /dev/null 2>&1  
			for f in /etc/fabos/auth.[0-7].conf
			do
			    if [ -e $f ]; then
				/bin/cp /mnt$f $f > /dev/null 2>&1
			    fi
			done
		fi
	fi
}

#RBAC_UPDATE_SUPPORTED="Version Supports RBAC Update"
rbac_conversion()
{
			if [ $ACTIVECP ]; then
				isActiveCp=1
			else
				isActiveCp=0
			fi

			pizza=`/fabos/bin/slotshow | grep -c "Not supported on this platform"`
			is_fwdl_arg "s"
			local singlemode=$?
			if [ $pizza -eq 0 -a $singlemode -ne 0 -a $isActiveCp -eq 0 ]; then
				bothCpUpdate=1
			else
				bothCpUpdate=0
			fi

			#Rbac and Userdb Update
				if [ "$bothCpUpdate" -eq 0 ]; then
					/bin/mv /etc/fabos/rbac/dynamic.default /etc/fabos/rbac/org_dynamic.default
					/bin/cp /mnt/etc/fabos/rbac/dynamic.default /etc/fabos/rbac/dynamic.default
					/fabos/libexec/trig_userdb_merge /mnt/etc/fabos/rbac/dynamic $FROM_MAJOR.$FROM_MINOR.$FROM_PATCH $TO_MAJOR.$TO_MINOR.$TO_PATCH
					/bin/cp /mnt/etc/fabos/rbac/dynamic /etc/fabos/rbac/dynamic
					/bin/mv /etc/fabos/rbac/org_dynamic.default /etc/fabos/rbac/dynamic.default
					if [ $pizza -ne 0 ]; then
						/fabos/cliexec/config save /etc/fabos/rbac/dynamic
					fi
				else
					correcthost_to_curr_vfid /bin/mv /etc/fabos/rbac/dynamic.default /etc/fabos/rbac/org_dynamic.default
					correcthost_to_curr_vfid /bin/mv /mnt/etc/fabos/rbac/dynamic.default /mnt/etc/fabos/rbac/org_dynamic.default
					/bin/rcp /mnt/etc/fabos/rbac/dynamic.default root@$(otherhost):/etc/fabos/rbac/dynamic.default
					/bin/rcp /mnt/etc/fabos/rbac/dynamic.default root@$(otherhost):/mnt/etc/fabos/rbac/dynamic.default
					correcthost_to_curr_vfid /fabos/libexec/trig_userdb_merge /mnt/etc/fabos/rbac/dynamic $FROM_MAJOR.$FROM_MINOR.$FROM_PATCH $TO_MAJOR.$TO_MINOR.$TO_PATCH
					correcthost_to_curr_vfid /bin/cp /mnt/etc/fabos/rbac/dynamic /etc/fabos/rbac/dynamic
					correcthost_to_curr_vfid /bin/mv /etc/fabos/rbac/org_dynamic.default /etc/fabos/rbac/dynamic.default
					correcthost_to_curr_vfid /bin/mv /mnt/etc/fabos/rbac/org_dynamic.default /mnt/etc/fabos/rbac/dynamic.default
					correcthost_to_curr_vfid /fabos/cliexec/config save /etc/fabos/rbac/dynamic
				fi
}

# Sync passwd file if / and /mnt have different files
# To resolve /passwd file overwrite during RPM installation
passwd_file_sync()
{
	#Passwd file sync
	primsum=`/usr/bin/md5sum /etc/passwd | /usr/bin/cut -d ' ' -f 1`
	secsum=`/usr/bin/md5sum /mnt/etc/passwd | /usr/bin/cut -d ' ' -f 1`
	if [ "$primsum" != "$secsum" ]; then
		/bin/cp /etc/passwd /mnt/etc/passwd
	fi
}

#
# Update supportlink default start date in v8.2.2 and above
#
update_supportlink_config()
{
	# Only perform supportlink update when upgrading to v8.2.2 (or above) from prior version
	if [ ${TO_MAJOR} -gt 8 ] || [ ${TO_MAJOR} -eq 8 -a ${TO_MINOR} -gt 2 ] || [ ${TO_MAJOR} -eq 8 -a ${TO_MINOR} -eq 2 -a ${TO_PATCH} -ge 2 ]; then
  	   FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
       FABOS_SWITCHNO=0

	   SL_SRCBM=`correcthost /fabos/cliexec/config get http.sl.cfgsourcebm 2`;
	   SL_STIME=`correcthost /fabos/cliexec/config get http.sl.starttime 2`;
       SL_PERIOD=`correcthost /fabos/cliexec/config get http.sl.period 2`;
       SL_SDATE=`correcthost /fabos/cliexec/config get http.sl.startdate 5`;

	   #If its an older release or source bitmask is available, return it. 
	   #The keys will be updated as part of default installation at the startup.
	   if [ "$SL_SRCBM" == "" ]; then
		  FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
          return $STS_OK
       fi
   
       #If its already set to new defaults, no changes required
       if [ "$SL_SDATE" == "06/01/2019" -a "$SL_PERIOD" == "1" -a "$SL_STIME" == "1" ]; then
		  FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
          return $STS_OK
       fi

	   # Bitmask for period and stime/sdate used in BSL module
       SL_CFG_PERIOD_BM=0x2
	   SL_CFG_STIME_BM=0x4
       SL_CFG_SDATE_BM=0x80

	   # Update period and date only for non-user configuration (profle/default).
	   # Period and date will go together and only if both of them are profile/default configured, will change upon upgrade. 
       if [ "$SL_SRCBM" == "0" ] || [ "$(($SL_SRCBM & $SL_CFG_PERIOD_BM))" -eq 0 -a "$(($SL_SRCBM & $SL_CFG_SDATE_BM))" -eq 0 -a "$(($SL_SRCBM & $SL_CFG_STIME_BM))" -eq 0 ]; then
			correcthost /fabos/cliexec/config set http.sl.period 2 1
			correcthost /fabos/cliexec/config set http.sl.starttime 2 1
			correcthost /fabos/cliexec/config set http.sl.startdate 5 "06/01/2019"
			correcthost /fabos/cliexec/config save
	    fi
		FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
	fi
}

maintenance_conversion() {

        new_fw_is_SV=$(grep -c "MAINTENANCE_SUPPORT" $MNT_POSTINST) # grep in postinst of New fw
        cur_fw_is_SV=$( grep -c "MAINTENANCE_SUPPORT" $POSTINST)    # grep in postinst of Current fw

        #Forward conversion
        if [ $cur_fw_is_SV -eq 0 -a $new_fw_is_SV -gt 0 ]; then

		# 'maintenance' will be added to passwd file during bootup in rcinit/fabos/ as a
		# workaround for legacy check_post_features.sh primary to secondary partition copy
		# of passwd file

		#shadow file conversion
		/usr/sbin/chroot /mnt /fabos/libexec/config_convert /etc/shadow FWDL_CONVERSION MAINTENANCE_ADDITION > /dev/null 2>&1

		#group file conversion
		/usr/sbin/chroot /mnt /fabos/libexec/group_convert /etc/group FWDL_CONVERSION MAINTENANCE_ADDITION > /dev/null 2>&1

		#user.db file conversion
		export VF_ENABLED=$VF_ENABLED
		/usr/sbin/chroot /mnt /fabos/libexec/dummy_trigger /etc/fabos/user.db FWDL_CONVERSION MAINTENANCE_ADDITION > /dev/null 2>&1

		if [ -d /mnt/fabos/users/maintenance ]; then
			/usr/sbin/chroot /mnt /bin/chown -R maintenance:maintenance /fabos/users/maintenance > /dev/null 2>&1
		fi

        #Backward conversion
        elif [ $new_fw_is_SV -eq 0 -a $cur_fw_is_SV -gt 0 ]; then

		#passwd file conversion
		/fabos/libexec/passwd_convert /mnt/etc/passwd FWDL_CONVERSION MAINTENANCE_REMOVAL > /dev/null 2>&1

		#shadow file conversion
		/fabos/libexec/config_convert /mnt/etc/shadow FWDL_CONVERSION MAINTENANCE_REMOVAL > /dev/null 2>&1

		#group file conversion
		/fabos/libexec/group_convert /mnt/etc/group FWDL_CONVERSION MAINTENANCE_REMOVAL > /dev/null 2>&1

		#user.db file conversion
		/fabos/libexec/dummy_trigger /mnt/etc/fabos/user.db FWDL_CONVERSION MAINTENANCE_REMOVAL > /dev/null 2>&1

		remove_svcexec_log

		#Temp code for 8.2.x group.default reference issue in downgrade (not applicable in releases that do not allow downgrade to lesser than 9.0)
                pizza=`/fabos/bin/slotshow | grep -c "Not supported on this platform"`
		is_fwdl_arg "s"
		local singlemode=$?
		if [ $pizza -eq 0 -a $singlemode -ne 0 ]; then
			if [ $ACTIVECP ]; then
				isActiveCp=1
			else
				isActiveCp=0
			fi
			if [ "$isActiveCp" -eq 1 ]; then
				/bin/cp /mnt/etc/group.default /etc/group.default
			else
				/bin/rcp /mnt/etc/group.default root@$(otherhost):/etc/group.default
				/bin/rcp /mnt/etc/group.default root@$(otherhost):/mnt/etc/group.default
			fi
		fi
        fi
}

ldaps_protocol_handling() {

	new_fw_is_SV=$(/bin/grep -c "LDAPS_SUPPORT" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$(/bin/grep -c "LDAPS_SUPPORT" $POSTINST)    # grep in postinst of Current fw

	LDAP_FILE="/etc/fabos/ldap.conf"
	CHASSIS_CONFIG="/etc/fabos/fabos.chassis.conf"
	MNT_LDAP_FILE="/mnt/etc/fabos/ldap.conf"
	MNT_CHASSIS_CONFIG="/mnt/etc/fabos/fabos.chassis.conf"
	TMP_FILE="/tmp/ldap"

	if [ ! -f $LDAP_FILE ]; then
		# LDAP servers not configured
		return
	fi

	#Downgrade
	if [ $new_fw_is_SV -eq 0 -a $cur_fw_is_SV -gt 0 ]; then
		while read line
		do
			columns=`echo $line | awk 'BEGIN{FS=" "};{print NF}'`
			if [ $columns -eq 4 -o $columns -eq 9 ]; then
				/bin/echo $line | /bin/awk '!($4="")' >> $TMP_FILE
			else 
				/bin/echo $line >> $TMP_FILE
			fi
		done < $LDAP_FILE
		mv $TMP_FILE $LDAP_FILE >/dev/null 2>&1

		while read line
		do
			columns=`echo $line | awk 'BEGIN{FS=" "};{print NF}'`
			if [ $columns -eq 4 -o $columns -eq 9 ]; then
				/bin/echo $line | /bin/awk '!($4="")' >> $TMP_FILE
			else 
				/bin/echo $line >> $TMP_FILE
			fi
		done < $MNT_LDAP_FILE
		mv $TMP_FILE $MNT_LDAP_FILE >/dev/null 2>&1

		/bin/sed '/ldap.server.*.tlsMode/d' $CHASSIS_CONFIG > $TMP_FILE
		mv $TMP_FILE $CHASSIS_CONFIG

		/bin/sed '/ldap.server.*.tlsMode/d' $MNT_CHASSIS_CONFIG > $TMP_FILE
		mv $TMP_FILE $MNT_CHASSIS_CONFIG
	fi
}

# Taggged features Post install updates begin here for Forward Conversion:

#******UID Conversion
uid_conversion

#******Invalid Accts Conversion
invalid_accounts_conversion

#******DefAcct Passwd Conversion
default_account_passwd_update

#******Factory Conversion
factory_conversion

#******File Permission Updates	
file_permission_modifications

#******Passwd hash/Passwd files Conversion
passwd_hash_conversion

#******Root access update	
root_access_update

#******Cipherkey removal	
cipher_key_update

#******Setting the LDAP ciphers 
ldap_cipher_update	

#******Handle Pam conf
pam_conf_conversion

#******Authsecret Conversion
authsecret_conversion

#******Rbac db Update
rbac_conversion

#*******SSH host key conversion
ssh_hostkey_conversion

#*******Disable IPSec on standby CP
ipsec_disable_conversion

#******* BSL Starttime/date updates from v8.2.2
update_supportlink_config

#Upgrade from <8.2.1 to 8.2.1
        # If user defined role is exists in the switch then those roles
        # will be mapped to the udrole in the group file
if [  $FROM_MAJOR -eq 8 -a $FROM_MINOR -lt 2 ] || [ $FROM_MAJOR -eq 8 -a $FROM_MINOR -eq 2 -a $FROM_PATCH -lt 1 ]; then
        if [ $TO_MAJOR -gt 8 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -gt 2 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 2 -a $TO_PATCH -ge 1 ]; then

			pizza=`/fabos/bin/slotshow | grep -c "Not supported on this platform"`
			if [ $ACTIVECP ]; then
				isActiveCp=1
			else
				isActiveCp=0
			fi
			udrolecount=`cat /etc/group | grep ::7 | /bin/sed 's/::7.*//' | /bin/sed -r '$!s/$/\,/' | tr -d '\n' | wc -c`
			if [ $udrolecount -gt 0 ]; then
				if [ "$pizza" -ne 0 -o "$isActiveCp" -eq 1 ]; then
					udr=`cat /etc/group | grep ::7 | /bin/sed 's/::7.*//' | /bin/sed -r '$!s/$/\,/' | tr -d '\n'`
					udrole=`echo $udr,`
					udrolemem=`cat /etc/group | grep udrole | /bin/sed 's/udrole::550://'`
					echo $udrole >> /tmp/udgroup
					echo $udrolemem >> /tmp/udgroup
					udlist=`cat /tmp/udgroup | tr , '\n' | sort | /bin/sed '$!N; /^\(.*\)\n\1$/!P; D' | /bin/sed -r '$!s/$/\,/' | tr -d '\n' | /bin/sed 's/^/udrole::550:/'`
					/bin/sed 's/.*udrole::550:.*/'"$udlist"'/' /etc/group > /tmp/group
					/bin/cp /tmp/group /etc/group
					/bin/rm /tmp/udgroup
					/bin/rm /tmp/group
				else
					/bin/rcp root@$(otherhost):/mnt/etc/group /tmp/groupAcp
					udr=`cat /tmp/groupAcp | grep ::7 | /bin/sed 's/::7.*//' | /bin/sed -r '$!s/$/\,/' | tr -d '\n'`
					udrole=`echo $udr,`
					udrolemem=`cat /tmp/groupAcp | grep udrole | /bin/sed 's/udrole::550://'`
					echo $udrole >> /tmp/udgroup
					echo $udrolemem >> /tmp/udgroup
					udlist=`cat /tmp/udgroup | tr , '\n' | sort | /bin/sed '$!N; /^\(.*\)\n\1$/!P; D' | /bin/sed -r '$!s/$/\,/' | tr -d '\n' | /bin/sed 's/^/udrole::550:/'`
					/bin/sed 's/.*udrole::550:.*/'"$udlist"'/' /etc/group > /tmp/group
					/bin/rcp /tmp/group root@$(otherhost):/etc/group
					/bin/rcp /tmp/group root@$(otherhost):/mnt/etc/group
					/bin/rm /tmp/groupAcp
					/bin/rm /tmp/udgroup
					/bin/rm /tmp/group
				fi
			fi
		fi
	correcthost /fabos/cliexec/config save /etc/group
	correcthost /fabos/cliexec/config save /mnt/etc/group
fi

#Upgrade from <8.2.0 to >=8.2.0
if [ $FROM_MAJOR -lt 8 ] || [ $FROM_MAJOR -eq 8 -a $FROM_MINOR -lt 2 ]; then
        if [ $TO_MAJOR -gt 8 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -gt 2 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 2 -a $TO_PATCH -ge 0 ]; then

		# "config get" for fips mode returns value only if called from
		# default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
		# revert it back to its original value after "config get"
		FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		FABOS_SWITCHNO=0

		# FIPS mode is not supported in 8.2.
		# Disabling the mode if enabled.
		fipsmode=`/fabos/cliexec/config get fips.mode 2`
		if [ $fipsmode -eq 1 ]; then
			correcthost_to_curr_vfid /fabos/cliexec/config set fips.mode 2 0
			correcthost_to_curr_vfid /fabos/cliexec/configcommit
		fi
	
		FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
	fi
fi


#Upgrade from <8.1.0 to >=8.1.0
if [ $FROM_MAJOR -lt 8 ] || [ $FROM_MAJOR -eq 8 -a $FROM_MINOR -lt 1 ]; then
	if [ $TO_MAJOR -gt 8 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -gt 1 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 1 -a $TO_PATCH -ge 0 ]; then
		# Setting log.msg to yes in case of upgrade
		correcthost_to_curr_vfid /fabos/cliexec/config set log.msg 5 yes
		/fabos/cliexec/config update

		# Enable simulate if fips force was set in FROM version.
		checkFipsForceMode
		retVal=$?
		if [ $retVal -eq 1 ]; then
			echo "FIPS force Mode active"
		        # "config get" for fips mode returns value only if called from
		        # default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
		        # revert it back to its original value after "config get"
		        FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		        FABOS_SWITCHNO=0
			correcthost_to_curr_vfid /fabos/cliexec/config set fips.mode 2 0
			correcthost_to_curr_vfid /fabos/cliexec/config set fips.simulate 2 1
			correcthost_to_curr_vfid /fabos/cliexec/configcommit
		        FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			
			echo "Warning: Please disable FIPS simulate mode and re-enable after firmware download completes."
		fi
	fi
fi

if [ $TO_MAJOR -le 8 -a $TO_MINOR -lt 1 ]; then

        cnt=`/fabos/bin/configshow -all | grep auditlog.quiettime | wc -l`
        if [ $cnt -eq 4 ]; then
                /fabos/cliexec/config remove auditlog.quiettime.enable
                /fabos/cliexec/config remove auditlog.quiettime.starttime
                /fabos/cliexec/config remove auditlog.quiettime.endtime
                /fabos/cliexec/config remove auditlog.quiettime.dow
                /fabos/cliexec/configcommit;
        fi

        cnt=`/fabos/bin/configshow -all | grep raslog.quiettime | wc -l`
        if [ $cnt -eq 4 ]; then
                /fabos/cliexec/config remove raslog.quiettime.enable
                /fabos/cliexec/config remove raslog.quiettime.starttime
                /fabos/cliexec/config remove raslog.quiettime.endtime
                /fabos/cliexec/config remove raslog.quiettime.dow
                /fabos/cliexec/configcommit;
        fi

fi


#Downgrade from >= 8.2.0 to < 8.2.0
if [ $FROM_MAJOR -gt 8 ] || [ $FROM_MAJOR -eq 8 -a $FROM_MINOR -ge 2 ]; then
    if [ $TO_MAJOR -lt 8 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -lt 2 ]; then
        # Remove ficud log files that have changed format in 8.2.0
                rm -f /var/log/sw*/C4_payload_log
                rm -f /mnt/var/log/sw*/C4_payload_log

    fi
fi

#Downgrade from >= 9.0.0 to < 9.0.0
if [ $FROM_MAJOR -ge 9 ]; then
    if [ $TO_MAJOR -lt 9 ]; then
        # Remove ficud log files that have changed format in 9.0.0
                rm -f /var/log/sw*/C4_event_log
                rm -f /mnt/var/log/sw*/C4_event_log
                rm -f /var/log/sw*/DD_error_log
                rm -f /mnt/var/log/sw*/DD_error_log
                rm -f /var/log/sw*/HealthCheck_log
                rm -f /mnt/var/log/sw*/HealthCheck_log
                rm -f /var/log/sw*/FICU_DBG_Log
                rm -f /mnt/var/log/sw*/FICU_DBG_Log
                rm -f /var/log/sw*/FICU_MAPS_Log
                rm -f /mnt/var/log/sw*/FICU_MAPS_Log
				rm -f /etc/fabos/ficu.conf.log.*
				rm -f /mnt/etc/fabos/ficu.conf.log.*

		# Remove ge port persistent disable reason string from config DB while downgrade from 9.0
		for key in `/fabos/bin/configshow | grep -i geportCfgDisableReason. | cut -f 1 -d ':'`
		do
			/fabos/cliexec/config remove $key
			correcthost /fabos/cliexec/config remove $key
		done
		/fabos/cliexec/config update;
	fi
fi

#Upgrade from < 9.0.0 to >= 9.0.0
if [ $FROM_MAJOR -lt 9 ]; then
    if [ $TO_MAJOR -ge 9 ]; then
        # Remove ficud log files that have changed format in 9.0.0
                rm -f /var/log/sw*/C4_event_log
                rm -f /mnt/var/log/sw*/C4_event_log
                rm -f /var/log/sw*/DD_error_log
                rm -f /mnt/var/log/sw*/DD_error_log
                rm -f /var/log/sw*/HealthCheck_log
                rm -f /mnt/var/log/sw*/C4_event_log
                rm -f /var/log/sw*/FICU_DBG_Log
                rm -f /mnt/var/log/sw*/FICU_DBG_Log
                rm -f /var/log/sw*/FICU_MAPS_Log
                rm -f /mnt/var/log/sw*/FICU_MAPS_Log
				rm -f /etc/fabos/ficu.conf.log.*
				rm -f /mnt/etc/fabos/ficu.conf.log.*
		# Consider to do this in 9.0.1		
	        # Remove trace.ftp.port left from 9.0.0 -> pre-9.0.0 -> 9.0.0
		#current_context=$CURRENT_VF;
		#context_switch $def_vf_id;
	        #ftp_port=`/fabos/cliexec/config get trace.ftp.port 2`
		#context_switch $current_context;
		#if [ "$ftp_port" != "" ]; then
#		    $ECHO "found ftp_port=$ftp_port, remove it"
		#    correcthost_to_DS /fabos/cliexec/config remove "trace.ftp.port"
		#    correcthost_to_DS /fabos/cliexec/config update
		#fi
    fi
fi


ffdc_config

# handling the updating of /etc/hosts
#

/mnt/fabos/libexec/hosts_convert

comp_file /mnt/etc/passwd.rpmnew /mnt/etc/passwd.default
DIFF_PWD=$?
if [ $DIFF_PWD == "0" ]; then
	$ECHO "cleaning up /mnt/etc/passwd.rpmnew"
	rm /mnt/etc/passwd.rpmnew
fi


#
# After a netinstall, there are different private-public keys,
# we would copy from the active partition to secondary.
#
if [ -f "/etc/ssh_host_rsa_key" ]; then
	cp /etc/ssh_host_rsa_key /mnt/etc/ssh_host_rsa_key
fi

if [ -f "/etc/ssh_host_rsa_key.pub" ]; then
	cp /etc/ssh_host_rsa_key.pub /mnt/etc/ssh_host_rsa_key.pub
fi

if [ -f "/etc/ssh_host_dsa_key" ]; then
	cp /etc/ssh_host_dsa_key /mnt/etc/ssh_host_dsa_key
fi

if [ -f "/etc/ssh_host_dsa_key.pub" ];then
	cp /etc/ssh_host_dsa_key.pub /mnt/etc/ssh_host_dsa_key.pub
fi


remove_snmp_config_key()
{
	/fabos/bin/configshow | grep -qi snmp.64mibCap.ISCSI-MIB
	if [ $? -eq 0 ]; then
		/fabos/cliexec/config remove snmp.64mibCap.ISCSI-MIB
	fi
	/fabos/bin/configshow | grep -qi snmp.64mibCap.BD-MIB
        if [ $? -eq 0 ]; then
                /fabos/cliexec/config remove snmp.64mibCap.BD-MIB
        fi
	snmpMibCap=`correcthost /fabos/cliexec/config get snmp.mibCap 2`
	mask=0x91000
        let "snmpMibCap=snmpMibCap & ~mask"
	correcthost /fabos/cliexec/config set snmp.mibCap 2 $snmpMibCap
        correcthost /fabos/cliexec/configcommit;
	
}

remove_snmpv3_users()
{
	i=6
    while [ $i -lt 12 ]; do
		user=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Usm.$i`
        if [ "$user" ]; then
			if [ $i -ge 6 ]; then
				auth_priv_flag=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Usm.$i.usmAuthPrivEncFlag | cut -f 4 -d'.' | cut -f 1 -d':'`
				if [ "$auth_priv_flag" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmAuthPrivEncFlag
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmAuthPrivEncFlag.default
				fi
				auth_prot=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Usm.$i.usmAuthProtocol | cut -f 4 -d'.' | cut -f 1 -d':'`
				if [ "$auth_prot" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmAuthProtocol
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmAuthProtocol.default
				fi
				auth_secr=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Usm.$i.usmAuthSecret | cut -f 4 -d'.' | cut -f 1 -d':'`
				if [ "$auth_secr" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmAuthSecret
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmAuthSecret.default
				fi
				usm_index=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Usm.$i.usmIndex | cut -f 4 -d'.' | cut -f 1 -d':'`
				if [ "$usm_index" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmIndex
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmIndex.default
				fi
				priv_prot=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Usm.$i.usmPrivProtocol | cut -f 4 -d'.' | cut -f 1 -d':'`
				if [ "$priv_prot" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmPrivProtocol
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmPrivProtocol.default
				fi
				priv_secr=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Usm.$i.usmPrivSecret | cut -f 4 -d'.' | cut -f 1 -d':'`
				if [ "$priv_secr" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmPrivSecret
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmPrivSecret.default
				fi
				user_name=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Usm.$i.usmUserName | cut -f 4 -d'.' | cut -f 1 -d':'`
				if [ "$user_name" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmUserName
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$i.usmUserName.default
				fi
				usm_auth_key=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Keys.$i.usmAuthKey | cut -f 4 -d'.' | cut -f 1 -d':'`
				if [ "$usm_auth_key" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Keys.$i.usmAuthKey
				fi
				auth_key_size=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Keys.$i.usmAuthKeySize | cut -f 4 -d'.' | cut -f 1 -d':'`
				if [ "$auth_key_size" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Keys.$i.usmAuthKeySize
				fi
				usm_priv_key=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Keys.$i.usmPrivKey | cut -f 4 -d'.' | cut -f 1 -d':'`
				if [ "$usm_priv_key" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Keys.$i.usmPrivKey
				fi
				priv_key_size=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Keys.$i.usmPrivKeySize | cut -f 4 -d'.' | cut -f 1 -d':'`
				if [ "$priv_key_size" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Keys.$i.usmPrivKeySize
				fi
				mgr_eng_id=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.mgrengineId.$i | cut -f 3 -d'.' | cut -f 1 -d':'`
				if [ "$mgr_eng_id" ] ; then
					correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.mgrengineId.$i
				fi
			fi
		fi
		i=`expr $i + 1`
	done
	/fabos/cliexec/configcommit ;
}

remove_snmp_group_users_config_key()
{
    date > /tmp/snmp_users_remove.txt
    CONFIGSHOW -all >> /tmp/snmp_users_remove.txt

    j=0
    while [ $j -lt 12 ]; do
		user_access=`/bin/cat /tmp/snmp_users_remove.txt | grep -i snmp.snmpv3Usm.$j.userAccessLevel`
		if [ "$user_access" ] ; then
			correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.snmpv3Usm.$j.userAccessLevel
		fi
		j=`expr $j + 1`
	done
	j=0
	while [ $j -lt 6 ]; do
		comm_access=`/bin/cat /tmp/snmp_users_remove.txt| grep -i snmp.agtParty.$j.commAccessLevel`
		if [ "$comm_access" ] ; then
			correcthost_to_curr_vfid /fabos/cliexec/config remove snmp.agtParty.$j.commAccessLevel
		fi
		j=`expr $j + 1`
	done
	remove_snmpv3_users ;
        rm -rf /tmp/snmp_users_remove.txt
}

set_snmp_default_values()
{
	declare -a snmp_community=("Secret C0de" "OrigEquipMfr" "private" "public" "common" "FibreChannel")
	declare -a snmp_user=("snmpadmin1" "snmpadmin2" "snmpadmin3" "snmpuser1" "snmpuser2" "snmpuser3")
	
	for (( i = 0; i < 6; i++ ))
	do
		def_comm=${snmp_community[i]}
		comm_name=`/fabos/cliexec/config get snmp.agtParty.$i.authPrivSecret 5`
                if [ $i -eq 0 ]; then
                        if [ $STANDBYCP -eq 1 ]; then
                               # due to the space in the community string, it is consider as two strings
                                # and through wrong error as number of argument while doing config set rsh.
                                # So the "Secret C0de" is handled for standby CP seperately.
                                def_comm=$"Secret\ C0de"
                        fi
                fi
		correcthost_to_curr_vfid /fabos/cliexec/config set snmp.agtParty.$i.authPrivSecret.default 5 "$def_comm"
		if [ -z "$comm_name" ] ; then
			correcthost_to_curr_vfid /fabos/cliexec/config set snmp.agtParty.$i.authPrivSecret 5 "$def_comm"
		fi
	done
	for (( i = 0; i < 6; i++ ))
	do
		def_user=${snmp_user[i]}
		v3user_name=`/fabos/cliexec/config get snmp.snmpv3Usm.$i.usmUserName 5`
		correcthost_to_curr_vfid /fabos/cliexec/config set snmp.snmpv3Usm.$i.usmUserName.default 5 "$def_user"
		if [ -z "$v3user_name" ] ; then
			correcthost_to_curr_vfid /fabos/cliexec/config set snmp.snmpv3Usm.$i.usmUserName 5 "$def_user"
		fi
	done
}

remove_apm_config_keys_in_all_contexts()
{
	# Check for Virtual Fabrics
	check_vf_enabled
	if [ $? -ne $STS_OK ]; then
		if [ $ACTIVECP ]; then
			CHASSISCMD="cmd_chassis" ;
			current_context=$CURRENT_VF ;
			for_all_contexts remove_apm_config_keys ;
			context_switch $current_context ;
		else
			for_all_contexts_standby remove_apm_config_keys ;
		fi
	else
		remove_apm_config_keys ;
	fi
}

remove_apm_config_keys()
{

	# For TTmon and EEmon configurations on the base switch remove the
	# keys on the active CP, so they don't get synced when
	# firmwaredownload is done on the standby 
	BASE=`correcthost_to_curr_vfid /fabos/bin/switchshow | grep "Base Switch:" | cut -d ' ' -f 6 | cut -d ',' -f 1`
	if [ "$BASE" == "Yes" ]; then
		for key in `/fabos/bin/configshow | grep "perf.eemonc\." | cut -f 1 -d':'`
		do
			correcthost_to_curr_vfid /fabos/cliexec/config remove $key
		done

		for key in `/fabos/bin/configshow | grep "perf.ttmonc" | cut -f 1 -d ':'`
		do
			correcthost_to_curr_vfid /fabos/cliexec/config remove $key
		done
		correcthost_to_curr_vfid /fabos/cliexec/configcommit
	fi

	for  key in `/fabos/bin/configshow | grep "perf\." | cut -f 1 -d':'`
	do		
		str=`echo $key | cut -f 1 -d '.'`
		if [ "$str" == "perf" ]; then
			/fabos/cliexec/config remove $key
		fi
	done
	/fabos/cliexec/configcommit ;
}

add_ag_fporttrunking_key()
{
	/fabos/bin/configshow | grep -q ag.fporttrunking

	if [ $? -ne $STS_OK ]; then
		/fabos/cliexec/config set ag.fporttrunking 2 0
		/fabos/cliexec/configcommit ;
	fi
}

####MAPS
swbd=`sin | awk ' {print $2} ' | grep SWBD | sed 's@,@@'`

#touch fileName

#################################### MAPS obsolete, deprecated, unwanted rules database ############

# rules database <existing-rule-name>: 1 or <new-rule-name>
# if the script sees 1 instead of <new-rule-name> then it would delete old rule from user
# configuration.

# keeps rule database per feature so it would be easy to track
####################################################################################################

#### PS rules
psRulesList=("defCHASSISBAD_PWR_MARG:defCHASSISBAD_PWR_CRIT:740")

## These rules defintion is only applicable to Tomtoo platform.
psFanRulesList=("defCHASSISBAD_PWR_MARG:1:0" "defCHASSISBAD_PWR_CRIT:1:0" "defCHASSISBAD_FAN_MARG:1:0" "defCHASSISBAD_FAN_CRIT:1:0")

#### PS rules
fcrRulesList=("defSWITCHBB_FCR_CNT_12:defSWITCHBB_FCR_CNT_MAX:810")

#### Back end port rules
beRulesList=("defALL_BE_PORTSBAD_OS_5M_10:1:0" "defALL_BE_PORTSBAD_OS_D_100:1:0" "defALL_BE_PORTSCRC_5M_10:1:0" "defALL_BE_PORTSCRC_D_100:1:0" "defALL_BE_PORTSFRM_LONG_5M_10:1:0" "defALL_BE_PORTSFRM_LONG_D_100:1:0" "defALL_BE_PORTSFRM_TRUNC_5M_10:1:0" "defALL_BE_PORTSFRM_TRUNC_D_100:1:0" "defALL_BE_PORTSITW_5M_10:1:0" "defALL_BE_PORTSITW_D_100:1:0" "defALL_BE_PORTSLR_5M_10:1:0" "defALL_BE_PORTSLR_D_100:1:0" "defALL_BE_PORTS_LATENCY_CLEAR:1:0" "defALL_BE_PORTS_LATENCY_IMPACT:1:0")

# FAN rules
fanRulesList=("defALL_FAN_AIR_FLOW_MISMATCH:1:900")

# ENCR rules
encrRulesList=("defALL_E_PORTSENCR_BLK:1:900" "defALL_E_PORTSENCR_DISC:1:900" "defALL_E_PORTSENCR_SHORT_FRM:1:900")

#### SFP rules
sfpRulesList=("defALL_PORTSSFP_STATE_ON:1:0")

#### FCIP rules
fcipRulesList=("defALL_CIRCUITSCIR_PKTLOSS_PER_05:1:0" "defALL_CIRCUITSCIR_PKTLOSS_PER_1:1:0" "defALL_CIRCUITSCIR_PKTLOSS_PER_5:1:0" "defALL_CIRCUITSCIR_STATE_0:1:0" "defALL_CIRCUITSCIR_STATE_3:1:0" "defALL_CIRCUITSCIR_STATE_5:1:0" "defALL_CIRCUITSCIR_UTIL_60:1:0" "defALL_CIRCUITSCIR_UTIL_75:1:0" "defALL_CIRCUITSCIR_UTIL_90:1:0" "defALL_CIRCUITS_JITTER_PER_05:1:0" "defALL_CIRCUITS_JITTER_PER_15:1:0" "defALL_CIRCUITS_JITTER_PER_20:1:0" "defALL_CIRCUITS_RTT_250:1:0" "defALL_CIRCUIT_F_QOS_PKTLOSS_PER_05:1:0" "defALL_CIRCUIT_F_QOS_PKTLOSS_PER_1:1:0" "defALL_CIRCUIT_F_QOS_PKTLOSS_PER_5:1:0" "defALL_CIRCUIT_F_QOS_UTIL_PER_50:1:0" "defALL_CIRCUIT_F_QOS_UTIL_PER_75:1:0" "defALL_CIRCUIT_F_QOS_UTIL_PER_90:1:0" "defALL_CIRCUIT_HIGH_QOS_PKTLOSS_PER_05:1:0" "defALL_CIRCUIT_HIGH_QOS_PKTLOSS_PER_1:1:0" "defALL_CIRCUIT_HIGH_QOS_PKTLOSS_PER_5:1:0" "defALL_CIRCUIT_HIGH_QOS_UTIL_PER_50:1:0" "defALL_CIRCUIT_HIGH_QOS_UTIL_PER_75:1:0" "defALL_CIRCUIT_HIGH_QOS_UTIL_PER_90:1:0" "defALL_CIRCUIT_LOW_QOS_PKTLOSS_PER_05:1:0" "defALL_CIRCUIT_LOW_QOS_PKTLOSS_PER_1:1:0" "defALL_CIRCUIT_LOW_QOS_PKTLOSS_PER_5:1:0" "defALL_CIRCUIT_LOW_QOS_UTIL_PER_50:1:0" "defALL_CIRCUIT_LOW_QOS_UTIL_PER_75:1:0" "defALL_CIRCUIT_LOW_QOS_UTIL_PER_90:1:0" "defALL_CIRCUIT_MED_QOS_PKTLOSS_PER_05:1:0" "defALL_CIRCUIT_MED_QOS_PKTLOSS_PER_1:1:0" "defALL_CIRCUIT_MED_QOS_PKTLOSS_PER_5:1:0" "defALL_CIRCUIT_MED_QOS_UTIL_PER_50:1:0" "defALL_CIRCUIT_MED_QOS_UTIL_PER_75:1:0" "defALL_CIRCUIT_MED_QOS_UTIL_PER_90:1:0" "defALL_EXT_GE_PORTSCRC_10:1:0" "defALL_EXT_GE_PORTSCRC_20:1:0" "defALL_EXT_GE_PORTSCRC_5:1:0" "defALL_EXT_GE_PORTSLOS_10:1:0" "defALL_EXT_GE_PORTSLOS_20:1:0" "defALL_EXT_GE_PORTSLOS_5:1:0" "defALL_TUNNELSSTATE_CHG_0:1:0" "defALL_TUNNELSSTATE_CHG_1:1:0" "defALL_TUNNELSSTATE_CHG_3:1:0" "defALL_TUNNELSUTIL_PER_50:1:0" "defALL_TUNNELSUTIL_PER_75:1:0" "defALL_TUNNELSUTIL_PER_90:1:0" "defALL_TUNNEL_F_QOS_PKTLOSS_PER_05:1:0" "defALL_TUNNEL_F_QOS_PKTLOSS_PER_1:1:0" "defALL_TUNNEL_F_QOS_PKTLOSS_PER_5:1:0" "defALL_TUNNEL_F_QOS_UTIL_PER_50:1:0" "defALL_TUNNEL_F_QOS_UTIL_PER_75:1:0" "defALL_TUNNEL_F_QOS_UTIL_PER_90:1:0" "defALL_TUNNEL_HIGH_QOS_PKTLOSS_PER_05:1:0" "defALL_TUNNEL_HIGH_QOS_PKTLOSS_PER_1:1:0" "defALL_TUNNEL_HIGH_QOS_PKTLOSS_PER_5:1:0" "defALL_TUNNEL_HIGH_QOS_UTIL_PER_50:1:0" "defALL_TUNNEL_HIGH_QOS_UTIL_PER_75:1:0" "defALL_TUNNEL_HIGH_QOS_UTIL_PER_90:1:0" "defALL_TUNNEL_LOW_QOS_PKTLOSS_PER_05:1:0" "defALL_TUNNEL_LOW_QOS_PKTLOSS_PER_1:1:0" "defALL_TUNNEL_LOW_QOS_PKTLOSS_PER_5:1:0" "defALL_TUNNEL_LOW_QOS_UTIL_PER_50:1:0" "defALL_TUNNEL_LOW_QOS_UTIL_PER_75:1:0" "defALL_TUNNEL_LOW_QOS_UTIL_PER_90:1:0" "defALL_TUNNEL_MED_QOS_PKTLOSS_PER_05:1:0" "defALL_TUNNEL_MED_QOS_PKTLOSS_PER_1:1:0" "defALL_TUNNEL_MED_QOS_PKTLOSS_PER_5:1:0" "defALL_TUNNEL_MED_QOS_UTIL_PER_50:1:0" "defALL_TUNNEL_MED_QOS_UTIL_PER_75:1:0" "defALL_TUNNEL_MED_QOS_UTIL_PER_90:1:0" "defALL_CIRCUITSCIR_PKTLOSS_PER_01:1:0" "defALL_EXT_GE_PORTSINV_LEN_0:1:0" "defALL_EXT_GE_PORTSINV_LEN_1:1:0")

#### extension rules
extnRulesList=("defALL_CIRCUITS_IP_JITTER_PER_05:1:0" "defALL_CIRCUITS_IP_JITTER_PER_15:1:0" "defALL_CIRCUITS_IP_JITTER_PER_20:1:0" "defALL_CIRCUITS_IP_PKTLOSS_P_05:1:0" "defALL_CIRCUITS_IP_PKTLOSS_P_1:1:0" "defALL_CIRCUITS_IP_PKTLOSS_P_5:1:0" "defALL_CIRCUITS_IP_RTT_250:1:0" "defALL_CIRCUITS_IP_UTIL_P_60:1:0" "defALL_CIRCUITS_IP_UTIL_P_75:1:0" "defALL_CIRCUITS_IP_UTIL_P_90:1:0" "defALL_CIRCUIT_IP_HIGH_QOS_PKTLOSS_P_05:1:0" "defALL_CIRCUIT_IP_HIGH_QOS_PKTLOSS_P_1:1:0" "defALL_CIRCUIT_IP_HIGH_QOS_PKTLOSS_P_5:1:0" "defALL_CIRCUIT_IP_HIGH_QOS_UTIL_P_50:1:0" "defALL_CIRCUIT_IP_HIGH_QOS_UTIL_P_75:1:0" "defALL_CIRCUIT_IP_HIGH_QOS_UTIL_P_90:1:0" "defALL_CIRCUIT_IP_LOW_QOS_PKTLOSS_P_05:1:0" "defALL_CIRCUIT_IP_LOW_QOS_PKTLOSS_P_1:1:0" "defALL_CIRCUIT_IP_LOW_QOS_PKTLOSS_P_5:1:0" "defALL_CIRCUIT_IP_LOW_QOS_UTIL_P_50:1:0" "defALL_CIRCUIT_IP_LOW_QOS_UTIL_P_75:1:0" "defALL_CIRCUIT_IP_LOW_QOS_UTIL_P_90:1:0" "defALL_CIRCUIT_IP_MED_QOS_PKTLOSS_P_05:1:0" "defALL_CIRCUIT_IP_MED_QOS_PKTLOSS_P_1:1:0" "defALL_CIRCUIT_IP_MED_QOS_PKTLOSS_P_5:1:0" "defALL_CIRCUIT_IP_MED_QOS_UTIL_P_50:1:0" "defALL_CIRCUIT_IP_MED_QOS_UTIL_P_75:1:0" "defALL_CIRCUIT_IP_MED_QOS_UTIL_P_90:1:0" "defALL_TUNNELS_IP_UTIL_P_50:1:0" "defALL_TUNNELS_IP_UTIL_P_75:1:0" "defALL_TUNNELS_IP_UTIL_P_90:1:0" "defALL_TUNNEL_IP_HIGH_QOS_PKTLOSS_P_05:1:0" "defALL_TUNNEL_IP_HIGH_QOS_PKTLOSS_P_1:1:0" "defALL_TUNNEL_IP_HIGH_QOS_PKTLOSS_P_5:1:0" "defALL_TUNNEL_IP_HIGH_QOS_UTIL_P_50:1:0" "defALL_TUNNEL_IP_HIGH_QOS_UTIL_P_75:1:0" "defALL_TUNNEL_IP_HIGH_QOS_UTIL_P_90:1:0" "defALL_TUNNEL_IP_LOW_QOS_PKTLOSS_P_05:1:0" "defALL_TUNNEL_IP_LOW_QOS_PKTLOSS_P_1:1:0" "defALL_TUNNEL_IP_LOW_QOS_PKTLOSS_P_5:1:0" "defALL_TUNNEL_IP_LOW_QOS_UTIL_P_50:1:0" "defALL_TUNNEL_IP_LOW_QOS_UTIL_P_75:1:0" "defALL_TUNNEL_IP_LOW_QOS_UTIL_P_90:1:0" "defALL_TUNNEL_IP_MED_QOS_PKTLOSS_P_05:1:0" "defALL_TUNNEL_IP_MED_QOS_PKTLOSS_P_1:1:0" "defALL_TUNNEL_IP_MED_QOS_PKTLOSS_P_5:1:0" "defALL_TUNNEL_IP_MED_QOS_UTIL_P_50:1:0" "defALL_TUNNEL_IP_MED_QOS_UTIL_P_75:1:0" "defALL_TUNNEL_IP_MED_QOS_UTIL_P_90:1:0")


#D Port
dPortRulesList=("defALL_D_PORTSLF_1:1:0" "defALL_D_PORTSLF_H30:1:0" "defALL_D_PORTSLF_D500:1:0"  "defALL_D_PORTSLF_2:1:0" "defALL_D_PORTSLF_H60:1:0"  "defALL_D_PORTSLF_D1000:1:0" "defALL_D_PORTSLF_3:1:0"  "defALL_D_PORTSLF_H90:1:0" "defALL_D_PORTSLF_D1500:1:0")


dLfRulesList=("defALL_D_PORTSLF_1:defALL_PORTSLF_1:810" "defALL_D_PORTSLF_2:defALL_PORTSLF_2:810"  "defALL_D_PORTSLF_3:defALL_PORTSLF_3:810")

portLfRulesList=("defALL_HOST_PORTSLF_0:defALL_PORTSLF_0:800" "defALL_HOST_PORTSLF_3:defALL_PORTSLF_3:800" "defALL_HOST_PORTSLF_5:defALL_PORTSLF_5:800" "defALL_OTHER_F_PORTSLF_0:defALL_PORTSLF_0:800" "defALL_OTHER_F_PORTSLF_3:defALL_PORTSLF_3:800" "defALL_OTHER_F_PORTSLF_5:defALL_PORTSLF_5:800" "defALL_TARGET_PORTSLF_0:defALL_PORTSLF_0:800" "defALL_TARGET_PORTSLF_3:defALL_PORTSLF_3:800" "defALL_TARGET_PORTSLF_5:defALL_PORTSLF_5:800" "defNON_E_F_PORTSLF_0:defALL_PORTSLF_0:800" "defNON_E_F_PORTSLF_3:defALL_PORTSLF_3:800" "defNON_E_F_PORTSLF_5:defALL_PORTSLF_5:800" "defALL_E_PORTSLF_0:defALL_PORTSLF_0:800" "defALL_E_PORTSLF_3:defALL_PORTSLF_3:800" "defALL_E_PORTSLF_5:defALL_PORTSLF_5:800")

#TODO No rules (r2) found in all release for below one
dLsignalRulesList=("defALL_D_PORTSLOSS_SIGNAL_1:defALL_PORTSLOSS_SIGNAL_1:800" "defALL_D_PORTSLOSS_SIGNAL_2:defALL_PORTSLOSS_SIGNAL_2:800" "defALL_D_PORTSLOSS_SIGNAL_3:defALL_PORTSLOSS_SIGNAL_3:800")

portLsignalRulesList=("defALL_HOST_PORTSLOSS_SIGNAL_0:defALL_PORTSLOSS_SIGNAL_0:810" "defALL_HOST_PORTSLOSS_SIGNAL_3:defALL_PORTSLOSS_SIGNAL_3:810" "defALL_HOST_PORTSLOSS_SIGNAL_5:defALL_PORTSLOSS_SIGNAL_5:810" "defALL_OTHER_F_PORTSLOSS_SIGNAL_0:defALL_PORTSLOSS_SIGNAL_0:810" "defALL_OTHER_F_PORTSLOSS_SIGNAL_3:defALL_PORTSLOSS_SIGNAL_3:810" "defALL_OTHER_F_PORTSLOSS_SIGNAL_5:defALL_PORTSLOSS_SIGNAL_5:810" "defALL_TARGET_PORTSLOSS_SIGNAL_0:defALL_PORTSLOSS_SIGNAL_0:810" "defALL_TARGET_PORTSLOSS_SIGNAL_3:defALL_PORTSLOSS_SIGNAL_3:810" "defALL_TARGET_PORTSLOSS_SIGNAL_5:defALL_PORTSLOSS_SIGNAL_5:810" "defNON_E_F_PORTSLOSS_SIGNAL_0:defALL_PORTSLOSS_SIGNAL_0:810" "defNON_E_F_PORTSLOSS_SIGNAL_3:defALL_PORTSLOSS_SIGNAL_3:810" "defNON_E_F_PORTSLOSS_SIGNAL_5:defALL_PORTSLOSS_SIGNAL_5:810" "defALL_E_PORTSLOSS_SIGNAL_0:defALL_PORTSLOSS_SIGNAL_0:810"  "defALL_E_PORTSLOSS_SIGNAL_3:defALL_PORTSLOSS_SIGNAL_3:810" "defALL_E_PORTSLOSS_SIGNAL_5:defALL_PORTSLOSS_SIGNAL_5:810")

fpiRulesList=("defALL_F_PORTS_IO_FRAME_LOSS:defALL_PORTS_IO_FRAME_LOSS:800" "defALL_F_PORTS_IO_PERF_IMPACT:defALL_PORTS_IO_PERF_IMPACT:0")

fcipExtMSRulesList=("defALL_EXT_GE_PORTSINV_LEN_0:1:0" "defALL_EXT_GE_PORTSINV_LEN_1:1:0")
qsfpRulesList=("defALL_QSFPSFP_TEMP_85:1:0" " defALL_QSFPRXP_2180:1:0"  "defALL_QSFPCURRENT_10:1:0"  "defALL_QSFPVOLTAGE_3600:1:0" "defALL_QSFPVOLTAGE_2940:1:0" "defALL_QSFPSFP_TEMP_n5:1:0")

#### QSFP rules list for new 32G breakout qsfp 
QsfpRulesList=("defALL_32GSWL_QSFPRXP_3400:defALL_32GSWL_QSFPRXP_2187:810")

obsoleteAmpRules=("defALL_OTHER_F_PORTSCRC_20:1:0" "defALL_OTHER_F_PORTSCRC_21:1:0" "defALL_OTHER_F_PORTSITW_40:1:0" "defALL_OTHER_F_PORTSITW_41:1:0" "defALL_OTHER_F_PORTSITW_21:1:0" "defALL_QSFPSFP_TEMP_85:1:0" "defALL_OTHER_F_PORTSC3TXTO_20:1:0" "defALL_OTHER_F_PORTSSTATE_CHG_11:1:0" "defALL_QSFPRXP_2180:1:0" "defALL_QSFPCURRENT_10:1:0" "defALL_QSFPVOLTAGE_3600:1:0" "defALL_OTHER_F_PORTSLR_5:1:0" "defALL_OTHER_F_PORTSLOSS_SYNC_3:1:0" "defALL_OTHER_F_PORTSLOSS_SYNC_5:1:0" "defALL_OTHER_F_PORTSSTATE_CHG_10:1:0" "defALL_OTHER_F_PORTSSTATE_CHG_20:1:0" "defALL_OTHER_F_PORTSC3TXTO_2:1:0" "defALL_OTHER_F_PORTSC3TXTO_11:1:0" "defALL_OTHER_F_PORTSC3TXTO_10:1:0" "defALL_OTHER_F_PORTSC3TXTO_3:1:0" "defALL_OTHER_F_PORTSC3TXTO_4:1:0" "defALL_OTHER_F_PORTSPE_10:1:0" "defALL_OTHER_F_PORTSITW_15:1:0" "defALL_OTHER_F_PORTSLR_4:1:0" "defALL_OTHER_F_PORTSLR_2:1:0" "defALL_OTHER_F_PORTSLR_20:1:0" "defALL_OTHER_F_PORTSSTATE_CHG_2:1:0" "defALL_OTHER_F_PORTSSTATE_CHG_5:1:0" "defALL_OTHER_F_PORTSSTATE_CHG_4:1:0" "defALL_OTHER_F_PORTSITW_20:1:0" "defALL_OTHER_F_PORTSCRC_40:1:0" "defALL_OTHER_F_PORTSLOSS_SYNC_0:1:0" "defALL_OTHER_F_PORTSLR_10:1:0" "defALL_OTHER_F_PORTSLR_11:1:0" "defALL_OTHER_F_PORTSCRC_2:1:0" "defALL_OTHER_F_PORTSCRC_0:1:0" "defALL_QSFPVOLTAGE_2940:1:0" "defALL_OTHER_F_PORTSCRC_10:1:0" "defALL_QSFPSFP_TEMP_n5:1:0" "defALL_OTHER_F_PORTSITW_80:1:0" "defALL_OTHER_F_PORTSPE_3:1:0" "defALL_OTHER_F_PORTSPE_2:1:0" "defALL_OTHER_F_PORTSPE_0:1:0" "defALL_OTHER_F_PORTSPE_7:1:0" "defALL_OTHER_F_PORTSPE_5:1:0")

#### ALL_QSFP group and its default rules are depricated. Removing them from all platforms
allQsfpRuleList=("defALL_QSFPCURRENT_10:1:0" "defALL_QSFPRXP_2180:1:0" "defALL_QSFPSFP_TEMP_85:1:0" "defALL_QSFPSFP_TEMP_n5:1:0" "defALL_QSFPVOLTAGE_2940:1:0" "defALL_QSFPVOLTAGE_3600:1:0")

#### AG unsupported rule list
allAGUnSupportedRuleList=("defALL_LOCAL_PIDSIT_FLOW_8:1:0" "defALL_F_PORTSDEV_LOGIN_DIST_BALANCED:1:0" "defALL_F_PORTSDEV_LOGIN_DIST_IMBALANCED:1:0" "defALL_F_PORTSDEV_LOGIN_DIST_BALANCE_FAILED:1:0" "defSWITCHBB_FCR_CNT_MAX:1:0" "defSWITCHL2_DEVCNT_PER_60:1:0" "defSWITCHL2_DEVCNT_PER_75:1:0" "defSWITCHL2_DEVCNT_PER_90:1:0" "defSWITCHLSAN_DEVCNT_PER_60:1:0" "defSWITCHLSAN_DEVCNT_PER_75:1:0" "defSWITCHLSAN_DEVCNT_PER_90:1:0" "defSWITCHZONE_CFGSZ_PER_70:1:0" "defSWITCHZONE_CFGSZ_PER_80:1:0" "defSWITCHZONE_CFGSZ_PER_90:1:0" "defSWITCHZONE_CHG_10:1:0" "defSWITCHZONE_CHG_2:1:0" "defSWITCHZONE_CHG_5:1:0" "defSWITCHFAB_CFG_1:1:0" "defSWITCHFAB_CFG_2:1:0" "defSWITCHFAB_CFG_4:1:0" "defSWITCHFAB_SEG_1:1:0" "defSWITCHFAB_SEG_2:1:0" "defSWITCHFAB_SEG_4:1:0" "defSWITCHDID_CHG_1:1:0" "defSWITCHEPORT_DOWN_1:1:0" "defSWITCHEPORT_DOWN_2:1:0" "defSWITCHEPORT_DOWN_4:1:0" "defIT_COUNT_P_90:1:0" "defIT_COUNT_P_75:1:0" "defIT_COUNT_P_60:1:0")

#### FOS 9.0 new recommended SFP thresholds rule list
sfpRulesList90=("defALL_16GLWL_SFPCURRENT_70:defALL_16GLWL_SFPCURRENT_90:900" "defALL_25Km_16GLWL_SFPVOLTAGE_2850:defALL_25Km_16GLWL_SFPVOLTAGE_3000:900" "defALL_25Km_16GLWL_SFPVOLTAGE_3750:defALL_25Km_16GLWL_SFPVOLTAGE_3600:900" "defALL_32GLWL_SFPCURRENT_60:defALL_32GLWL_SFPCURRENT_90:900" "defALL_25Km_32GELWL_SFPCURRENT_70:defALL_25Km_32GELWL_SFPCURRENT_130:900" "defALL_32GSWL_QSFPCURRENT_10:defALL_32GSWL_QSFPCURRENT_43:900" "defALL_40G_QSFPCURRENT_10:defALL_40G_QSFPCURRENT_12:900")

##### strstr function to search a sub string in the string 
function strstr ( ) {
    #echo "eheh",$1 $2,"done"
    # if s2 points to a string of zero length, strstr echoes s1
    [ ${#2} -eq 0 ] && { echo "$1" ; return 0; }

    # strstr echoes nothing if s2 does not occur in s1
    case "$1" in
    *$2*) ;;
    *) return 1;;
    esac

    # use the pattern matching code to strip off the match and everything
    # following it
    first=${1/$2*/}

    # then strip off the first unmatched portion of the string
    xxx="${1##$first}"
    echo "$xxx" 
}

##### runs cli command on active CP
function runMapsCliCommand ( ) {
    ret=`correcthost_to_curr_vfid $1`
    echo $ret
}

# This function is the replacement of CONFIGSHOW function.
# This function  returns the configuration from local copy instead of doing RSH
# to active CP and get the configuration
# In the begining copyAllConfigurationFiles function copy all the configuration
# to /tmp directory and expect below function would use that configuration.
CONFIGSHOW_ADV() {
    if [ "$1" = "-chassis"  ]; then 
	cat /tmp/config_chassis
    elif [ "$1" = "-a" ] || [ "$1" = "-all" ] ; then
	cat /tmp/config_all
    else
	if [ $VF_ENABLED -ne $STS_OK ]; then
	    cat /tmp/config_$CURRENT_VF
	else 
	    cat /tmp/config_128
	fi
    fi
}

rm /tmp/maps_flows_log 2>  /dev/null
touch /tmp/maps_flows_log

#######################################################################
# Clears all the flow rules
# It first checks flow groups, if not present then don't do anything
# Otherwise delete all the rules having flow groups
#######################################################################
clearMapsFlowRules ( ) {
    #filter all the user defined groups
    CONFIGSHOW_ADV | grep "maps.udgroup." | grep -v maps.udgroup.list > /tmp/maps_groups

    #echo "groups: $groups ...$CURRENT_VF"
    policy=""
    found=""

    #keeps track of all the flow groups

    
    flowGroupsList=""



    policy=`CONFIGSHOW_ADV |grep "maps.activePolicy:" |awk -F: '{print $2}'`
    if [ -z $policy ]
    then
	echo "$CURRENT_VF policy $policy $actPolicyRules" >>/tmp/maps_flows_log
    else 
	CONFIGSHOW_ADV |grep "maps.policy.$policy"|awk -F: '{print $2}' > /tmp/maps_act_rules
	echo "policy $policy $actPolicyRules" >>/tmp/maps_flows_log
    fi
    
    #iterate through all the grpups
    for line in `cat /tmp/maps_groups`
    do
      group="$line"

      # if no group found then no need to proceed - without group user can't defined rules
      if [ -z "$group" ]
      then
	  continue
      fi

      #get the type and name - if the group type is not flow type then don't proceed
      flowGroup=`echo "$group" | awk -Fmaps.udgroup. '{print $2}'`
      if [ -z "$flowGroup" ]
      then
	  continue
      fi

      groupType=`echo "$flowGroup" | awk -F: '{print $2}'| cut -c 1-2` 
      groupName=`echo "$flowGroup" | awk -F: '{print $1}'` 

      
      echo "$CURRENT_VF $group, Type: $groupType Name: $groupName">>/tmp/maps_flows_log

      # check for flow group type 
      if [ "$groupType"  != 14 ]
      then
	  continue
      fi

      
      flowGroupsList="$groupName  $flowGroupsList"
		
      #search all the rules having group name
      CONFIGSHOW_ADV | grep  "maps\.rule\." | grep "$groupName" | awk  '{print $1}' > /tmp/maps_flow_rules
      echo "$CURRENT_VF now checking maps rules" >> /tmp/maps_flow_logs
      # delete each rule
      for line in `cat /tmp/maps_flow_rules`
      do
	ruleName=`echo $line | awk -Fmaps.rule. '{print $2}' | awk -F: '{print $1}'`
		
	#echo "flow group rule $line, $ruleName ,,, $flowGroup"
	cmd="/fabos/sbin/mapsrule --delete $ruleName -force"
			
	ret=$(runMapsCliCommand "$cmd")
	echo "$CURRENT_VF $cmd $ret $line" >> /tmp/maps_flow_log
	if [[ -z "$found" && ! -z "$policy" ]]
	then
	    found=`cat /tmp/maps_act_rules | grep "$ruleName"`
	    echo "$CURRENT_VF $ruleName found in active policy $policy" >> /tmp/maps_flows_log  
	fi
      done
    done 
    
    #reenable the policy if we touch the active policy
    if [ ! -z "$found" ]
    then
	cmd="/fabos/sbin/mapspolicy --enable $policy"

	ret=$(runMapsCliCommand "$cmd")
	echo "$CURRENT_VF $cmd $ret" >> /tmp/maps_flows_log  
    fi

    echo "$CURRENT_VF deimporting groups $flowGroupsList" >> /tmp/maps_flows_log  

    #deimport all the groups
    for groupName in $flowGroupsList
    do
      if [ -z "$groupName" ]
      then
	  continue
      fi
      
      cmd="/fabos/sbin/mapsconfig --deimport $groupName"
      ret=$(runMapsCliCommand "$cmd")
      echo "$CURRENT_VF $cmd $ret" >> /tmp/maps_flows_log
    done
}


#### deletes rule(s) and if need be replaced with new rule
function deleteRules ( ) {
    rulesList=$1
    ret=0

    
    #configuration for each logical switch
    CONFIGSHOW_ADV>xxx

    configBuffer=`awk '/^maps\.policy\./' xxx`
    #echo "configBuffer",$configBuffer 

    if [ -z "$configBuffer" ]
    then
	return $ret
    fi
	
    # getting maps.policy.list token value. this token has all the user
    # policies names
    policyList=`cat xxx | grep maps.policy.list`
    policyList=$(strstr "$policyList" ':')
    policyList=${policyList:1}
    policyList=$(echo $policyList | tr "," "\n")
    
    #echo "policyList",$policyList

    toVersion=${TO_MAJOR}${TO_MINOR}${TO_PATCH}
    fromVersion=${FROM_MAJOR}${FROM_MINOR}${FROM_PATCH}
    isDowngrade=`echo "$toVersion" "$fromVersion" | awk '{print $1 - $2}'`
	# echo "to $toVersion from $fromVersion isdown $isDowngrade"

    if [ $isDowngrade -lt 0 ]
    then
    	isDowngrade=1
    else
		isDowngrade=0
    fi

    # iterating all the policies
    for policy in $policyList
    do
        # getting rules present in the policy
        ruleBuffer=`cat xxx | grep "maps.policy.$policy"`

	# if no rules are present the continue
	if [ -z "$ruleBuffer" ]
	then
	    continue
	fi
	
	#iterating user rule database. user rules could come in two forms:
	# 1. simply delete the rule from user policy
	# 2. follow step #1 and then replace with new rule
        for ruleRec in $rulesList
	do
	    rule=${ruleRec%%:*}
	    tempValue=${ruleRec#*:}
	    newRule=${tempValue%%:*}
	    lastSupportRel=${tempValue#*:}
	    value=`echo "$lastSupportRel" "$toVersion" | awk '{print $1 - $2}'`

	    if [ $isDowngrade -eq 1 ]
	    then
            if [ $value -gt 0 ]
            then
		        #Downgrade Scenario
	            #searching old rule in user policy rules
	            found=`echo "$ruleBuffer" | grep "$newRule"`

                #rule not found then continue
	            if [ -z "$found" ]
	            then
		            continue
	            fi

	            #echo "rule",$rule
	            cmd="/fabos/sbin/mapspolicy --delrule $policy -rulename $rule"
	            ret=$(runMapsCliCommand "$cmd")
            fi
	    else 
    	        #upgrade Scenario
                #searching old rule in user policy rules
                found=`echo "$ruleBuffer" | grep "$rule"`

                #rule not found then continue
                if [ -z "$found" ]
                then
	            continue
                fi

                #echo "rule",$rule
                #deleting a rule and adding new rule back
                cmd="/fabos/sbin/mapspolicy --delrule $policy -rulename $rule"
                ret=$(runMapsCliCommand "$cmd")

                #adding a rule if ruleName is given
                if [ "$newRule" !=  1 ]
                then
	            #echo $newRule >> fileName
	            cmd="/fabos/sbin/mapspolicy --addrule $policy -rulename $newRule"
	            ret=$(runMapsCliCommand "$cmd")
                fi
	    fi
	done
    done
}

#### deletes rules from all FIDs
function deleteRulesFromAllFIDs ( ) {
    # check VF enabled
    if [ $VF_ENABLED -ne $STS_OK ]; then
	if [ $ACTIVECP ] 
	then
	    for_all_contexts deleteRules "$1"
	else
	    for_all_contexts_standby deleteRules "$1"   
	fi
    else 
	deleteRules "$1"
    fi	
}


#### deletes rules from all FIDs
function clearFlowRulesFromAllFIDs ( ) {
    # check VF enabled
    if [ $VF_ENABLED -ne $STS_OK ]; then
	if [ $ACTIVECP ] 
	then
	    for_all_contexts clearMapsFlowRules 
	else
	    for_all_contexts_standby clearMapsFlowRules
	fi
    else 
	clearMapsFlowRules
    fi	
}
#set -x
echo "$CURRENT_VF starting cleaning up flow configuration" >> /tmp/maps_flows_log  
clearFlowRulesFromAllFIDs
echo "$CURRENT_VF done cleaning up flow configuration" >> /tmp/maps_flows_log  
#set +x
#### Defect 610817: when migrating from FW->MAPS fw_SWITCHWWNOUT was configured
#### incorrectly. reconfiguring this as part of postinstall
	correcthost_all_vfs /fabos/sbin/mapsRule --config fw_SWITCHWWNOUT -group ALL_WWN > /dev/null

####MAPS rules cleanup start

# remove all_d_ports having LF, and Loss of signal rules and replaced with ALL_PORTS rules 
# remove LF and loss of signal rules for E, F ports and replaced them with ALL_PORTS
    fcrRulesList=${fcrRulesList[@]}
    deleteRulesFromAllFIDs "$fcrRulesList"

    dPortRules=${dPortRulesList[@]}
    deleteRulesFromAllFIDs "$dPortRules"

    dLfRulesList=${dLfRulesList[@]}
    deleteRulesFromAllFIDs "$dLfRulesList"

    dLsignalRulesList=${dLsignalRulesList[@]}
    deleteRulesFromAllFIDs "$dLsignalRulesList"

    portLsignalRulesList=${portLsignalRulesList[@]}
    deleteRulesFromAllFIDs "$portLsignalRulesList"

    portLfRulesList=${portLfRulesList[@]}
    deleteRulesFromAllFIDs "$portLfRulesList"

    fpiRulesList=${fpiRulesList[@]}
    deleteRulesFromAllFIDs "$fpiRulesList"

    QsfpRules=${QsfpRulesList[@]}
    deleteRulesFromAllFIDs "$QsfpRules"

    allQsfpRules=${allQsfpRuleList[@]}
    deleteRulesFromAllFIDs "$allQsfpRules"

    ag_mode_enabled
    # needs to cleanup below rules if the switch is AG	
    if [ $? -ne 0 ]
    then
	    allAGUnSupportedRule=${allAGUnSupportedRuleList[@]}
	    deleteRulesFromAllFIDs "$allAGUnSupportedRule"
    fi
    
    # if the platform is Wedge (SWBD161) then delete BE, FCIP rules
    if [ $swbd == "SWBD161"  -o $swbd == "SWBD162" ]
    then

	fcipRules=${fcipRulesList[@]}
	deleteRulesFromAllFIDs "$fcipRules"

	beRules=${beRulesList[@]}
	deleteRulesFromAllFIDs "$beRules"

	encrRules=${encrRulesList[@]}
	deleteRulesFromAllFIDs "$encrRules"
	
    ##
    # dont allow user to upgrade if for any reason user has added ALL_CIRCUITS/ALL_BE_PORTS in user defined rules
    ##
    fi

    # cleaning up embedded platforms -- too many and this is the reason use for loop.
    for bd in 156
    do
        # once if conditions gets executed we need to break becauuse no neede check further
        if [ "$swbd" == "$bd" ]
	then
	    fcipRules=${fcipRulesList[@]}
	    deleteRulesFromAllFIDs "$fcipRules"

	    beRules=${beRulesList[@]}
	    deleteRulesFromAllFIDs "$beRules"

	    #dPortRules=${dPortRulesList[@]}
	    #deleteRulesFromAllFIDs "$beRules"
	    break
	fi
    done

	# Delete GE_INV_LEN rules from FCIP platform.
    if [ $swbd == "SWBD165" -o $swbd == "SWBD166" ]
    then
		fcipRules=${fcipExtMSRulesList[@]}
		deleteRulesFromAllFIDs "$fcipRules"
	fi


    # if the platform is Odin(SWBD133)  & TYR(SWBD173) & TYR2(SWBD184) then delete FCIP rules
    if [ $swbd == "SWBD173" -o $swbd == "SWBD184" ]
    then
	fcipRules=${fcipRulesList[@]}
	deleteRulesFromAllFIDs "$fcipRules"

	#dPortRules=${dPortRulesList[@]}
	#deleteRulesFromAllFIDs "$beRules"

        ##
        # dont allow user to upgrade if for any reason user has added ALL_CIRCUITS in user defined rules.
        # this is extremely unexpected but could happen
        ##
    fi


    buf=`/fabos/cliexec/hashow`
    buf=$(strstr "$buf" 'Not supported on this platform')
    # if the platform is pizza box then delete critical ps rules
    if [ "$buf" ]
    then
	psRules=${psRulesList[@]}
	deleteRulesFromAllFIDs "$psRules"
    fi

	# replace FOS9.0 SFP rules with new recommended threshold rules
	# sfpRules=${sfpRulesList90[@]}
	# deleteRulesFromAllFIDs "$sfpRules"

#echo "maps cleanup end"
#### MAPS rules clean up end
# Create power-on test skip indicator file on standby
#
>/mnt/etc/skip_poweron_test

#
# Store checksum of ldconfig and ld.so (shared loader)
# The output hash values will be used during power on test
#
if [ "$TO_MAJOR" -ge 6 ]; then
$ECHO "Creating loader checksum file"
>/mnt/etc/ldchksum

    #Find the loader checksum
    if [ -s /mnt/var/glibc-linuxthreads/copyback/ld-* ]
    then
	md5sum /mnt/var/glibc-linuxthreads/copyback/ld-* | \
	/bin/sed -e "s,\/mnt\/var\/glibc-linuxthreads\/copyback\/ld-,\/lib\/ld-,g" \
	>> /mnt/etc/ldchksum
    else
	md5sum /mnt/lib/ld-* | \
	/bin/sed -e "s,\/mnt\/lib\/ld-,\/lib\/ld-,g" \
	>> /mnt/etc/ldchksum
    fi

    #Now manipulate the ldconfig checksum
    if [ -s /mnt/var/glibc-linuxthreads/copyback/ldconfig ]
    then
	md5sum /mnt/var/glibc-linuxthreads/copyback/ldconfig | \
	/bin/sed -e "s,\/mnt\/var\/glibc-linuxthreads\/copyback\/ldconfig,\/sbin\/ldconfig,g" \
	>> /mnt/etc/ldchksum
    else
	md5sum /mnt/sbin/ldconfig | \
	/bin/sed -e "s,\/mnt\/sbin\/ldconfig,\/sbin\/ldconfig,g" \
	>> /mnt/etc/ldchksum
    fi

else
    if [ -f /mnt/etc/ldchksum ]; then
	$ECHO "Removing loader checksum file"
	rm /mnt/etc/ldchksum
    fi
fi

# Remove trace_id.dat file so that trace process can create a new one when it starts
if [ -f '/mnt/var/trace/trace_id.dat' ] ;then
    /bin/rm -f /mnt/var/trace/trace_id.dat
fi

remove_ipfilter_rule()
{
	total_policy=8
	ipfilter1="897"
	ipfilter2="898"
	ipfilter3="111"
	for (( i = 0; i <= total_policy ; i++ ))
	do	
		rule_name=`/fabos/cliexec/config get ipfilter.$i.name 5`
		if [[ -n $rule_name && "$rule_name" = "default_ipv4" || 
			"$rule_name" = "default_ipv6" ]]; then
			new_rule=`/fabos/cliexec/config get ipfilter.$i.numofrules 2`
			old_rule=$new_rule
			for (( j = 1; j <= $new_rule && $new_rule != 0; j++ ))
			do
				d_port=`/fabos/cliexec/config get ipfilter.$i.rule.$j 5 |
						cut -f 6- -d ','`
				if [[ "$d_port" = "$ipfilter1" ||  "$d_port" = "$ipfilter2" ||
						"$d_port" = "$ipfilter3" ]]; then
					for (( k = $j; k <= $new_rule; k++ ))
					do
						if [ $k != $new_rule ]; then
							next_rule=`/fabos/cliexec/config get ipfilter.$i.rule.$((k+1)) 5`
							/fabos/cliexec/config set ipfilter.$i.rule.$k 5 "$next_rule"
						else
							/fabos/cliexec/config remove ipfilter.$i.rule.$k
						fi
					done
					(( new_rule-- ))
					(( j-- ))
				fi
			done
			if [ $old_rule != $new_rule ];then
				/fabos/cliexec/config set ipfilter.$i.numofrules 2 $new_rule
				/fabos/cliexec/config update
			fi
		else
			return
		fi			
	done
}

add_default_audit_key()
{
	default_key=10,
	clicommand="/fabos/cliexec/config get audit.cfg.class 5"
	ret=`correcthost $clicommand`;
	last=`echo $ret | awk '{print $NF}'`
	key_found=`echo $ret | grep $default_key |wc -l`
	if [ $key_found == "0" ]; then
		# defect 621163 In some cases , is missed at the end of key value
		# So checking that we need add only , 
		mssing_comma=10 
		key_found=`echo $ret | grep $mssing_comma |wc -l`
		if [ $key_found == "1" ]; then 
			clicommand="/fabos/cliexec/config set audit.cfg.class 5 $last,"
			ret=`correcthost $clicommand`;
			clicommand="/fabos/cliexec/config commit"
			ret=`correcthost $clicommand`;
		else  
		
			clicommand="/fabos/cliexec/config set audit.cfg.class 5 $last$default_key"
			ret=`correcthost $clicommand`;
			clicommand="/fabos/cliexec/config commit"
			ret=`correcthost $clicommand`;
		fi
	fi
}

# defect- 410381 Removing RPC and portmapper entries
if [ "$TO_MAJOR" -eq 7 -a "$TO_MINOR" -ge 1 ]; then
	check_vf_enabled
	if [ $? -eq $STS_ERR ]; then
		current_context=$CURRENT_VF
		if [ ! -e /fabos/link_sbin/lscfg_test ]; then
			/bin/ln -s /fabos/cliexec/lscfg_util /fabos/link_sbin/lscfg_test 2> /dev/null
		fi 
		vf_id=`lscfg_test --fid 0`
		if [ $current_context != $vf_id ]; then
			context_switch $vf_id
			remove_ipfilter_rule
			add_default_audit_key
			context_switch $current_context
		else
			remove_ipfilter_rule
			add_default_audit_key
		fi
		if [ -e /fabos/link_sbin/lscfg_test ]; then
			/bin/rm /fabos/link_sbin/lscfg_test
		fi
	else
		remove_ipfilter_rule
		add_default_audit_key
	fi
fi
# create the trace dump file on the /mnt dir
trace_create_dump_file


# Touch the /etc/fabos/ag/fos_config.backup file
# if it doesn't exist
#
if [ ! -f /etc/fabos/ag/fos_config.backup ]; then
	/bin/touch /etc/fabos/ag/fos_config.backup 2> /dev/null
fi

#
# Touch the /mnt/etc/fabos/config/fwdl_history file
# if it doesn't exist. If the file exists then it is from a 
# Netinstall that happened before this FWDL.
#
if [ ! -f /etc/fabos/config/fwdl_history ]; then
	echo "" > /mnt/etc/fabos/config/fwdl_history 2> /dev/null
else
	if [ $ACTIVECP ]; then
	    ret=`/fabos/sbin/ron -c > /dev/null 2>&1; echo $?`
	else
		ret=`/usr/bin/rsh -n $(otherhost) "ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 CURRENT_AD=0 /fabos/sbin/ron -c > /dev/null 2>&1; echo $?"`
	fi

	if [ $ret -ne 1 ]; then
		echo "" > /mnt/etc/fabos/config/fwdl_history 2> /dev/null
	else
		echo "NINSTALL_FWDL" > /mnt/etc/fabos/config/fwdl_history 2> /dev/null
	fi
fi


#
# for pizzabox with firmware v5.0 or older, make sure the
# upgrade to new firmware (v5.1) to boot in a quiet mode.
# for chassis-based platforms, we honor this mode as well.
#
OPT="$(echo $(cat /boot/extra_boot_opts 2>/dev/null) quiet)"
bootenv OSLoadOptions "$OPT"

#
# Platforms that upgrade from older FOS versions to 9.0.0
# running with Linux 4.1 do not have the rootdelay and pcie_ports set.
# Without the rootdelay set, it can cause mount failures.
#
case ${SWBD##SWBD} in
	'161' | '162' | '165' | '166' | '169' | '170' | '175' | '176' | '178')
		bootenv bootargs 'root=/dev/sda$prt rootfstype=ext4 console=ttyS0,9600 rootdelay=5 pcie_ports=native quiet'
		;;
esac
	
if [ ${SWBD##SWBD} == 156 ]; then
	# extract out slub_debug if there is any
	newarg=`bootenv bootargs | sed 's/slub_debug //'`
	bootenv bootargs "$newarg"
fi


# temporary for dcf branch: disable POST and set LABMode to 8
#/fabos/link_sbin/diagpost 0
#/fabos/link_sbin/setlabmode 8

disable_peer_beacon() {
	MAX_PARTITION=8
	partition=0
	counter=0
	fids=""
	current_context=-1
	while [ $partition -le $MAX_PARTITION ]; do
		if [ -f /proc/fabos/switch/$partition/route_info ]; then
			lcb=`grep "Peer beacon port =" /proc/fabos/switch/$partition/route_info | cut -d "=" -f2 | awk '{print $1}'`
			if [ "$lcb" != "" ] && [ $lcb -ne "-1" ]; then
				fids="$fids `cat /proc/fabos/switch/$partition/info | grep "LS Attributes:" | cut -d "," -f1 | awk '{print $4}'`"
				counter=`expr $counter + 1`
				break
			fi
		fi
		partition=`expr $partition + 1 `
	done
	if [ $ACTIVECP ] && [ $lcb -ne "-1" ]; then
		cliCommand="/fabos/link_sbin/portpeerbeacon --disable "$lcb"";
		check_vf_enabled
		if [ $? -ne $STS_OK ]; then
			current_context=$CURRENT_VF;
			context_switch $fids
		fi
		ret=`ROLE_ID=root $cliCommand `
		if [ $current_context -ne "-1" ]; then
			context_switch $current_context
		fi
		if [ -n "$ret" ]; then
			echo "post install script failed to run peer beacon command, cmd : cliCommand error: $ret";
		fi
	fi
}
disable_maps()
{
#    echo " in disable_maps function"
    if [ -f /tmp/maps.err.log ]; then
	if [ $ACTIVECP ]; then
		# echo "Disabling MAPS trynig again."
	    cliCommand="/fabos/link_sbin/mapsconfig --disablemaps";
#	    echo "active cp disable_maps $cliCommand\n"
		ret=`ROLE_ID=root $cliCommand`
	    if [ -n "$ret" ]; then
		echo "port install script failed to run MAPS command, cmd : $cliCommand error: $ret";
	    fi
	else
	    cliCommand="CHASSIS_ROLEID=0 CURRENT_VF=255 /fabos/link_sbin/mapsconfig --disablemaps"
	    ret=`correcthost $cliCommand`
	    # echo "standby cp disable_maps $cliCommand $ret $(otherhost)\n"
	    # this is error case when script failed to run command
	    # this could only happen in following condition
	    # 1. maps dead, 2. err.log exist but maps is disabled 
	    if [ -n "$ret" ]; then
		echo "port install script failed to run MAPS command, cmd : $cliCommand error: $ret";
	    fi
	fi
	rm /tmp/maps.err.log
   #else
	#echo "MAPS is not active"
    fi
}
#
# maps_enabled_check
#
# Check whether the switch is currently in auto csctl mode
#
maps_enabled_check() {
    # on active cp we need diffrent command than on the stand by.
    # dont know the reason why?
    if [ $ACTIVECP ]; then
	ret=`/fabos/cliexec/configshow -chassis | grep maps.migrated:1 |wc -l`
	# need to truncate all the leading blank characters 
	last=`echo $ret | tr -d ' '`
    else
	cmd="CHASSIS_ROLEID=0 CURRENT_VF=255 /fabos/cliexec/configshow -chassis | grep maps.migrated:1 | wc -l"
	ret=`correcthost  $cmd`;
	# ret will have command plus the result so we just need result. result will be 
	# either zero or 1 so we just need last character from the end
	last=${ret: -1:1}
    fi
    # this is check for debugging 
    #if  [ $last -eq 1 ]; then
	#echo "1: maps is enabled $last"
    #else
	#echo "1: maps is disabled $last"
    #fi
    # return the status
    return $last
}

#check for maps enabled
check_for_maps_enabled()
{
    maps_enabled_check
    if [ $? -gt 0 ]; then
	echo $MAPS_ACTIVE > /tmp/maps.err.log
    fi
    return $STS_OK
}
# enable netmon if the license is present while downgrading the firmware.
enable_netmon_if_fv_license_present()
{
	# check the FV license
#	fv_license=`/fabos/bin/licenseshow | grep "Fabric Vision license"`
	fv_license=`/fabos/libexec/lutil -l FABRIC_VISION`

#	echo "fv_license = $fv_license"

	# license is present
	if [ "$fv_license" == "yes" ] ; then
		# command to enable the netmon 2 indicate integer, 1 indicate enable
		clicmd="/fabos/cliexec/config set maps.netmon.enabled 2 1"

    	if [ $ACTIVECP ]; then
			ret=`$clicmd`

			#if above command fails
	    	if [ -n "$ret" ]; then
				echo "port install script failed to run MAPS command, cmd : $clicomd error: $ret";
	    	fi

			clicmd=/fabos/cliexec/configcommit
			ret=`$clicmd`
			# error check being done later
    	else
			# trying to enable netmon in LS=0 i.e., default switch
			# since 'config set' does not need RBAC check so passing on FABOS_SWITCHNO=0
			# should work.
			clicmd="CHASSIS_ROLEID=0 CURRENT_VF=255 FABOS_SWITCHNO=0 $clicmd"
			ret=`correcthost  $clicmd`;

			#if above command fails
	    	if [ -n "$ret" ]; then
				echo "port install script failed to run MAPS command, cmd : $clicmd error: $ret";
	    	fi
			
			# command to commit
			clicmd=/fabos/cliexec/configcommit	
			cmd="CHASSIS_ROLEID=0 CURRENT_VF=255 $clicmd"
			ret=`correcthost  $clicmd`;
    	fi

		# commit error code	
	    if [ -n "$ret" ]; then
			echo "port install script failed to run MAPS command, cmd : $clicmd error: $ret";
	    fi
	fi	
}

#enable auto reboot for recovery(defect #576089)
if [ $TO_MAJOR -ge 8 ]; then
	if [ -f /mnt/etc/fabos/config/no_reboot_recover ]; then
		rm /mnt/etc/fabos/config/no_reboot_recover
	fi
	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
	FABOS_SWITCHNO=0
	correcthost /fabos/cliexec/config remove system.intPortCrdRecov
	correcthost /fabos/cliexec/config remove system.fePortStuck
	correcthost /fabos/cliexec/config remove system.bePortToStuck
	correcthost /fabos/cliexec/config remove bottleneck.BECreditLossLRThresh
	correcthost /fabos/cliexec/config remove bottleneck.BECreditLossFaultingBlade
	remove_rpcd
	correcthost /fabos/cliexec/configcommit
	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
fi

# checks for downgrade if major is less than 8
if [ "$TO_MAJOR" -lt 8 ]; then
    # echo "$TO_MAJOR $TO_MINOR, now netmon has to be disabled"
	enable_netmon_if_fv_license_present
fi


# checks for downgrade
if [ "$TO_MAJOR" -eq 7 -a "$TO_MINOR" -le 1 ]; then
    # echo "$TO_MAJOR $TO_MINOR, now MAPS has to be disabled"  
    check_for_maps_enabled
    disable_maps
fi

#
# Downgrade from v7.3.0 to v7.2.0
#
if [ "$TO_MAJOR" -eq 7 -a "$TO_MINOR" -le 2 ]; then
	#echo "$TO_MAJOR $TO_MINOR, now peer beacon has to be disabled"
	disable_peer_beacon
fi

	if [ $TO_MAJOR -eq 7 -a $TO_MINOR -eq 3 -a $TO_PATCH -ge 1 ]; then
		ret=`/bin/ps -e | /bin/grep "agd" | /bin/grep -v "diag" | wc -l`
		if [ $ret -ne 0 ]; then
			check_vf_enabled
			if [ $? -ne $STS_OK ]; then
				FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
				FABOS_SWITCHNO=0
				add_ag_fporttrunking_key
				FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			else
				add_ag_fporttrunking_key
			fi
		fi
	fi

add_snmp_informsTag()
{

    inform=`/fabos/cliexec/config get snmp.inform 2`;
    informTagStatus="0";
    informTagStatusDefault="0";

    if [ "$inform" = "1" ]; then
        informTagStatus=1;
    else
        informTagStatus=0;
    fi

    i=0;
    while [ $i -lt 6 ]; do
    /fabos/bin/configshow -all | grep -qi snmp.snmpv3TrapTarget.$i.informenabled
    if [ $? -ne 0 ]; then
        /fabos/cliexec/config set snmp.snmpv3TrapTarget.$i.informenabled 2 $informTagStatus;
        /fabos/cliexec/config set snmp.snmpv3TrapTarget.$i.informenabled.default 2 $informTagStatusDefault;
    fi
    i=`expr $i + 1`
    done
    /fabos/cliexec/configcommit
}

remove_snmp_informsTag()
{
    i=0
    while [ $i -lt 6 ]; do
    /fabos/bin/configshow -all | grep -qi snmp.snmpv3TrapTarget.$i.informenabled
    if [ $? -eq 0 ]; then
        /fabos/cliexec/config remove snmp.snmpv3TrapTarget.$i.informenabled
        /fabos/cliexec/config remove snmp.snmpv3TrapTarget.$i.informenabled.default
    fi
    i=`expr $i + 1`
    done
    /fabos/cliexec/configcommit
}


#
# Downgrade from v7.2.1 to v7.2.0
#
SSHD_CONFIG_FILE=/etc/sshd_config
SSH_CONFIG_FILE=/etc/ssh_config
SSHD_CONFIG_FILE_MNT=/mnt/etc/sshd_config
SSH_CONFIG_FILE_MNT=/mnt/etc/ssh_config

if [ $TO_MAJOR -eq 7 -a $TO_MINOR -eq 2 -a $TO_PATCH -eq 0 ]; then

    if [ -f $SSHD_CONFIG_FILE ]; then
       /bin/grep -v "MinPrime" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
       /bin/grep -v "ShaValue" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
       /bin/grep -v "KexAlgorithms diffie-hellman-group-exchange-sha256" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
    fi
    if [ -f $SSH_CONFIG_FILE ]; then
       /bin/grep -v "MinPrime" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
       /bin/grep -v "ServerHostKeySize" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
       /bin/grep -v "ShaValue" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
       /bin/grep -v "KexAlgorithms diffie-hellman-group-exchange-sha256" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
    fi

    if [ -f $SSHD_CONFIG_FILE_MNT ]; then
    	/bin/grep -v "MinPrime" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
	/bin/grep -v "ShaValue" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
	/bin/grep -v "KexAlgorithms diffie-hellman-group-exchange-sha256" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
    fi

    if [ -f $SSH_CONFIG_FILE_MNT ]; then
	/bin/grep -v "MinPrime" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
	/bin/grep -v "ServerHostKeySize" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
	/bin/grep -v "ShaValue" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
	/bin/grep -v "KexAlgorithms diffie-hellman-group-exchange-sha256" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
    fi
fi

#Add ecdsa host key to sshd_config for releases >= v7.3.0
if [ $TO_MAJOR -eq 7 -a $TO_MINOR -ge 3 ]; then
    if [ -f $SSHD_CONFIG_FILE ]; then
	/bin/grep "HostKey /etc/ssh_host_ecdsa_key" $SSHD_CONFIG_FILE > /dev/null 2>&1
	ret=`echo $?`
	if [ $ret -ne 0 ]; then
    		echo "HostKey /etc/ssh_host_ecdsa_key" >> $SSHD_CONFIG_FILE
	fi
    fi
    if [ -f $SSHD_CONFIG_FILE_MNT ]; then
	/bin/grep "HostKey /etc/ssh_host_ecdsa_key" $SSHD_CONFIG_FILE_MNT > /dev/null 2>&1
	ret=`echo $?`
	if [ $ret -ne 0 ]; then
    		echo "HostKey /etc/ssh_host_ecdsa_key" >> $SSHD_CONFIG_FILE_MNT
	fi
    fi
fi
#Remove ecdsa host key from sshd_config for releases < v7.3.0
if [ $TO_MAJOR -eq 7 -a $TO_MINOR -lt 3 ]; then
    if [ -f $SSHD_CONFIG_FILE ]; then
       /bin/grep -v "HostKey /etc/ssh_host_ecdsa_key" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
    fi
    if [ -f $SSHD_CONFIG_FILE_MNT ]; then
       /bin/grep -v "HostKey /etc/ssh_host_ecdsa_key" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
    fi
fi


if [ -f $SSHD_CONFIG_FILE ]; then
	cat $SSHD_CONFIG_FILE | grep -v "#" | grep Banner | grep "/etc/fabos/motd" > /dev/null 2>&1
	retVal=$?
	if [ $retVal -ne 0 ]; then
	  	/bin/grep -v "Banner" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
		/bin/chmod 600 $SSHD_CONFIG_FILE
	        echo "Banner /etc/fabos/motd" >> $SSHD_CONFIG_FILE
		/fabos/cliexec/config save $SSHD_CONFIG_FILE 
	fi
	cat $SSHD_CONFIG_FILE | grep -v "#" | grep "Port " | grep -v "22" > /dev/null 2>&1
	retVal=$?
	if [ $retVal -eq 0 ]; then
	  	/bin/grep -v "Port " $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
		/bin/chmod 600 $SSHD_CONFIG_FILE
	        echo "Port 22" >> $SSHD_CONFIG_FILE
		/fabos/cliexec/config save $SSHD_CONFIG_FILE 
	fi
fi
if [ -f $SSHD_CONFIG_FILE_MNT ]; then
	cat $SSHD_CONFIG_FILE_MNT | grep -v "#" | grep Banner | grep "/etc/fabos/motd" > /dev/null 2>&1
	retVal=$?
	if [ $retVal -ne 0 ]; then
	  	/bin/grep -v "Banner" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
		/bin/chmod 600 $SSHD_CONFIG_FILE_MNT
	        echo "Banner /etc/fabos/motd" >> $SSHD_CONFIG_FILE_MNT
		/fabos/cliexec/config save $SSHD_CONFIG_FILE_MNT 
	fi
	cat $SSHD_CONFIG_FILE_MNT | grep -v "#" | grep "Port " | grep -v "22" > /dev/null 2>&1
	retVal=$?
	if [ $retVal -eq 0 ]; then
	  	/bin/grep -v "Port " $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
		/bin/chmod 600 $SSHD_CONFIG_FILE_MNT
	        echo "Port 22" >> $SSHD_CONFIG_FILE_MNT
		/fabos/cliexec/config save $SSHD_CONFIG_FILE_MNT 
	fi
fi

# Syncing known_hosts file from primary to secondary partition so as to avoid host key mismatch error after fwdl
/fabos/cliexec/config save /root/.ssh/known_hosts > /dev/null 2>&1

#Add extra macs from sshd_config for releases >= v7.3.0
if [ $TO_MAJOR -eq 7 -a $TO_MINOR -ge 3 ]; then
    # "config get" for fips mode returns value only if called from
    # default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
    # revert it back to its original value after "config get"

    checkFipsMode
    retVal=$?
    if [ $retVal -eq 1 ]; then
	if [ -f $SSHD_CONFIG_FILE ]; then
	  	/bin/grep -v "Macs" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
	        echo "Macs hmac-sha1,hmac-sha2-256,hmac-sha2-512" >> $SSHD_CONFIG_FILE

 		/bin/grep -v "Macs" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
		echo "Macs hmac-sha1,hmac-sha2-256,hmac-sha2-512" >> $SSH_CONFIG_FILE

	       /bin/grep -v "KexAlgorithms" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
	        echo "KexAlgorithms ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256" >> $SSHD_CONFIG_FILE

	       /bin/grep -v "KexAlgorithms" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
	        echo "KexAlgorithms ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256" >> $SSH_CONFIG_FILE
		/fabos/cliexec/config save $SSHD_CONFIG_FILE 
		/fabos/cliexec/config save $SSH_CONFIG_FILE
    		if [ $STANDBYCP -eq 1 ] ; then
			/bin/rcp $SSHD_CONFIG_FILE root@$(otherhost):$SSHD_CONFIG_FILE
			/bin/rcp $SSH_CONFIG_FILE root@$(otherhost):$SSH_CONFIG_FILE
		fi
	fi
	if [ -f $SSHD_CONFIG_FILE_MNT ]; then
	       /bin/grep -v "Macs" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
	        echo "Macs hmac-sha1,hmac-sha2-256,hmac-sha2-512" >> $SSHD_CONFIG_FILE_MNT

	       /bin/grep -v "Macs" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
        	echo "Macs hmac-sha1,hmac-sha2-256,hmac-sha2-512" >> $SSH_CONFIG_FILE_MNT

	       /bin/grep -v "KexAlgorithms" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
	        echo "KexAlgorithms ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256" >> $SSHD_CONFIG_FILE_MNT

	       /bin/grep -v "KexAlgorithms" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
	        echo "KexAlgorithms ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256" >> $SSH_CONFIG_FILE_MNT
		/fabos/cliexec/config save $SSHD_CONFIG_FILE_MNT
		/fabos/cliexec/config save $SSH_CONFIG_FILE_MNT
    		if [ $STANDBYCP -eq 1 ] ; then
			/bin/rcp $SSHD_CONFIG_FILE_MNT root@$(otherhost):$SSHD_CONFIG_FILE_MNT
			/bin/rcp $SSH_CONFIG_FILE_MNT root@$(otherhost):$SSH_CONFIG_FILE_MNT
		fi
	fi
    fi
fi
#Remove extra macs from sshd_config for releases < v7.3.0
if [ $TO_MAJOR -eq 7 -a $TO_MINOR -lt 3 ]; then
    # "config get" for fips mode returns value only if called from
    # default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
    # revert it back to its original value after "config get"
    checkFipsMode
    retVal=$?
    if [ $retVal -eq 1 ]; then
	if [ -f $SSHD_CONFIG_FILE ]; then
       		/bin/grep -v "Macs" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
		echo "Macs hmac-sha1" >> $SSHD_CONFIG_FILE

	        /bin/grep -v "Macs" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
        	echo "Macs hmac-sha1" >> $SSH_CONFIG_FILE

	        /bin/grep -v "KexAlgorithms" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
        	echo "KexAlgorithms diffie-hellman-group-exchange-sha256" >> $SSHD_CONFIG_FILE

	        /bin/grep -v "KexAlgorithms" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
        	echo "KexAlgorithms diffie-hellman-group-exchange-sha256" >> $SSH_CONFIG_FILE
		/fabos/cliexec/config save $SSHD_CONFIG_FILE
		/fabos/cliexec/config save $SSH_CONFIG_FILE
    		if [ $STANDBYCP -eq 1 ] ; then
			/bin/rcp $SSHD_CONFIG_FILE root@$(otherhost):$SSHD_CONFIG_FILE
			/bin/rcp $SSH_CONFIG_FILE root@$(otherhost):$SSH_CONFIG_FILE
		fi
	fi
	if [ -f $SSHD_CONFIG_FILE_MNT ]; then
	        /bin/grep -v "Macs" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
		echo "Macs hmac-sha1" >> $SSHD_CONFIG_FILE_MNT

  	        /bin/grep -v "Macs" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
         	echo "Macs hmac-sha1" >> $SSH_CONFIG_FILE_MNT

	        /bin/grep -v "KexAlgorithms" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
	        echo "KexAlgorithms diffie-hellman-group-exchange-sha256" >> $SSHD_CONFIG_FILE_MNT

	        /bin/grep -v "KexAlgorithms" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
 	        echo "KexAlgorithms diffie-hellman-group-exchange-sha256" >> $SSH_CONFIG_FILE_MNT
		/fabos/cliexec/config save $SSHD_CONFIG_FILE_MNT
		/fabos/cliexec/config save $SSH_CONFIG_FILE_MNT
    		if [ $STANDBYCP -eq 1 ] ; then
			/bin/rcp $SSHD_CONFIG_FILE_MNT root@$(otherhost):$SSHD_CONFIG_FILE_MNT
			/bin/rcp $SSH_CONFIG_FILE_MNT root@$(otherhost):$SSH_CONFIG_FILE_MNT
		fi
	fi
    fi
fi

#Remove ssh ecdsa keypair for releases < v7.3.0 in fips mode
if [ $TO_MAJOR -eq 7 -a $TO_MINOR -lt 3 ]; then
    # "config get" for fips mode returns value only if called from
    # default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
    # revert it back to its original value after "config get"
    checkFipsMode
    retVal=$?
    PRIVKEY_DIR=/root/.ssh
    PRIVKEY_FILE_ECDSA=id_ecdsa
    EXPORT_PUBKEY_FILE_ECDSA=id_ecdsa.pub
    if [ $retVal -eq 1 ]; then
    	if [ -e $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA ]; then
		size=`/bin/ls -la $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA | /bin/awk ' { print $5 } '`
		correcthost_to_curr_vfid /bin/dd if=/dev/zero of=$PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA bs=1 count=$size 2> /dev/null
		correcthost_to_curr_vfid /fabos/cliexec/config save $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA

		correcthost_to_curr_vfid /bin/rm $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA
		correcthost_to_curr_vfid /bin/rm $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_ECDSA
		correcthost_to_curr_vfid /fabos/cliexec/config save $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA
		correcthost_to_curr_vfid /fabos/cliexec/config save $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_ECDSA
	fi
    fi
fi

#Remove ecdsa host key for releases < v7.3.0 in fips mode
if [ $TO_MAJOR -eq 7 -a $TO_MINOR -lt 3 ]; then
    # "config get" for fips mode returns value only if called from
    # default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
    # revert it back to its original value after "config get"
    checkFipsMode
    retVal=$?
    if [ $retVal -eq 1 ]; then
	HOST_KEY_DIR=/etc
	HOST_ECDSA_KEY=ssh_host_ecdsa_key
	PUB_SUFFIX=.pub
	if [ -e $HOST_KEY_DIR/$HOST_ECDSA_KEY ]; then
			size=`/bin/ls -la $HOST_KEY_DIR/$HOST_ECDSA_KEY | /bin/awk ' { print $5 } '`
			correcthost_to_curr_vfid /bin/dd if=/dev/zero of=$HOST_KEY_DIR/$HOST_ECDSA_KEY bs=1 count=$size 2> /dev/null
			correcthost_to_curr_vfid /fabos/cliexec/config save $HOST_KEY_DIR/$HOST_ECDSA_KEY

			correcthost_to_curr_vfid /bin/rm $HOST_KEY_DIR/$HOST_ECDSA_KEY
			correcthost_to_curr_vfid /bin/rm $HOST_KEY_DIR/$HOST_ECDSA_KEY$PUB_SUFFIX
			correcthost_to_curr_vfid /fabos/cliexec/config save $HOST_KEY_DIR/$HOST_ECDSA_KEY
			correcthost_to_curr_vfid /fabos/cliexec/config save $HOST_KEY_DIR/$HOST_ECDSA_KEY$PUB_SUFFIX

	fi
    fi
fi

#swTrackChangesTrap is deprecated in v7.2.0
# AMP base version is 7.4 Hence skip the conditon in AMP 
if [ "$TO_MAJOR" -ge 7 -a "$TO_MINOR" -ge 3 -a $ANALYTICS_FLAG -eq 0 ]; then
	# Check for Virtual Fabrics
	check_vf_enabled
	if [ $? -ne $STS_OK ]; then
		CHASSISCMD="cmd_chassis" ;
		current_context=$CURRENT_VF ;
		for_all_contexts  remove_snmp_trap_change;
		context_switch $current_context ;
	else
		remove_snmp_trap_change ;
	fi
fi

if [ "$TO_MAJOR" -ge 8 -a "$TO_MINOR" -ge 0 ]; then
	remove_snmp_config_key;
	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
	FABOS_SWITCHNO=0
	correcthost /fabos/cliexec/config remove system.perrThreshold
	correcthost /fabos/cliexec/config remove system.perrFaultFlg
	correcthost /fabos/cliexec/configcommit
	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
fi

#case 1:
#Removing Home VF and chassis role field in ldap.map file if it exists when downgrade from v8.1.0 to v8.0.x or v7.x.x
if [ "$FROM_MAJOR" -eq 8 -a "$FROM_MINOR" -ge 1 -a "$FROM_PATCH" -ge 0 ]; then
        if [ "$TO_MAJOR" -lt 8 -o "$TO_MAJOR" -eq 8 -a "$TO_MINOR" -lt 1 ]; then
                if [ -f /etc/fabos/ldap.map ]; then
                pizza=`/fabos/bin/slotshow | grep -c "Not supported on this platform"`
		if [ $ACTIVECP ]; then
			isActiveCp=1
		else
			isActiveCp=0
		fi
                        if [ "$pizza" -ne 0 -o "$isActiveCp" -eq 1 ]; then
                                correcthost /bin/sed -r 's/:/*/2' /etc/fabos/ldap.map | sed 's|*\(.*\)*.$|\1|' > /tmp/ldap
                                correcthost /bin/sed -r 's/=/*/1' /tmp/ldap | sed 's|*\(.*\)*.$|\1|' > /tmp/ldap1
                                correcthost /bin/sed '/^$/d' /tmp/ldap1 > /tmp/ldap2
                                correcthost /bin/cat /tmp/ldap2 > /etc/fabos/ldap.map
                                correcthost /bin/cat /tmp/ldap2 > /mnt/etc/fabos/ldap.map
                                correcthost /bin/rm /tmp/ldap
                                correcthost /bin/rm /tmp/ldap1
                                correcthost /bin/rm /tmp/ldap2
                        else
                                correcthost "/bin/sed -r 's/:/*/2' /etc/fabos/ldap.map | sed 's|*\(.*\)*.$|\1|' > /tmp/ldap"
                                correcthost "/bin/sed -r 's/=/*/1' /tmp/ldap | sed 's|*\(.*\)*.$|\1|' > /tmp/ldap1"
                                correcthost "/bin/sed '/^$/d' /tmp/ldap1 > /tmp/ldap2"
                                correcthost "/bin/cat /tmp/ldap1 > /etc/fabos/ldap.map"
                                correcthost "/bin/cat /tmp/ldap1 > /mnt/etc/fabos/ldap.map"
                                correcthost "/bin/rm /tmp/ldap"
                                correcthost "/bin/rm /tmp/ldap1"
                                correcthost "/bin/rm /tmp/ldap2"
                        fi
                correcthost /fabos/cliexec/config save /etc/fabos/ldap.map
                correcthost /fabos/cliexec/config save /mnt/etc/fabos/ldap.map
                fi
        fi
fi
#case 2:
#Adding vf and chassis role field in ldap.map file if it exists when upgrade from v8.0.x or v7.x.x to v8.1.0
if [ "$FROM_MAJOR" -lt 8 -o "$FROM_MAJOR" -eq 8 -a "$FROM_MINOR" -lt 1 ]; then
        if [ "$TO_MAJOR" -eq 8 -a "$TO_MINOR" -ge 1 -a "$TO_PATCH" -ge 0 ]; then
                if [ -f /etc/fabos/ldap.map ]; then
        pizza=`/fabos/bin/slotshow | grep -c "Not supported on this platform"`
		if [ $ACTIVECP ]; then
			isActiveCp=1
		else
			isActiveCp=0
		fi
                        if [ "$pizza" -ne 0 -o "$isActiveCp" -eq 1 ]; then
                                correcthost /bin/sed -r 's/$/:(null):(null)/' /etc/fabos/ldap.map > /tmp/ldap
                                correcthost /bin/sed '/^$/d' /tmp/ldap > /tmp/ldap1
                                correcthost /bin/cat /tmp/ldap1 > /etc/fabos/ldap.map
                                correcthost /bin/cat /tmp/ldap1 > /mnt/etc/fabos/ldap.map
                                correcthost /bin/rm /tmp/ldap
                                correcthost /bin/rm /tmp/ldap1
                        else
                                correcthost "/bin/sed -r 's/$/:(null):(null)/' /etc/fabos/ldap.map > /tmp/ldap"
                                correcthost "/bin/sed '/^$/d' /tmp/ldap > /tmp/ldap1"
                                correcthost "/bin/cat /tmp/ldap > /etc/fabos/ldap.map"
                                correcthost "/bin/cat /tmp/ldap > /mnt/etc/fabos/ldap.map"
                                correcthost "/bin/rm /tmp/ldap"
                                correcthost "/bin/rm /tmp/ldap1"
                        fi
                correcthost /fabos/cliexec/config save /etc/fabos/ldap.map
                correcthost /fabos/cliexec/config save /mnt/etc/fabos/ldap.map
                fi
        fi
fi
remove_keepalive_key()
{
	/fabos/bin/configshow -all | grep -qi "sysrm.keepalive.period" 
	 if [ $? -eq 0 ]; then
		/fabos/cliexec/config remove "sysrm.keepalive.period"
 		/fabos/cliexec/configcommit
	fi
}

#Remove the "auditlogall.config" for releases < 7.4.0
if [ "$TO_MAJOR" -eq 7 -a "$TO_MINOR" -lt 4 ]; then
	if [ -f /mnt/etc/config/auditlogall.config ]; then
		/bin/rm /mnt/etc/config/auditlogall.config
	fi
	# create a "/mnt/etc/audit.storage" file in 7.3 and copy last 256 messages
	echo "creating the downgrade audit storage"
	/fabos/sbin/auditdump -d
fi

# Remove the audit storage from /mnt during upgrade/downlgrade on both active/stndby
if [ -f /etc/audit.storage ]; then
	/bin/rm /mnt/etc/audit.storage 2> /dev/null
fi

if [ $STANDBYCP -eq 1 ]; then
	if correcthost test -f /etc/audit.storage; then
		correcthost /bin/rm /mnt/etc/audit.storage 2> /dev/null
	fi
fi

change_em_slotpersistdis_to_slotpersistdis()
{
	cmd="/fabos/cliexec/config get emkey.slotpersistdis 2" 
	key_val=`correcthost $cmd`;
	if [ $key_val ]; then
		correcthost /fabos/cliexec/config set "slotpersistdis" 2 $key_val
		correcthost /fabos/cliexec/config remove emkey.slotpersistdis
        correcthost /fabos/cliexec/configcommit
	fi
}

change_slotpersistdis_to_em_slotpersistdis()
{
	cmd="/fabos/cliexec/config get slotpersistdis 2"
	key_val=`correcthost $cmd`;
	if [ $key_val ]; then
	    correcthost /fabos/cliexec/config set "emkey.slotpersistdis" 2 $key_val
        correcthost /fabos/cliexec/config remove slotpersistdis
        correcthost /fabos/cliexec/configcommit
	fi
}


remove_fmc_feature_key()
{
	if [ "$SWBD" == "SWBD165" -o "$SWBD" == "SWBD166" ]; then
		/fabos/bin/configshow -a | grep -qi system.eth_rate_limit

		if [ $? -eq $STS_OK ]; then
			/fabos/cliexec/config remove system.eth_rate_limit
			/fabos/cliexec/configcommit
		fi
	fi
}

remove_audit_blk_key()
{
	/fabos/cliexec/config remove auditlog.msg.disable
	/fabos/cliexec/configcommit ;

}

remove_rest_http_key()
{
	# remvoe the key http.restprotocol. key supported in >= 9.0
	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
	FABOS_SWITCHNO=0
	correcthost_to_curr_vfid /fabos/cliexec/config remove http.restprotocol
	correcthost_to_curr_vfid /fabos/cliexec/configcommit
	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
}

disable_encr_trunk_C4_ports()
{
    # Determine if portCfg and lsportCfg need to have garbage bits removed.
    # Need to do this on the Active CP.
    if [ $STANDBYCP -eq 1 ] && [ -e /mnt/sbin/clean_portcfg ] ; then
        /bin/rcp /mnt/sbin/clean_portcfg root@$(otherhost):/mnt/sbin
    fi
    if [ -e /mnt/sbin/clean_portcfg ] ; then
        correcthost_all_vfs /mnt/sbin/clean_portcfg $FROM_MAJOR $FROM_MINOR $FROM_PATCH $TO_MAJOR $TO_MINOR $TO_PATCH
    fi
}

# Disable the trunk config on the encrypted ports (Skywalker Blade and Wedge)
# while doing firmware upgrade from 8.2.0v or lower version to 9.0
# and above version of firmware.
disable_encr_trunk_on_C4_platform()
{
	# Validate for Skywalker blade on Allegiance and Venator
	# Validate for Wedge platformm too.
	if [ $swbd == "SWBD165" ] || [ $swbd == "SWBD166" ] || [ $swbd == "SWBD161" ] || [ $swbd == "SWBD162" ]; then
		# Handles the migration case of 8.2.0 to 9.0
		if [ $FROM_MAJOR -eq 8 -a $FROM_MINOR -eq 2 -a $FROM_PATCH -lt 1 ]; then
			disable_encr_trunk_C4_ports
		fi
	fi

	# Upgrade from 8.1.x to 9.0 is disruptive and hence no specific action
	# is required for Skywalker blade on Allegiance and Venator.
}

remove_http_bound ()
{
	/fabos/cliexec/config remove http.BoundApplication
	/fabos/cliexec/configcommit ;
}

delete_amp22_maps_config()
{
	# clean maps custom config
	echo yes | /fabos/link_sbin/mapsconfig  --purge > /dev/null

	if [ $? -ne $STS_OK ]; then
		echo "post install script failed to run mapsconfig --purge cmd error: $?";
	fi
}

amp_unbind_configs()
{
	# clean collection config. CLI handler will take care
	# to clean in ALL LS
	mgmtapp --unbind > /dev/null

	if [ $? -ne $STS_OK ]; then
		echo "post install script failed to run mgmtapp --unbind c, error: $?";
	fi

	# this is an workaround to remove IP bound cfg from other LS
	# Check for Virtual Fabrics
	check_vf_enabled
	if [ $? -ne $STS_OK ]; then 
		CHASSISCMD="cmd_chassis" ;
		current_context=$CURRENT_VF ;
		for_all_contexts  remove_http_bound;
		context_switch $current_context ;
	else 
		remove_http_bound ;
	fi 
}

delete_amp22_config()
{
	# clean only from amp2.2 to amp3.0
	if [ $FROM_MAJOR -eq 2 -a $FROM_MINOR -eq 2 ] ; then
		$ECHO "Clean maps & collection config"

		# clean MAPS config in ALL LS
		for_all_contexts delete_amp22_maps_config

		# unbind IP bound and collection configs
		amp_unbind_configs
	fi
}

set_PermitUserEnvironment()
{
	permituser_config=`/bin/cat $SSHD_CONFIG_FILE_MNT | /bin/grep "PermitUserEnvironment" | /bin/awk '{ print $2 }' `
	/bin/sed '/PermitUserEnvironment/ s/'$permituser_config'/'$1'/' $SSHD_CONFIG_FILE_MNT > $TMP_SSHD
	/bin/mv $TMP_SSHD $SSHD_CONFIG_FILE_MNT
	permituser_config=`/bin/cat $SSHD_CONFIG_FILE | /bin/grep "PermitUserEnvironment" | /bin/awk '{ print $2 }' `
	/bin/sed '/PermitUserEnvironment/ s/'$permituser_config'/'$1'/' $SSHD_CONFIG_FILE > $TMP_SSHD
	/bin/mv $TMP_SSHD $SSHD_CONFIG_FILE
}

set_rekey_config()
{
	# Handle sshd config rekey when fwdl to version <v9.0
	RekeyLimit=$(grep -c "RekeyLimit" $SSHD_CONFIG_FILE)
	RekeyLimit_mnt=$(grep -c "RekeyLimit" $SSHD_CONFIG_FILE_MNT)
	if [ $RekeyLimit -gt 0 -a $RekeyLimit_mnt -eq 0 ]; then
		RekeyLimit_config=`cat $SSHD_CONFIG_FILE | grep 'RekeyLimit'`
		/bin/echo $RekeyLimit_config >> $SSHD_CONFIG_FILE_MNT
	fi
}

# check MAPS config for rules having quiet time above
# 30 days and update them to 30 days.
check_n_update_maps_qt_max_limit()
{
	$ECHO "check_n_update_maps_qt_max_limit"
	THIRTY_DAYS_IN_SECS=2592000
	
	# to reduce configshow call in loop, redirect to file
	# and work on the file.
	CONFIGSHOW_ADV | grep 'maps\.rule\.' > /tmp/md_qt_logs

	for rule in `cat /tmp/md_qt_logs |grep qt= |cut -d':' -f 1|cut -d'.' -f 3`
	do
		curqt=`cat /tmp/md_qt_logs | grep -w $rule: | grep qt= | tr -s ' ' | cut -d' ' -f 4 |cut -d'=' -f 2`

		$ECHO "Rule: $rule Current qt: $curqt"

		# If value is very large it goes -ve in shell so compare -lt 0
		if [[ $curqt -lt 0 || $curqt -gt $THIRTY_DAYS_IN_SECS ]]; then

			$ECHO "$rule greater than 30 days. Update rule to 30days"

			rcmd="/fabos/sbin/mapsrule --config $rule -qt $THIRTY_DAYS_IN_SECS"
			ret=$(runMapsCliCommand "$rcmd")
		else
			$ECHO "Smaller than 30 days"
		fi
	done
	rm -f /tmp/md_qt_logs
}

maps_update_rule_qt_max_limit()
{
    # CHECk VF enabled
    if [ $VF_ENABLED -ne $STS_OK ]; then
		if [ $ACTIVECP ]
		then
			for_all_contexts check_n_update_maps_qt_max_limit
		else
			for_all_contexts_standby check_n_update_maps_qt_max_limit
		fi
    else
		check_n_update_maps_qt_max_limit
    fi
}

rest_throttle_config_update()
{
	# HTTP configs are present in the default context, so update the context.
   	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
   	FABOS_SWITCHNO=0
   	samReq=`correcthost /fabos/cliexec/config get http.samplerequest 2`

	#if its default or not configured, set it to 120	
	if [ "$samReq" == "30" -o "$samReq" == "" ]; then
		correcthost /fabos/cliexec/config set http.samplerequest 2 120
		correcthost /fabos/cliexec/config save
	fi

    FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
}

remove_auditcfg_keys()
{
        if [ $CURRENT_VF -ne $def_vf_id ]; then
                correcthost_to_curr_vfid /fabos/cliexec/config remove audit.cfg.class
                correcthost_to_curr_vfid /fabos/cliexec/config remove audit.cfg.state
                correcthost_to_curr_vfid /fabos/cliexec/config remove audit.cfg.severity
                correcthost_to_curr_vfid /fabos/cliexec/configcommit
        fi
}

# auditcfg key role is changed from Switch to chassis in 9.0
# Remove auditcfg for all VF except for default VF
update_audit_cfg()
{
    # Check for Virtual Fabrics
    if [ $VF_ENABLED -ne $STS_OK ]; then
        if [ $ACTIVECP ]; then
            CHASSISCMD="cmd_chassis";
            current_context=$CURRENT_VF ;
            for_all_contexts remove_auditcfg_keys ;
            context_switch $current_context ;
        else
            for_all_contexts_standby remove_auditcfg_keys ;
        fi
    fi
}

fwdl_to_90()
{
	$ECHO "fwdl_to_90"

	# When firmware upgrade to 9.0 happens ensure the trunking configuration
	# on the encryption ports on Skywalker blade and Wedge are disabled when
	# the firmware version is 8.2.0. We do not need to bother about 8.1.0
	# since an upgrade from 8.1.0 is disruptive.
	disable_encr_trunk_on_C4_platform

	#Change permituser config value to "no"
	set_PermitUserEnvironment "no"

	# MAPS rule quiet time max limit is changed to 30 days.
	# So, upgrading to 9.0, needs to make sure existing rule quiet time
	# above 30 days to modify to 30 days.
	maps_update_rule_qt_max_limit
	
	# Removing the config key port.portSwapEnabled since
	# portswap feature is deprecated in 9.0
	if [ $TO_MAJOR -ge 9 ]; then
		check_vf_enabled
		if [ $? -ne $STS_OK ]; then
			CHASSISCMD="cmd_chassis" ;
			current_context=$CURRENT_VF ;
			for_all_contexts remove_portswap_keys;
			context_switch $current_context ;
		else
			remove_portswap_keys;
		fi
	fi

	# when upgraded to v9.0, throttling sample time should be updated to 120,
	# if default (30) is set
	rest_throttle_config_update

        # Remove auditcfg keys except for default fid
        update_audit_cfg
}

fwdl_to_82()
{
	$ECHO "fwdl_to_82"
	change_slotpersistdis_to_em_slotpersistdis

	# When firmware upgrade to 8.2.1 happens ensure the trunking configuration
	# on the encryption ports on Skywalker blade and Wedge are disabled.
	disable_encr_trunk_on_C4_platform

	if [ $TO_PATCH -lt 1 ] ; then
		remove_fmc_feature_key
	fi

	if [ $FROM_MAJOR -gt 8 ]; then
		set_rekey_config
	fi

	# Handle permituser config value
	# Set permituser config to "yes" in fw_version<v8.2.1
	# And to "no" in fw_version >=v8.2.1
	if [ $TO_PATCH -lt 1 ]; then	
		set_PermitUserEnvironment "yes"
	else
		set_PermitUserEnvironment "no"
	fi
			
	remove_audit_blk_key
	remove_rest_http_key

	#fwdl from 9.0 to 8.2.x
	if [ $FROM_MAJOR -eq 9 -a $FROM_MINOR -eq 0 ]; then
        if [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 2 -a $FROM_PATCH -ge 0 ]; then
			cp_or_rm_alpa_files ;
		fi
	fi
	
	if [ $FROM_MAJOR -eq 9 -a $FROM_MINOR -eq 0 ]; then
        if [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 2 -a $FROM_PATCH -ge 0 ]; then
			CHASSISCMD="cmd_chassis" ;
			ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 FABOS_SWITCHNO=0 CURRENT_VF=255 CURRENT_AD=0
			set_snmp_default_values ;
			correcthost_to_curr_vfid /fabos/cliexec/configcommit
			# FOS-817821
			#remove_snmp_group_users_config_key;
		fi
	fi
}

fwdl_to_81()
{
	$ECHO "fwdl_to_81"
	echo "fwdl_to_81" > /mnt/etc/audit_up_dwn
	#Remove the keepalive key
	remove_keepalive_key
	change_em_slotpersistdis_to_slotpersistdis
	remove_fmc_feature_key
	remove_audit_blk_key
	

	if [ $FROM_MAJOR -gt 8 ]; then
		set_rekey_config
	fi
	#Change permituser config value to "yes"
	set_PermitUserEnvironment "yes"

	remove_rest_http_key

        if [ $FROM_MAJOR -eq 9 -a $FROM_MINOR -eq 0 ]; then
        if [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 1 -a $FROM_PATCH -ge 0 ]; then
                        CHASSISCMD="cmd_chassis" ;
                        ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 FABOS_SWITCHNO=0 CURRENT_VF=255 CURRENT_AD=0
                        set_snmp_default_values ;
                        correcthost_to_curr_vfid /fabos/cliexec/configcommit
                fi
        fi
}

fwdl_to_80()
{
	$ECHO "fwdl_to_80"
	echo "fwdl_to_80" > /mnt/etc/audit_up_dwn
	#Remove the keepalive key
	remove_keepalive_key
	change_em_slotpersistdis_to_slotpersistdis
	remove_fmc_feature_key
	remove_audit_blk_key
	remove_rest_http_key
}
fwdl_to_21()
{
	$ECHO "fwdl_to_21"
	# Add functions here if anything to be invoked during fwdl to 2.1
}
fwdl_to_22()
{
	$ECHO "fwdl_to_22"
	# Remove secondary partition if upgrade from 2 or higher to 2.2
	if [ $FROM_MAJOR -ge 2 -a $FROM_MINOR -eq 2 ] ; then
		if [ -f /etc/audit.storage ]; then
			/bin/rm /mnt/etc/audit.storage 2> /dev/null
		fi
	fi
}

# cleans up to be handled before going to amp3.0
fwdl_to_amp30()
{
	# clean the maps and collection config from all fids
	delete_amp22_config
}

# To handle different down grade cases
case "${TO_MAJOR}.${TO_MINOR}" in
	'9.0')
		fwdl_to_90
	;;
	'8.2')
		fwdl_to_82
	;;
	'8.1')
		fwdl_to_81
	;;
	'8.0')
		fwdl_to_80
	;;
	'3.0')
		fwdl_to_amp30
	;;
	'2.1')
        fwdl_to_21
    ;;
    '2.2')
        fwdl_to_22
    ;;
	*)
		#fwdl_to_74_lower
	 ;;
esac

#add snmp informs tags if it is upgrade from pre7.4 to >=7.4
# AMP base version is 7.4 Hence skip the conditon in AMP
if ( ( [ "$FROM_MAJOR" -lt 7 ] || [ "$FROM_MAJOR" -eq 7 -a "$FROM_MINOR" -lt 4 ] ) && [ $ANALYTICS_FLAG -eq 0 ] ) ; then
    add_snmp_informsTag
fi

#remove snmp informs tags if it is downgrade from >=7.4 to pre7.4
# AMP base version is 7.4 hence skip the conditon in AMP
if  ( ( [ "$TO_MAJOR" -lt 7  ] || [ "$TO_MAJOR" -eq 7 -a "$TO_MINOR" -lt 4 ] ) && [ $ANALYTICS_FLAG -eq 0 ] ) ; then
    remove_snmp_informsTag
fi

if [ $ANALYTICS_FLAG -eq 1 -a "$TO_MAJOR" -lt 2 ]; then
	# Check for Virtual Fabrics
	check_vf_enabled
	if [ $? -ne $STS_OK ]; then 
		CHASSISCMD="cmd_chassis" ;
		current_context=$CURRENT_VF ;
		for_all_contexts  remove_http_bound;
		context_switch $current_context ;
	else 
		remove_http_bound ;
	fi 
fi

#
# Upgrade from v7.2.0 to v7.2.1/v7.3
#
if [ $FROM_MAJOR -eq 7 -a $FROM_MINOR -eq 2 -a $FROM_PATCH -eq 0 ]; then
	# "config get" for fips mode returns value only if called from
	# default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
	# revert it back to its original value after "config get"
	checkFipsMode
	retVal=$?
	if [ $retVal -eq 1 ]; then
		/mnt/fabos/sbin/sshdconfigupdate ServerHostKeySize 1
	        /mnt/fabos/sbin/sshdconfigupdate MinPrime 1
        	/mnt/fabos/sbin/sshdconfigupdate ShaValue 1 postinst

		#Explicitly adding to secondary partition since config save does not happen on STANDBY CP
    		if [ $STANDBYCP -eq 1 ] ; then
        		/usr/sbin/chroot /mnt /fabos/sbin/sshdconfigupdate ServerHostKeySize 1
		        /usr/sbin/chroot /mnt /fabos/sbin/sshdconfigupdate MinPrime 1
        		/usr/sbin/chroot /mnt /fabos/sbin/sshdconfigupdate ShaValue 1 postinst
		fi

		if [ -f "/mnt/etc/ssh_host_rsa_key" ]; then
		        /bin/rm /mnt/etc/ssh_host_rsa_key > /dev/null  2>&1
		fi

		if [ -f "/mnt/etc/ssh_host_rsa_key.pub" ]; then
		        /bin/rm /mnt/etc/ssh_host_rsa_key.pub > /dev/null  2>&1
		fi
		/usr/bin/ssh-keygen -b 2048 -t rsa -f /mnt/etc/ssh_host_rsa_key -N "" > /dev/null  2>&1
		/bin/chmod 600 /mnt/etc/ssh_host_rsa_key
		/bin/chmod 600 /mnt/etc/ssh_host_rsa_key.pub
   	fi
fi

if [ -f '/mnt/fabos/cliexec/delduprule' ] ; then
	if [ $ACTIVECP ] ; then
		correcthost_all_vfs /mnt/fabos/cliexec/delduprule
	else
		/bin/rcp /mnt/fabos/cliexec/delduprule root@$(otherhost):/fabos/cliexec/delduprule
		correcthost_all_vfs /fabos/cliexec/delduprule
	fi
fi

#*******SSH host key conversion
ssh_rekeylimit_conversion

### PrivilegeSeparation, ServerKeybits and PrintLastlog Handling
sshd_config_handling

### MinPrime, ServerHostKeySize Handling
ssh_fips_config_handling

#******* Maintenance account support
maintenance_conversion

#***** LDAPS support
ldaps_protocol_handling

set_secure_mode() {
	/fabos/cliexec/config set cfgload.secure 2 1
	/fabos/cliexec/configcommit
}

# Set the cfgload.secure to 1 for these platforms.
if [ "$SWBD" == "SWBD156" ]; then
	check_vf_enabled
	if [ $? -eq $STS_ERR ]; then
		current_context=$CURRENT_VF
		if [ $current_context != $def_vf_id ]; then
			context_switch $def_vf_id
			set_secure_mode
		else
			set_secure_mode
		fi
	else
		set_secure_mode
	fi
fi

# savepsnewfwver()
# Parse .bin (binary executable) filenames for
# the PSU's Com, LLC, Pri firmware versions
# And Save the psu's new firmware versions in /etc/fabos/psnewfwver
# in the following format:  
# PpLlCc
#   where   P = Major Version#, p = minor version# for Pri image
#           L = Major Version#, l = minor version# for LLC image
#           C = Major Version#, c = minor version# for Com image
#   Example:
#   If the new dist has these PSU new firmware version files:
#       Brocade_GEN_6_ECD16020042_Com_Ver_3_1.bin*
#       Brocade_GEN_6_ECD16020042_LLC_Ver_3_2.bin*
#       Brocade_GEN_6_ECD16020042_Pri_Ver_3_4.bin*
#   Then this function will save the parsed version number
#   in file /mnt/etc/fabos/psnewfwver as
#   343231
#
savepsnewfwver()
{
	oldpwd=`pwd`
    cd /mnt/fabos/factory
    ComMaj=$(ls Brocade*Com*  > /dev/null  2>&1 | awk -F'Ver' '{print $2}'| awk -F'_'  '{print $2}')
    ComMin=$(ls Brocade*Com*  > /dev/null  2>&1 | awk -F'Ver' '{print $2}'| awk -F'_'  '{print $3}' | awk -F'.' '{print $1}')
    LLCMaj=$(ls Brocade*LLC*  > /dev/null  2>&1 | awk -F'Ver' '{print $2}'| awk -F'_'  '{print $2}')
    LLCMin=$(ls Brocade*LLC*  > /dev/null  2>&1 | awk -F'Ver' '{print $2}'| awk -F'_'  '{print $3}' | awk -F'.' '{print $1}')
    PriMaj=$(ls Brocade*Pri*  > /dev/null  2>&1 | awk -F'Ver' '{print $2}'| awk -F'_'  '{print $2}')
    PriMin=$(ls Brocade*Pri*  > /dev/null  2>&1 | awk -F'Ver' '{print $2}'| awk -F'_'  '{print $3}' | awk -F'.' '{print $1}')
    cd $oldpwd

	if [ -z $ComMaj ]; then ComMaj=0; fi
	if [ -z $ComMin ]; then ComMin=0; fi
	if [ -z $LLCMaj ]; then LLCMaj=0; fi
	if [ -z $LLCMin ]; then LLCMin=0; fi
	if [ -z $PriMaj ]; then PriMaj=0; fi
	if [ -z $PriMin ]; then PriMin=0; fi

    echo $PriMaj$PriMin$LLCMaj$LLCMin$ComMaj$ComMin > /mnt/etc/fabos/psnewfwver
}

# This call belongs in check_post_features.
# But there it will not be effective at the time of upgrading to this image.
# So also adding it here so it will be invoked 
# even when upgrading for the first time to an image with the psu enhancement
if [ $swbd == "SWBD165" -o $swbd == "SWBD166" ]; then
	savepsnewfwver
fi

# Elminate all the white space to see if any ports are in the
# list.
t=$(echo $iface_list | sed -e "s/ //g" )

# If there are no non-white space characters left, then the
# port list is empty, so there is no need to send Hello messages
if [ -z $t ]
then
 exit 0
fi


# Create the link to the internal command
# First make sure we are in our home directory
cd /root
if [ ! -x fspfHATest ]
then
 /bin/ln -s /mnt/fabos/bin/fspf_tst fspfHATest
fi

# #############################

send_hellos 1>postinst.out 2>&1 &

disown %1

exit 0
