#!/bin/sh
#
#    Copyright (c) 2004-2018 Brocade Communications Systems, LLC.
#    All rights reserved.
#
#    Description:
#
#        This pre-install script will be run before firmware
#        download or firmwarerestore starts. 
#
MSG="
There  is  a  problem  with  the  firmware  image  installed  on  the  server.
The preinst file is in DOS format. Please reload the firmware image on server,
using the right tool/options  (to prevent  DOS style  ASCII file conversions),
and then retry firmwaredownload.  "; # comment so ^M will not impact MSG.
#set -x
check4dos() { if [ $# -gt 1 ] ; then echo "$MSG" ; exit 5 ; fi ; } ; check4dos 1 

#
# Note the extra space (above) at the end of the call "check4dos 1 " right here ^
# This space is very important for it to work correctly.
# In case of dos conversion it will add a ^M at the end of this space.
# That will make it look like calling check4dos with 2 parameters,
# and result in $MSG being printed out instead of the current failure
# ": not a signal specification" which does not convey what exactly went wrong.
#
# This will not address all types of conversion errors though.
# We have seen cases wher ^M was added at the end of PATH below.
# To address that a space has been added at the end of that line
#

##################################################################################
#  Attention!!  Attention!!  Attention!!  Attention!!  Attention!!  Attention!!  # 
#  ---------    ---------    ---------    ---------    ---------    ---------    #
#              Add Only TAGS here! This is the TAGs section.........              #
# Please do not remove these lines in all future merges. These are feature TAGS. #
# each TAG in a given preinst script indicates support for the respective feature#
# in that version of FOS. The TAG method of compatibility checking/fwdl blocking #
# was first introduce to block fwdl of versions not supporting 8548 Rev 3.1 CPU  #
# on zentron 4 CP and then extended to support these other subsequent features.  #
#																				 #
# TAG method provides a finer granularity compatibility checking/fwdl blocking   #
# at the patch id level, thereby permitting feature porting to patch versions.   #
# These defines are for use with the check_features.sh.in script where all the   #
# firmware version compatibility checking and firmwaredownload blocking resides. #
# the TAGs are NOT for use by preinst script itself. This is because there is no #
# guarantee as to  whether the preinst of the current version or the new version #
# will be invoked. fwdl always invokes the higher FOS version's preinst script.  #
# if <major>.<minor>.<patch> version of the current and new (to be downloaded)   #
# FOS version are equal then it invokes the preinst of the to be downloaded FOS  #
#																				 #
##################################################################################

CP31_ZENTRON4_SUPPORTED="Version Supports 8548 Rev 3.1 CP"
NON_DFE_SUPPORTED="Version Supports NON DFE"
QSFPP_ICL_SUPPORTED="Version Supports QSFPP ICL"
BUF_OP_MODE_SUPPORTED="Version Supports BufOpMode"
GEN6_BUF_OP_MODE_SUPPORTED="Version Supports Gen 6 BufOpMode"
Q20_SWBD134_SUPPORTED="Version Supports Q20 for Huawei"
ROOT_PERMANET_DISABLE_SUPPORTED="Version Supports Permanetly Disable root for Huawei"
IPFILTER514_SUPPORTED="Skybolt does not boot with this. warn user to remove 514"
NONDFE_FORCE_DISABLE_SUPPORTED="Version supports portcfgnondfe --force_disable"
TACACS_ENCRYPTION_SUPPORTED="Version Supports TACACS Encryption"
RADIUS_TACACS_ENCRYPTION="Version has encrypted secrets"
CHEW_SERDES_SUPPORTED="SBI:0x101b_0x01_SI:0xFE5D_0045"
SOLO_SUPPORTED="Supports solo device"
QSFP_32G_ICL_SUPPORTED="This verison Supports 2KM 32G QSFP ICL"
NEW_128MB_FLASH_SUPPORTED="This verison Supports the new 128MB Flash"
QSFP_32G_2KM_ICL_NON_ICL_SUPPORTED="Version Supports 2KM 32G QSFP in both ICL and NON ICL Ports"
WEDGE_CR_SUPPORT="Version support LCW"
LS_ACC_CLEAN_ADDRESS_BIT_SUPPORTED="Version supports Clean Address Bit"
BSN_SUPPORT_LINK_SUPPORTED="Version supports BSL"
EMULEX_FPORT_TRUNKING_SUPPORTED="Version supports Emulex F-Port Trunking"
LDAP_ROLE_NAME_LENGTH_64_SUPPORTED="This version supports LDAP role name with length 64 characters"
DOWNGRADE_UPGRADE_FROM_V81X_TEST_ONLY_SUPPORTED="Version supports downgrade to & upgrade from v8.1.x_test_only_release builds"
V8X_SUPPORTING_EULA="FOS8.x Version that supports EULA"
SSH_PERMIT_USER_ENV_NOTSUPPORTED="PermitUserEnvironment is not supported"
CYPRESS_MID01_BOOTFLASH_SUPPORTED="Version support for the new Cypress 16M BootFlash-do not use 9.0 Tag - use this for this support"
HUAWEI_SPECIAL_SWBD_SUPPORTED="This special verison of huawei switches without encryption support"
EXTN_PRE90_GEN7_MEDIA_SUPPORTED="Version 8.x supports Gen7 media on extension platform"
DEFAULT_ADMIN_ACCOUNT_CHECK="Support to disable/enable default accounts from the custom users with admin privileges"
WWN_FAILURE_MITIGATION_SUPPORTED="This version supports WWN failure mitigation using CF on CP as backup"

#################################################################################
##     END of TAGs Section.........                                            ##
#################################################################################

# Trap / Ignore SIGINT so user cannot interrupt this script with ^C
trap "" 2
trap "" SIGPIPE

#
# Passed in version numbers
#
TO_MAJOR=$1
TO_MINOR=$2
TO_PATCH=$3

PREINST="/sbin/preinst"
ENC_VERSION_STR="6.1.1_enc"
ENC_VERSION_STR_DEV="6.1.1orion"
CEE_VERSION_STR="6.1.2_cee"
RELEASE_FILE="/tmp/release.plist"
RESTORE_FILE="/mnt/fabos/share/release"
CHECK_FEATURES_FILE="/sbin/check_features"
MAPS_WARN_FILE="maps_82_warning.txt"
#
# When firmwaredownload is invoking this script,
# TYPE should be NULL; when firmwarerestore is
# invoking it, TYPE is "restore"
#
if [ "$4" = "restore" ]; then
    TYPE=$4
    FWNAME=$5
else
    FWNAME=$4
    TYPE=""
fi

CHASSISCONFIG=/bin/getchassisconfig
AUTHORIZED_KEYS_PATH=/fabos/users/admin/.ssh/

##########################################################
#    Begin Common code for Preinst / check_features      #
#    Need to move this to common file shared by the      #
#    2 scripts to prevent finding/fixing same bug twice  #
##########################################################

PATH=/bin:/usr/bin:/sbin:/usr/sbin # adding comment to protect from DOS conversion
#
# Common variables
#
NULL=/dev/null
if [ "$DEBUG" = 1 ]; then
	ECHO='echo -e'
else
	ECHO=:
fi

# This should match the file name in src/lib/upgrade/upgrade.c
STATUS_FILE=/tmp/fwdl_err.txt
BNA_STATUS_FILE=/tmp/bna_fwdl_err.txt

#
# Error codes - these have to match the error codes
# in fwdl.h.
#

STS_OK=0
STS_ERR=255

AMP_22_CONFIG_SIZE=30000
RET_CODE=${STS_OK}
RET=${STS_OK}

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

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

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

# Determine the system platform identifier.
SWBD=`sin | swbd 2> ${NULL}`
CPID=`sin | cpid 2> ${NULL}`


otherhost(){
#        printf 10.0.0.$((5+$(othercp)))
	case ${SWBD##SWBD} in
	'62')
	    printf 127.1.1.$((8 - CPID % 2))
	    ;;
	'77')
	    printf 127.1.1.$((6 - CPID % 2))
	    ;;
	'141')
		printf 127.1.$((17 - CPID % 2)).$((17 - CPID % 2))
	    ;;
	'142')
		printf 127.1.$((15 - CPID % 2)).$((15 - CPID % 2))
	    ;;
	'165' | '166')
	    printf 127.3.1.$((2 - CPID % 2))
	    ;;
	*)
	    printf 10.0.0.$((6 - CPID % 2))
	    ;;
	esac
}

HASHOW="$(/fabos/bin/hashow)"
hashow_cmd=$(ls /fabos/cliexec/hashow)
if [ "$hashow_cmd" != "/fabos/cliexec/hashow" ]; then
       	hashow_cmd="/fabos/bin/hashow"
fi

othercp(){
        that=${HASHOW#*Remote CP \(Slot}
        that="${that%%,*}"
        printf $(($that - 5))
}


ha_role() {
 	case "$($hashow_cmd | ( read a; echo $a ))" in
	    *Local*Active*)
	    printf "ACTIVE"
 	    ;;
	    *Local*Standby*)
	    printf "STANDBY"
 	    ;;
	    *"Not supported"*)
	    printf "ACTIVE"
 	    ;;
	    *)
	    printf "STANDBY"
	    ;;
	esac
}

HA_ROLE=$(ha_role)
if [ $HA_ROLE == "ACTIVE" ]; then
    ACTIVECP=1
fi

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
}

HA_STATE=$(ha_state)


########################################################
#    End Common code for Preinst / check_features      #
########################################################


BNA_WARN_STATUS_FILE=/tmp/bna_fwdl_warn.txt
FCIP_STATUS_FILE=/tmp/fcip_fwdl_err.txt
APPSERVER_STATUS_FILE=/tmp/appserver_status_file.txt
ENC_BLOCK_DGRD_FILE=/tmp/enc_block_dgrd.txt


# clear status file
echo > $STATUS_FILE
echo " " > $STATUS_FILE
echo > $BNA_STATUS_FILE
echo " " > $BNA_STATUS_FILE
if [ -z $TYPE ]; then
	echo "The following item(s) need to be addressed before downloading the specified firmware:" >> $STATUS_FILE
else
	echo "The following items need to be addressed before restoring the specified firmware:" >> $STATUS_FILE
fi

add_err_status(){
	echo -e "$1" >> $STATUS_FILE
	if [ "$#" -eq "1" ]; then
		echo -e "$1" >> $BNA_STATUS_FILE
	elif [ "$#" -eq "2" ]; then
		echo -e "$2" >> $BNA_STATUS_FILE
	fi	
}

add_warn_status(){
                echo -e "$1" >> $BNA_WARN_STATUS_FILE
}


add_err_status_fid(){
	if [ "$#" -eq 2 ]; then
		echo -e "$1" "$2" >> $STATUS_FILE
		echo -e "$1" "$2" >> $BNA_STATUS_FILE
	elif [ "$#" -eq 3 ]; then
		echo -e "$1" "$3" >> $STATUS_FILE
		echo -e "$2" "$3" >> $BNA_STATUS_FILE
	fi
	
}

add_warn_status_fid(){
                echo -e "$1" "$2" >> $BNA_WARN_STATUS_FILE
}

is_fwdl_arg() {

	#
	# Reads command line args passed to firmwaredownload
	# and checks if the required argument is specified
	#
	for arg in $(/usr/bin/tr '\0' ' ' < /proc/$PPID/cmdline)
	do
            case $arg in
            (-*$1*)
		return $STS_OK
		;;
            esac
        done
        return $STS_ERR
}

allow_nondisruptive_fwdl() {
	# Skip for restore
	if [ -n "$TYPE" ]; then
		$ECHO " running firmwarerestore"
		return $STS_OK
	fi

    # Allow 6.1.2_cee <-> 6.3 HCL on Elara
    # For others, allow only disruptive fwdl
    case ${SWBD##SWBD} in
    '76')
        ;;
    *)
		is_fwdl_arg "s"
		local singlemode=$?
		is_fwdl_arg "f"
		local forcemode=$?
		if [ $singlemode -ne 0 -o $forcemode -ne 0 ]; then
			return $STS_ERR
		fi
		;;
	esac

	return $STS_OK
}


STS_AUTOBOOT_ERR=254
allow_disruptive_single_mode_fwdl() {
	# Skip for restore
	if [ -n "$TYPE" ]; then
		$ECHO " running firmwarerestore"
		return $STS_OK
	fi
	local slotbased= 
	local auto_boot=
	is_fwdl_arg "s"
	local singlemode=$?
	if [ $singlemode -ne 0 ]; then
		return $STS_ERR
	fi
	slotbased=`/sbin/bootenv slotbased 2>/dev/null| grep yes`
	
	if [ "$slotbased" != "yes" ] ; then
		auto_reboot=`/sbin/bootenv autoboot 2>/dev/null | grep yes`
		if [ "$auto_reboot" = "yes" ] ; then
			#return $STS_ERR		
            return $STS_AUTOBOOT_ERR;
		fi
	fi
	return $STS_OK
}

handle_disruptive_single_mode_fwdl() {
    allow_disruptive_single_mode_fwdl
    local tempvar=$?
        if [ $tempvar != $STS_OK ]; then
            if [ $tempvar = $STS_AUTOBOOT_ERR ]; then
                add_err_status "$DISRUPTIVE_FWDL_AUTOBOOT_DISABLE" "$BNA_UNSUPPORTED_NON_DISRUPTIVE_MODE_FWDL"
            elif [ $tempvar = $STS_ERR ]; then
                add_err_status "$UNSUPPORTED_NON_DISRUPTIVE_MODE_FWDL" "$BNA_UNSUPPORTED_NON_DISRUPTIVE_MODE_FWDL"
            fi
            return $STS_ERR
        fi
    return $STS_OK
}

check_for_non_disruptive_fwdl() {
	# Skip for restore
	if [ -n "$TYPE" ]; then
		$ECHO " running firmwarerestore"
		return $STS_ERR
	fi

	is_fwdl_arg "s"
	local singlemode=$?
	if [ $singlemode -ne 0 ]; then
		return $STS_ERR
	fi

	return $STS_OK
} 

check_autoreboot_opt() {
	# Skip for restore
	if [ -n "$TYPE" ]; then
		$ECHO " running firmwarerestore"
		return $STS_OK
	fi

	is_fwdl_arg "b"
	local auto_reboot=$?
	if [ $auto_reboot -eq 0 ]; then
		return $STS_ERR
	fi

	return $STS_OK
}


handle_disruptive_single_mode_fwdl_amp() {
    check_for_non_disruptive_fwdl
    local tempvar=$?
        if [ $tempvar != $STS_OK ]; then
            add_err_status "$UNSUPPORTED_NON_DISRUPTIVE_MODE_FWDL" "$BNA_UNSUPPORTED_NON_DISRUPTIVE_MODE_FWDL"
            return $STS_ERR
        fi
    return $STS_OK
}

TEST() {

	$ECHO  -n "TEST $1 "
	if [ $HA_ROLE == "STANDBY" ] && [ $HA_STATE == "NOSYNC" ]; then
	    return $STS_OK
	fi

	$1
 	if [ "$?" -ne "$STS_OK" ]; then
		$ECHO "failed"
		if [ "$#" -eq "2" ]; then
			add_err_status "$2"
		elif [ "$#" -eq "3" ]; then
			add_err_status "$2"	"$3"
		fi		
		RET_CODE=$STS_ERR
		return $STS_ERR
	fi

	$ECHO "passed"
	return $STS_OK
}

TEST_FIDS()
{
	check_failed=0
	FID_CONTEXT="FID(s)"
	SPACE_STRING=" "
	PERIOD="."
	COMMA=","
	num_err=0
	rval=$STS_OK
	local_flag=$?
	non_vf_switch="the switch"

	$ECHO  -n "TEST $1 "
	if [ $(ha_role) == "STANDBY" ] && [ $(ha_state) == "NOSYNC" ]; then
	    return $STS_OK
	fi
	if [ $VF_ENABLED -ne $STS_OK ]; then 
		if [ $(ha_role) == "ACTIVE" ]; then
			FID_LIST=${CONTEXTS}
		else
			/bin/ln -s /fabos/cliexec/lscfg_util /fabos/link_sbin/lscfg_test 2> /dev/null
			export PATH=/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/link_rbin:/fabos/factory:/fabos/xtool
			STANDBY_FIDS=`lscfg_test --all | grep -e "[0-9]" | grep -v "Total" | \
							awk '{ print $2 }'`
			FID_LIST=$STANDBY_FIDS
		fi

		for FID in $FID_LIST
		do
			context_switch $FID
			$1
			if [ $? -ne $STS_OK ]; then
				check_failed=1
				num_err=`expr $num_err + 1`
				if [ $num_err -eq 1 ]; then
					FID_CONTEXT=$FID_CONTEXT$SPACE_STRING$FID
				else
					FID_CONTEXT=$FID_CONTEXT$COMMA$FID
				fi
			else
				continue
			fi
		done
	else
		$1
		if [ $? -ne $STS_OK ]; then
			check_failed=1
			FID_CONTEXT=$non_vf_switch
		fi
	fi
	if [ $check_failed -eq 0 ]; then
		return $STS_OK
	else
		$ECHO "failed"
		FID_CONTEXT=$FID_CONTEXT$PERIOD
		if [ "$#" -eq 2 ]; then
			add_err_status_fid "$2" "$FID_CONTEXT"
		elif [ "$#" -eq 3 ]; then
			add_err_status_fid "$2" "$3" "$FID_CONTEXT"
		fi
		RET_CODE=$STS_ERR
		return $STS_ERR
	fi

}

TEST_FIDS_ADV()
{
	check_failed=0
	FID_CONTEXT="FID(s)"
	SPACE_STRING=" "
	PERIOD="."
	COMMA=","
	num_err=0
	rval=$STS_OK
	local_flag=$?
	non_vf_switch="switch"


	$ECHO  -n "TEST $1 "
	if [ $HA_ROLE == "STANDBY" ] && [ $HA_STATE == "NOSYNC" ]; then
	    return $STS_OK
	fi
	 numOfArgs="$#"; # get the last argument
	 lastArg=${!#}; # get the last argument
	 fArgs="${lastArg/funcArgs=}";
	 # it means user has not passed any function arguments
	 if [ "$fArgs" == "$lastArg" ]
	 then
	     fArgs=""
	 fi
	 arg2=$(eval echo $`echo $2`);
	 let numOfArgs=numOfArgs-1
	 if [ $numOfArgs -eq 3 ]; then
	     arg3=$(eval echo $`echo $3`);
	 fi

	if [ $VF_ENABLED -ne $STS_OK ]; then 
		if [ $HA_ROLE == "ACTIVE" ]; then
			FID_LIST=${CONTEXTS}
		else
			/bin/ln -s /fabos/cliexec/lscfg_util /fabos/link_sbin/lscfg_test 2> /dev/null
			export PATH=/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/link_rbin:/fabos/factory:/fabos/xtool
			STANDBY_FIDS=`lscfg_test --all | grep -e "[0-9]" | grep -v "Total" | \
							awk '{ print $2 }'`
			FID_LIST=$STANDBY_FIDS
		fi

		for FID in $FID_LIST
		do
			context_switch $FID
			$1 $fArgs
			if [ $? -ne $STS_OK ]; then
				check_failed=1
				num_err=`expr $num_err + 1`
				if [ $num_err -eq 1 ]; then
					FID_CONTEXT=$FID_CONTEXT$SPACE_STRING$FID
				else
					FID_CONTEXT=$FID_CONTEXT$COMMA$FID
				fi
			else
				continue
			fi
		done
	else
	    $1 $fArgs
		if [ $? -ne $STS_OK ]; then
			check_failed=1
			FID_CONTEXT=$non_vf_switch
		fi
	fi
	if [ $check_failed -eq 0 ]; then
		return $STS_OK
	else
		$ECHO "failed"
		FID_CONTEXT=$FID_CONTEXT$PERIOD
		if [ $numOfArgs -eq 2 ]; then
			add_err_status_fid "$arg2" "$FID_CONTEXT"
		elif [ $numOfArgs -eq 3 ]; then
			add_err_status_fid "$arg2" "$arg3" "$FID_CONTEXT"
		fi
		RET_CODE=$STS_ERR
		# echo "....$numOfArgs  ... $arg2"
		# cat $STATUS_FILE
		return $STS_ERR
	fi

}

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

context_switch()
{
    if [ $VF_ENABLED -ne $STS_OK ]; then
        if [ "$1" != "chassis" ]
        then
            eval $(/fabos/cliexec/lscfg_util --switch $1)
        else
            eval $(/fabos/cliexec/lscfg_util --chassis)
            #export CHASSIS_ROLEID=0
        fi
    fi
	glb_vf_id="$CURRENT_VF"
	glb_ls_id="$FABOS_SWITCHNO"
    export ROLE_ID=root
}

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
}


# 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
#}
	CONTEXTS=$($CHASSISCMD /fabos/cliexec/configshow -all | sed -n 's/Fabric ID =//p')



glb_ls_id=0
glb_vf_id=128
def_vf_id=128

# 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
}

#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() {
    # 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

# 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} ; 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
}

#
# vf_enabled
#
# Check whether VF is enabled
# both Active and Standby have this information
#
check_vf_enabled() {
	/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

}

correcthost() {
    if [ $ACTIVECP ]; then
	"$@"
    else
	/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CURRENT_AD=0 "$@"
    fi
}


# get the current firmware version
CUR_MAJOR=$(/sbin/getfabosver | sed -n -e 's/Major://gp')
CUR_MINOR=$(/sbin/getfabosver | sed -n -e 's/Minor://gp')
CUR_PATCH=$(/sbin/getfabosver | sed -n -e 's/Patch://gp')
PEER_MAJOR=$(correcthost /sbin/getfabosver | sed -n -e 's/Major://gp')
PEER_MINOR=$(correcthost /sbin/getfabosver | sed -n -e 's/Minor://gp')

#
# 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() {
	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
}

# 7800/FX8-24
# executes the provided function in the context of all configured virtual
# fabrics, and logical switches on the active and standby CP's to determine
# if a critera is met
correcthost_all_vfs() {
	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
}


###################################################
### The messages are for firmwarerestore.	###
###################################################
FWDL_RUNNING_MSG="Firmwaredownload or firmwarecommit is already running. Please wait for it to complete first."
FWRESTORE_DISALLOWED_MSG="No need to run firmwarerestore because firmware has already been committed, or there is no firmwaredownload performed."
FWRESTORE_VER_DISALLOWED_MSG="Firmwarerestore from v6.3.x to v6.1.2_cee is not supported. Please run firmwarecommit first and then download the new firmware."

###################################################
###################################################
####                                           ####
####                                           ####
####     PRESINSTALL MESSAGES SECTION          ####
####    ------------------------------         ####
####                                           ####
###################################################
###################################################
UNSUPPORTEDANALYTICSMSG="Cannot download the requested firmware because the firmware doesn't support Analytics mode on this platform. Please disable the Analytics mode and try again."
UNSUPPORTED_DL_VERMSG="Cannot downgrade to 7.4 or lower. Please downgrade to 8.0 first and then download the desired firmware version."
UNSUPPORTED_UP_VERMSG="Cannot upgrade directly to 8.2. Please upgrade to 8.0 first and then upgrade to 8.2."
UNSUPPORTED_AMP_UP_VERMSG="Cannot upgrade directly to 3.0. Please upgrade to 2.2 first and then upgrade to 3.0."
UNSUPPORTED_NON_DISRUPTIVE_MODE_FWDL="Non disruptive firmwaredownload is not supported when firmwaredownload with two versions apart. Please try to use \"firmwaredownload\" with single mode option enabled."
DISRUPTIVE_FWDL_AUTOBOOT_DISABLE="Non disruptive firmwaredownload is not supported when firmwaredownload with two versions apart. Disruptive firmware download is disallowed when auto-boot option is enabled. Please disable auto-boot and try again."
UNSUPPORTEDPLATFORMMSG="Cannot download the requested firmware because the firmware doesn't support this platform. Please enter another firmware path."
UNSUPPORTED_FWDL_AMP="Cannot download the requested firmware because firmware downgrade from version 3.0.0 to 2.1.0 or lower is not supported in AMP."
SWITCH_FAULTY_MSG="Firmwaredownload is not allowed since the switchState is Faulty. Use \"switchShow\" to see the switch state. Please recover the switch before proceeding."
XFCIP_FEATURE_RESTRICTION="Downgrade is not allowed because some extension features did not pass firmwaredownload pre-checks (see above). Please address these issues before proceeding."
EXTN_CERT_DEL_MSG="Certificates and/or CSRs related to Extension feature are present in the switch that are not supported in the older versions. Please use \"seccertmgmt delete -all extn\" to delete them, before proceeding with downgrade."
EXTN_FIPS_UNSUPP_PSK_LEN="There are extension IPsec policies with pre-shared key size less than 32 characters. Please update all the IPsec policies with pre-shared key length of atleast 32 characters, before upgrading to v8.2.0 or higher"
EXTN_CERT_UNSUPP_FILENAME="There are extension certificates, CSRs, or private keys whose filenames have unsupported characters. Supported characters are as follows:\na-zA-Z0-9~@%_+:-\nPlease use the cli \"seccertmgmt delete\" to delete these files and then recreate them before upgrading to v8.2.1 or higher."
COMPRESSION_FWDL_RESTRICTION="In-Flight Compression is enabled. Use portenccompshow to identify which ports have compression enabled and portcfgcompress to disable compression on those ports."
ENCRYPTION_FWDL_RESTRICTION="In-Flight Encryption is enabled. Use portenccompshow to identify which ports have Encryption enabled and portcfgencrypt to disable Encryption on those ports."
ENCRYPTION_DISRUPTIVE_FWDL="In-Flight Encryption is active. Use portenccompshow to identify which ports have Encryption enabled and active, and disable those ports."
COMPRESSION_FWDL_RESTRICTION_WEDGE="Upgrade is not allowed because In-Flight Compression is enabled on ports 44-47. Use portenccompshow to identify which ports have compression enabled and portcfgcompress to disable compression on those ports."
SCAL_DOWN_TO_5K_LSAN_10K_DEV="Firmware downgrade is not allowed as some of the LSAN Zones or Devices cannot be accommodated in previous Fabric OS v8.1.0 version. \n\t1. Use \"fcrlsancount\" to configure LSAN count as 3000 or 5000. \n\t2. Use \"lsanzoneshow --maxcapacity\" to view LSAN Zones and Devices that need to be removed. \n\t3. Use \"lsanzoneshow --remove\" to generate configuration script for removal of the same."
NOS_EX_PORT_RESTRICTION="\nUpgrade to selected version is not allowed because Ex Ports are configured in NOS interop-mode. Please disable NOS interopmode configuration using \"portcfgexport\" CLI on the ports. \n"
UNSUPPORTED_SNMP_FIPS_PASS_LEN="Upgrade is not allowed since one or more snmpv3 users have auth/priv password length lesser than 8 in FIPS mode"
UNSUPPORTED_SNMP_PASS_LEN="WARNING: one or more snmpv3 users have auth/priv password length lesser than 8"
UNSUPPORTED_SNMP_FIPS_AUTH_MD5="Upgrade is not allowed since one or more snmpv3 users have unsupported auth protocol MD5 configured in FIPS mode"
SNMP_USER_PASSWD_ENCRYPTION="Downgrade is not allowed since snmpv3 user password encryption is enabled. Please use snmpconfig --set snmpv3 -disable passwd_encryption to disable it"
SNMP_USER_PASSWD_ENCRYPTION_WARN="WARNING: SNMP functionality may be affected if snmpv3 users have authentication and privacy password length lesser than 8. Please use snmpconfig --set snmpv3 to update the authentication and privacy password and it must be between 8 and 32 characters length."
UNSUPPORTED_ICL_PORT_CONFIGURATION="Firmware upgrade to Fabric OS 8.0.1 or higher is not allowed when there are more than 4 chassis interconnected through Inter-Chassis Links (ICLs) and the Enterprise ICL (EICL) license is not installed in the system. Note that even with an EICL license installed, only 10 chassis are allowed to interconnect through ICLs. You can either install an EICL license, or you must disable the additional ICL links before performing a firmware upgrade."
DISC_FRM_TYPE_CONFIGURED="Downgrade is not allowed because discard frame logging is enabled for frame type other than timeout du unroute. Please disable those discard frame types first. {Usage: framelog --disable -type [type1miss | type2miss | type6miss]}"
UNSUPPORTED_MULTIPLE_SECURE_SYSLOG="Upgrade is not allowed because switch is configured and installed with more than one secure syslog-ng server and its CA certificates, only one secure syslog-ng server supported. Please retain the certificate and configuration for single secure syslog-ng server."
BNA_UNSUPPORTED_MULTIPLE_SECURE_SYSLOG="Upgrade is not allowed because switch is configured and installed with more than one secure syslog-ng server and its CA certificates, only one secure syslog-ng server supported. Please retain the certificate and configuration for single secure syslog-ng server."
MAPS_82_WARN="In MAPS, user-defined rules are present for IP_EXTN_FLOW. These rules will not be monitored in pre-8.2.0 FOS version."
VTAP_QOS_MODE_ENABLED="vTap and QOS compatibility mode is ON. Please set this config option to OFF(configureChassis CLI)and proceed with downgrade"
VTAP_ECB_COEXIST_ENABLED="vTap and Encryption/Compression Coexistence Mode ON. Please set this config option to OFF(configurechassis CLI)and proceed with downgrade"
VTAP_ENABLED="Downgrade is not allowed as vTap flow is activated"
ANALYZER_VTAP_ENABLED="Downgrade is not allowed as both Analyzer and vTap flow are active"
MULTI_FMS_MODE_ENABLED="Warning: FMS mode is enabled on more than four logical switches. Maximum of four logical switches can be configured as CUP switches prior to FOS 8.1"
FM_ENABLED_ON_AG="Flow Mirror flow(s) exist. Please delete Flow Mirror flow(s) and proceed with downgrade."
DEVICE_QUARANTINED_ON_AG="Error: Firmaware downgrade not allowed due to devices/F-ports are quarantined by SDDQ feature in Access Gateway mode. Please recover Devices/F-ports from quarantine state and proceed with downgrade"
DISABLE_MIRROR_CONFIGURATION="Downgrade is not allowed because switch is in AG mode and Mirror port configuration is enabled on some of the ports.\nPlease use \"portcfgshow\" to get port list and use \"portcfg mirrorport <port_no> --disable\" to disable it before downgrading."
REMOTE_FOSEXEC_CONFIGURED="Downgrade is not allowed because switch is in AG mode and Remote Fosexec feature is configured on the switch. Please use the \"configure\" command to disable Remote Fosexec mode."
MAPS_UNQUAR_CONFIG_ERR="Downgrade is not allowed, because un-quarantine action is enabled. Please use 'mapsconfig --actions' command to delete this action in"  
MAPS_RE_BALANCE_CONFIG_ERR="WARNING: RE_BALANCE action is enabled - it is not supported in pre-FOS8.2.1 release. Please use 'mapsconfig --actions' command to delete this action from FID: "
BNA_821_WARN="WARNING: MAPS user defined rules for DEV_LOGIN_DIST, ALL_25Km_32GELWL_SFP will not be monitored prior to v8.2.1. Please delete these rules from the switch"
MAPS_UNINSTALL_VTAP_CONFIG_ERR="Downgrade is not allowed, because uninstall_vtap action is enabled. Please use 'mapsconfig --actions' command to delete this action in"  
MAPS_UNQUAR_RULES_CONFIG_ERR="Downgrade is not allowed, because un-quarantine action is configured in user defined rules. Please delete this action from all user defined rules present in the"
MAPS_UNINSTALL_VTAP_RULES_CONFIG_ERR="Downgrade is not allowed, because uninstall_vtap action is configured in user defined rules. Please delete this action from all user defined rules present in the"
MAPS_81_RULES_CONFIG_ERR="Downgrade is not allowed, because there are MAPS user-defined rule names with length greater than 40. Please delete these rules in"
MAPS_81_ROR_RULES_CONFIG_ERR="Downgrade is not allowed, because MAPS ROR rules are present. Please delete these rules in"
MAPS_74_WARN="In MAPS, user-defined rules are present for IO_LATENCY_CLEAR ALL_CIRCUIT_HIGH_QOS, ALL_CIRCUIT_MED_QOS, ALL_CIRCUIT_LOW_QOS and ALL_CIRCUIT_F_QOS DEV_NPIV_LOGINS monitoring. These rules will not be monitored in pre-7.4 FOS version."
MAPS_80_WARN="In MAPS, user-defined rules are present for GE_CRC, GE_LOS_OF_SIG, ALL_EXT_GE_PORTS, DAYS_TO_EXPIRE, EXPIRED_CERTS, RD_STATUS_TIME_LT_8K, RD_STATUS_TIME_8_64K, RD_STATUS_TIME_64_512K, RD_STATUS_TIME_GE_512K, WR_STATUS_TIME_LT_8K, WR_STATUS_TIME_8_64K, WR_STATUS_TIME_64_512K, WR_STATUS_TIME_GE_512K, RD_1stDATA_TIME_LT_8K, RD_1stDATA_TIME_8_64K, RD_1stDATA_TIME_64_512K, RD_1stDATA_TIME_GE_512K, WR_1stXFER_RDY_LT_8K, WR_1stXFER_RDY_8_64K, WR_1stXFER_RDY_64_512K, WR_1stXFER_RDY_GE_512K, RD_PENDING_IO_LT_8K, RD_PENDING_IO_8_64K, RD_PENDING_IO_64_512K, RD_PENDING_IO_GE_512K, WR_PENDING_IO_LT_8K, WR_PENDING_IO_8_64K, WR_PENDING_IO_64_512K, WR_PENDING_IO_GE_512K, FAN_AIRFLOW_MISMATCH, IT_FLOW, ALL_LOCAL_PIDS monitoring. These rules will not be monitored in pre-8.0.1 FOS version."
MAPS_810_WARN="In MAPS, user-defined rules are present for severity change monitoring. These rules will not be monitored in pre-8.0.1 FOS version."
BD_TO_MAPS_MIGRATION="WARNING:Latency & Congestion monitoring features of AN module are being discontinued in FOS8.0. MAPS monitors the same functionality under FPI and after upgrade FPI will start monitoring the switch."
UNSUPPORTED_PWHASH_MSG="Downgrade is not allowed because System hash type is not set to MD5, or all user passwords are not hashed using MD5. Please configure the system hash using \"passwdcfg --hash md5\" and change all account passwords before proceeding. Also verify all local passwords are configured with the MD5 hash using the command \"passwdcfg --showhash -all\"."
UNSUPPORTED_USERCONFIG_MSG="Downgrade is not allowed because access time range is configured for one or more user accounts. Please delete the access time configuration of the user account using \"userConfig --change <username> -at 00:00-00:00\" or delete the user account using \"userConfig --delete <username>\". Please ensure that access time is not configured for any accounts by executing \"userConfig --show -a\" command before proceeding further"
UNSUPPORTED_OPWHASH_MSG="WARNING !!!! Password hash in the history contains non-MD5 hash for user(s) which must be cleared to proceed with downgrade. Please confirm with [Y/N] to proceed further, when prompted for."
EUROPA_BLADE_IS_PRESENT="FCOE10-24 blade is not supported by the targeted firmware.Please remove the blade before upgrading."
LANCE_BLADE_IS_PRESENT="Lance (FS8-18) blade is not supported by the targeted firmware.Please remove the blade before upgrading."
UNSUPPORTED_VE_PORT_FLOWS_MSG="Downgrade is not allowed because one or more flows are defined on VE ports. Please delete those flows using the command \"flow --delete <flow name>\"."
DEFAULT_FORMAT_NOT_SET="Dynamic portname format is not set to default in one or more partitions. Please run \"portname -d -default\" in the corresponding partitions to set default portname format."
UNSUPPORTED_DHCPV6_OPTION="Downgrade is not permitted because the target firmware does not support DHCPV6 option.  Please disable DHCPV6 option using the CLI command ipaddrset -ipv6 -nodhcpv6 and retry firmwaredownload"
ETHSW_SERVICE_ENABLED="Upgrade to 8.x is not allowed as the Ethernet Switch Service is enabled on the switch. Disable Ethernet Switch Service and retry firmware download."
ADMIN_DOMAIN_SUPPORT_RESTRICTION="Firmware upgrade is not allowed because Admin Domains are configured. The Admin Domain feature is deprecated from Fabric OS 8.1.0. Please use \"ad --select 255; ad --show\" to view the Admin Domains configured and \"ad --delete AD_ID; ad --apply\" to delete the AD before upgrading."
DISABLE_ALIAS_PEER_ZONE="Firmware downgrade to Fabric OS 8.0.x or lower is not allowed because Alias Peer Zones are configured. Before downgrading, remove all alias members from all peer zones from"
DISABLE_ENH_ZNOBJ_NAME="Firmware downgrade to Fabric OS 8.0.x or lower is not allowed because Enhanced Zone Object Names are configured. Before downgrading, remove any zone objects containing enhanced names or modify zone object names such that they are not numeric-starting and do not contain special characters ('-', '$', '^') from"
LS_NUMBER_NOTSUPPORTED="Logical Switches with LS instance > 7 are not supported in FOS8.0 or lower. Please delete the Logical switch with LS instance >7 before downgrade. LS instance can be verified using the command \"lscfg --show -instance\"."
MANUAL_IPV6_GWY_CONFIGURED="Manually configured ipv6 gateway is present. Please remove the Manualy configured gateway ip before downgrade."
UNSUPPORTED_SSH_REKEY_MSG="Downgrade is not allowed because ssh rekey is configured.Please remove configuration by executing \"sshutil rekeyinterval 0\""
FICON_LS_NOT_SUPPORTED="Downgrade is not allowed due to the presence of FICON logical switch. Please delete the FICON logical switch using the command \"lscfg --delete [-FID]\" and retry.\n\t\t"
UNSUPPORTED_LDAP_ROLEMAP_ROOT="Download is not allowed because ldap role map to root is configured. Please check and unmap the configuration by executing \"ldapcfg --unmaprole <LDAP rolename>\""
UNSUPPORTED_LDAP_MULTIPLE_ROLEMAP="Mapping between a ldap role with multiple switch roles is not supported in pre-8.1.0 versions. Please remove those mappings using 'ldapcfg --unmaprole <LDAP rolename>' before downgrade. If required add those mappings after downgrade using 'ldapcfg --maprole <LDAP rolename>'."
GEN6_APP_SERVER_RESTRICTION="Non-disruptive firmware downgrade is not supported due to registered Application Server entries, see \"appserver --show -domain <local domain ID>\". Either disable registered devices or issue \"firmwaredownload\" with single mode option enabled."
IMPORTED_TEMPLATE_NOTSUPPORTED="One or more imported crypto template(s) consists \"X509v3, Protocol or Log\" group's attributes that are not supported in pre-8.1.0 versions. Please delete the same using \"secCryptoCfg --delete\" to downgrade."
ERROR_24_BIT_LICENSES="Upgrade of FOS is not possible due to an invalid license key.  Please contact your reseller."
SNMP_GROUPNAME_RO="SNMP V1/ V3 is set to RO group. Please use snmpconfig --set snmpv1/snmpv3 -groupname default before downgrade."
RASLOG_MODE_PRESENT="Custom Raslog Mode is not supported in pre-8.2.0. MAPS generates default RASLOGs-1001-4 for all the monitoring systems in default raslog mode"
AUL_MISS_BLK_DWLD="Firmware downgrade is not permitted. Please install Analytics Upgrade License to allow downgrade."
DYNAMIC_LAG_PRESENT="Dynamic(LACP) LAGs are not supported in pre-8.2.0. Please retry firmware downgrade after deleting the Dynamic LAG configurations."
QSFP_32G_FWDL_BLOCK="Downgrade is not allowed as some of the ports are connected with ZUA serial numbered QSFP(s). Please remove the QSFP(s) flagged and connect the supported QSFP before proceeding with the downgrade."
LACP_GLOBAL_CONFIG_PRESENT="Global LACP configurations are present in database. Set it to default using \"lacp --config -sysprio 32768\" before downgrading"
LLDP_CONFIG_PRESENT="LLDP configurations are present in database. Please remove them using \"lldp --default\" before downgrading"
FCOE_CONFIG_PRESENT="FCOE configurations are present in database. Please remove them using \"fcoe --default\" before downgrading"
FCOE_CONFIG_PRESENT_ON_TYR="FCOE configurations are not supported for this platform in targeted version. Please remove them using \"fcoe --default\" before upgrading."
LACP_LAG_NAME_VLAN_PRESENT="LAG present with name staring with vlan. Please remove them using \"portcfg lag <name> --delete\" before upgrading"
ETHERNET_CONFIG_PRESENT_ON_TYR="Ethernet configurations are not supported for this platform in targeted version. Please convert them to FC using \"portCfgFlexPort --proto fc <[Slot/]Port>\" before upgrading."
CHECK_8BIT_ROUTE_STATUS_NON_VF="There are 8bit routes installed to support more NPIV login for FC32-48 blades. Please use \"portaddress --show\" to determine which ports in FC32-48 blades are affected. These ports need to be disabled before downgrade."
CHECK_8BIT_ROUTE_STATUS_VF="There are 8bit routes installed to support more NPIV login for FC32-48 blades in default switch. Please use \"portaddress --show\" in default switch to determine which ports in FC32-48 blades are affected. These ports need to be disabled before downgrade."
ENCRYPTION_ON_WEDGE64="Downgrade is not allowed because one or more ports have encryption configured. Please disable encryption configuration on all such ports before downgrade."
ZONE_TI_MAXZONENAME="One or more TI zone name length is 64 characters. TI zone name with 64 characters may not work as expected in pre-FOS 8.2.0 releases. Execute \"zone --delete\" command to remove the TI zone names with 64 characters."
ISL_RRDY_BS="Downgrade is not allowed because ISL R_RDY mode is enabled on a port in the Base Switch. Please disable using \"portcfgislmode\" before downgrading."
FIPSMODE_NOTSUPPORTED="Warning: FIPS mode will be disabled on upgrade as it is not supported. On successful upgrade, FIPS Inside can be configured, if required.\nPlease confirm with [Y/N] to proceed further, when prompted for."
FIPSSIMULATE_NOTSUPPORTED="FIPS Simulate is not supported in the target version. Please disable the same using \"fipscfg --disable simulate\" to upgrade."
FIPSINSIDE_NOTSUPPORTED="FIPS Inside mode is not supported in the target version and the configuration will be void on downgrade. Please disable the same using \"fipscfg --disable fipsinside\" to downgrade.\nUpon successful downgrade, FIPS mode can be configured, if required."
GEN5_GEN6_PS_MISMATCH_WARN_MSG="Warning: Gen5 Power Supply is in use. Please replace it with Gen6 Power Supply for high availability operation"
MAX_IPFILTER_POLICY="More than four custom ipfilter policies are defined. Please limit the custom ipfilter polcies to four by deleting ipfilter policies using \"ipfilter --delete\""
IPFILTER_POLICY_NAME="One or more custom ipfilter policy(ies) are named \"default_ipv4_2\" or \"default_ipv6_2\". Please rename the policy(ies) by cloning them with a different name using \"ipfilter --clone\" and then deleting the \"default_ipv4_2\"/\"default_ipv6_2\" using \"ipfilter --delete\""
FMC_NOTSUPPORTED="Downgrade is not allowed because Ethernet Rate Limiting feature is enabled on Management Ports. Please disable this feature by using \"configure\" command before downgrading."
TOM_CHEW_UNSUPPORTED_DOWNGRADE="Firmware Downgrade to version 8.2.0 or below is not permitted on this platform."
ENCRYPTION_TRUNKING_ON_SKYWALKER="Downgrade is not allowed because both Trunking and Encryption are configured together on one or more ports on a FC32-48 port blade. Please check portCfgShow and disable either Trunking or Encryption on affected ports before downgrade."
MAPS_RULE_WITH_INVALID_THRESHOLD_LEN="Downgrade is not allowed because one or more user defined MAPS rules have threshold length greater than 16 characters"
AMP30_COL_UPG_WARN="WARNING!! AMPOS2.2 MAPS and Collection configurations are NOT compatible to AMPOS3.0. Upgrading to AMPOS3.0 will clear the custom configurations."
AMP30_CFG_ERR_MSG="Downgrade to AMPOS2.2 or lower version is NOT compatible to binded management server. Use the CLI mgmtapp --unbind to clear the existing configurations from all LS before downgrade."
AMP30_MD_RULE_ERR_MSG="Downgrade is not allowed because MAPS user defined configuration have incompatible rule/monitor name(s).Please refer the admin guide to remove the incompatible user defined rule(s) using \"mapsconfig --purge\" or \"mapsrule --delete <rule name>\" commands"
AMP30_MP_ERR_MSG="Current multipath entries count is more than what allowed in AMPOS2.2. Please execute CLI \"flow --reset sys_mon_analytics --lu_wwn\" to clean before downgrade." 
ADDITIONAL_REBOOT_SKYB="HCL is not supported on downgrade to 8.2.0x or prior firmware versions. Perform additional switch reboot post firmware downgrade."
ADDITIONAL_REBOOT_HRPN="HCL is not supported on downgrade to 8.2.0x or prior firmware versions. Perform additional blade slot power cycle on all SX6 blades post firmware downgrade."
ASC_CA_CERTIFICATE_SUPPORT="Downgrade is not allowed because ASC ca certificate is present in the switch. Please delete the certificate using \"seccertmgmt delete -ca -server asc\" command."
CHANGE_DEFAULT_PWD="Password(s) for admin/user are at default. Kindly change the password to non-default value before proceeding."
HALF_DUPLEX_CONFIG_PRESENT="firmwareDownload is not allowed because half duplex is configured.  Use ethif --set to clear half duplex configuration before upgrade."
IPSEC_DISABLE_WARN="IPSec feature is enabled. Please disable it by using \"ipsecConfig --disable\" CLI command, as it is deprecated in target release."
IPSEC_DISABLE_WARN_STANDBY="IPSec feature is enabled. Firmware upgrade will disable IPsec as it is deprecated in target release."
LDAPS_CONFIGURED_WARN_MSG="WARNING: LDAPS (default port 636) is not supported in the target firmware version. Please change the server configuration to StartTLS (default port 389) instead."
#######################################################
### The messages are for firmwarerestore from BNA.	###
#######################################################
BNA_FWDL_RUNNING_MSG="Firmware download or firmware commit is already running. Please wait for it to complete first."
BNA_FWRESTORE_DISALLOWED_MSG="No need to run firmware restore because firmware has already been committed, or there is no firmware download performed."
BNA_FWRESTORE_VER_DISALLOWED_MSG="Firmware restore from v6.3.x to v6.1.2_cee is not supported. Please run firmware commit first and then download the new firmware."
###################################################
###################################################
####                                           ####
####                                           ####
####     PRESINSTALL MESSAGES SECTION FOR BNA  ####
####    -------------------------------------  ####
####                                           ####
###################################################
###################################################
BNA_EUROPA_BLADE_IS_PRESENT="FCOE10-24 blade is not supported by the targeted firmware.Please remove the blade before upgrading."
BNA_LANCE_BLADE_IS_PRESENT="Lance (FS8-18) blade is not supported by the targeted firmware.Please remove the blade before upgrading."
BNA_UNSUPPORTED_DL_VERMSG="Cannot downgrade to 7.4 or lower. Please downgrade to 8.0 first and then download the desired firmware version."
BNA_UNSUPPORTED_UP_VERMSG="Cannot upgrade directly to 8.2. Please upgrade to 8.0 or higher first and then upgrade to 8.2."
BNA_UNSUPPORTED_AMP_UP_VERMSG="Cannot upgrade directly to 3.0. Please upgrade to 2.2 first and then upgrade to 3.0."
BNA_UNSUPPORTED_NON_DISRUPTIVE_MODE_FWDL="Non disruptive firmware download is not supported when firmware download with two versions apart. Please try again from cli with single mode option enabled."
BNA_UNSUPPORTEDPLATFORMMSG="Cannot download the requested firmware because the firmware doesn't support this platform. Please select another firmware."
BNA_UNSUPPORTED_FWDL_AMP="Cannot download the requested firmware beacuse Firmware downgrade from version 3.0.0 to 2.1.0 or lower is not supported in AMP."
BNA_SWITCH_FAULTY_MSG="Firmwaredownload is not allowed since the switchState is Faulty. Please recover the switch before proceeding."
BNA_UNSUPPORTED_USERCONFIG_MSG="Downgrade is not allowed because access time range is configured for one or more user accounts. Please delete the access time configuration of the user account using \"userConfig --change <username> -at 00:00-00:00\" or delete the user account using \"userConfig --delete <username>\". Please ensure that access time is not configured for any accounts by executing \"userConfig --show -a\" command before proceeding further"
BNA_EXTN_CERT_DEL_MSG="Certificates and/or CSRs related to Extension feature are present in the switch that are not supported in the older versions. Please run the cli \"seccertmgmt delete -all extn\" on the switch to delete them, before proceeding with downgrade."
BNA_EXTN_FIPS_UNSUPP_PSK_LEN="There are extension IPsec policies with pre-shared key size less than 32 characters. Please update all the IPsec policies with pre-shared key length of atleast 32 characters, before upgrading to v8.2.0 or higher"
BNA_EXTN_CERT_UNSUPP_FILENAME="There are extension certificates, CSRs, or private keys whose filenames have unsupported characters. Supported characters are as follows:\na-zA-Z0-9~@%_+:-\nPlease use the cli \"seccertmgmt delete\" to delete these files and then recreate them before upgrading to v8.2.1 or higher."
BNA_XFCIP_FEATURE_RESTRICTION="Downgrade is not allowed because some extension features did not pass firmwaredownload pre-checks. Please address these issues before proceeding."
BNA_UNSUPPORTED_ICL_PORT_CONFIGURATION="Firmware upgrade to Fabric OS 8.0.1 or higher is not allowed when there are more than 4 chassis interconnected through Inter-Chassis Links (ICLs) and the Enterprise ICL (EICL) license is not installed in the system. Note that even with an EICL license installed, only 10 chassis are allowed to interconnect through ICLs. You can either install an EICL license, or you must disable the additional ICL links before performing a firmware upgrade."
BNA_DISC_FRM_TYPE_CONFIGURED="Downgrade is not allowed because discard frame logging is enabled for frame type other than timeout du unroute. Please disable those discard frame types first. {Usage: framelog --disable -type [type1miss | type2miss | type6miss]}"
BNA_MAPS_UNQUAR_CONFIG_ERR="Downgrade is not allowed because un-quarantine action is enabled. Please use MAPS Policy Actions dialog to disable this action in"
BNA_MAPS_RE_BALANCE_CONFIG_ERR="WARNING: RE_BALANCE action is enabled. RE_BALANCE action is not supported in pre-FOS8.2.1 release. Please use MAPS Policy Actions dialog to disable this action."
BNA_MAPS_UNINSTALL_VTAP_CONFIG_ERR="Downgrade is not allowed because uninstall_vtap action is enabled. Please use MAPS Policy Actions dialog to disable this action in"
BNA_MAPS_UNQUAR_RULES_CONFIG_ERR="Downgrade is not allowed, because un-quarantine action is configured in user defined rules. Please use MAPS Policy Actions dialog to delete this action from all user defined rules in"
BNA_MAPS_UNINSTALL_VTAP_RULES_CONFIG_ERR="Downgrade is not allowed, because uninstall_vtap action is configured in user defined rules. Please use MAPS Policy Actions dialog to delete this action from all user defined rules in"
BNA_81_RULES_CONFIG_ERR="Downgrade is not allowed, because there are MAPS user-defined rule names with length greater than 40. Please delete these rules in"
BNA_81_ROR_RULES_CONFIG_ERR="Downgrade is not allowed, because there are MAPS ROR rules are present. Please delete these rules in"
BNA_BD_TO_MAPS_MIGRATION="WARNING:Latency & Congestion monitoring features of AN module are being discontinued in FOS8.0. MAPS monitors the same functionality under FPI and after upgrade FPI will start monitoring the switch."
BNA_MAPS_80_WARN="In MAPS, user-defined rules are present for GE_CRC, GE_LOS_OF_SIG, ALL_EXT_GE_PORTS, DAYS_TO_EXPIRE, EXPIRED_CERTS, RD_STATUS_TIME_LT_8K, RD_STATUS_TIME_8_64K, RD_STATUS_TIME_64_512K, RD_STATUS_TIME_GE_512K, WR_STATUS_TIME_LT_8K, WR_STATUS_TIME_8_64K, WR_STATUS_TIME_64_512K, WR_STATUS_TIME_GE_512K, RD_1stDATA_TIME_LT_8K, RD_1stDATA_TIME_8_64K, RD_1stDATA_TIME_64_512K, RD_1stDATA_TIME_GE_512K, WR_1stXFER_RDY_LT_8K, WR_1stXFER_RDY_8_64K, WR_1stXFER_RDY_64_512K, WR_1stXFER_RDY_GE_512K, RD_PENDING_IO_LT_8K, RD_PENDING_IO_8_64K, RD_PENDING_IO_64_512K, RD_PENDING_IO_GE_512K, WR_PENDING_IO_LT_8K, WR_PENDING_IO_8_64K, WR_PENDING_IO_64_512K, WR_PENDING_IO_GE_512K, FAN_AIRFLOW_MISMATCH monitoring. These rules will not be monitored in pre-8.0.1 FOS version."
BNA_MAPS_81_WARN="MAPS user defined rules for IP_EXTN_FLOW will be monitored as absolute number prior 8.2.1. Version 8.2.1 and above IP_EXTN_FLOW rules are monitored as percentage. Please re-create, or delete and then create, these rules from FID:$glb_vf_id"
BNA_UNSUPPORTED_VE_PORT_FLOWS_MSG="Downgrade is not allowed because one or more flows are defined on VE ports. Please delete those flows."
BNA_UNSUPPORTED_DHCPV6_OPTION="Downgrade is not permitted because the target firmware does not support DHCPV6 option.  Please disable DHCPV6 option using the CLI command ipaddrset -ipv6 -nodhcpv6 and retry firmwaredownload"
BNA_ADMIN_DOMAIN_SUPPORT_RESTRICTION="Firmware upgrade is not allowed because Admin Domains are configured. The Admin Domain feature is deprecated from Fabric OS 8.1.0. Please use \"ad --select 255; ad --show\" to view the Admin Domains configured and \"ad --delete AD_ID; ad --apply\" to delete the AD before upgrading."
BNA_DEFAULT_FORMAT_NOT_SET="Dynamic portname format is not set to default in one or more partitions. Please set default portname format in all partitions."
BNA_ETHSW_SERVICE_ENABLED="Upgrade to 8.x is not allowed as the Ethernet Switch Service is enabled on the switch. Disable Ethernet Switch Service and retry firmware download."
BNA_COMPRESSION_FWDL_RESTRICTION="In-Flight Compression is enabled. Use portenccompshow to identify which ports have compression enabled and portcfgcompress to disable compression on those ports."
BNA_ENCRYPTION_FWDL_RESTRICTION="In-Flight Encryption is enabled. Use portenccompshow to identify which ports have Encryption enabled and portcfgencrypt to disable Encryption on those ports."
BNA_ENCRYPTION_DISRUPTIVE_FWDL="In-Flight Encryption is active. Use portenccompshow to identify which ports have Encryption enabled and active, and disable those ports."
BNA_COMPRESSION_FWDL_RESTRICTION_WEDGE="Upgrade is not allowed because In-Flight Compression is enabled on ports 44-47. Use portenccompshow to identify which ports have compression enabled and portcfgcompress to disable compression on those ports."
BNA_ERROR_24_BIT_LICENSES="Upgrade of FOS is not possible due to an invalid license key.  Please contact your reseller."
INS_REV_MSG="This platform is not supported by 7.4.0_ins or lower. Please upgrade to a newer version."
BNA_SNMP_USER_PASSWD_ENCRYPTION="Downgrade is not allowed since the snmpv3 user password encryption is enabled. Please default snmp configuration to disalbe the encryption option."
BNA_MAPS_810_WARN="In MAPS, user-defined rules are present for Severity monitoring. These rules will not be monitored in pre-8.1.0 FOS version."
BNA_DISABLE_ALIAS_PEER_ZONE="Firmware downgrade to Fabric OS 8.0.x or lower is not allowed because Alias Peer Zones are configured. Before downgrading, remove all alias members from all peer zones from"
BNA_DISABLE_ENH_ZNOBJ_NAME="Firmware downgrade to Fabric OS 8.0.x or lower is not allowed because Enhanced Zone Object Names are configured. Before downgrading, remove any zone objects containing enhanced names or modify zone object names such that they are not numeric-starting and do not contain special characters ('-', '$', '^') from"
BNA_LS_NUMBER_NOTSUPPORTED="Logical Switches with LS instance > 7 are not supported in FOS8.0 or lower. Please delete the Logical switch with LS instance >7 before downgrade. LS instance can be verified using the command \"lscfg --show -instance\"."
BNA_MANUAL_IPV6_GWY_CONFIGURED="Manually configured ipv6 gateway is present. Please remove the Manualy configured gateway ip before downgrade."
BNA_FICON_LS_NOT_SUPPORTED="Downgrade is not allowed due to the presence of FICON logical switch. Please delete the FICON logical switch using the command \"lscfg --delete [-FID]\" and retry."
BNA_GEN6_APP_SERVER_RESTRICTION="Non-disruptive firmware downgrade is not supported due to registered Application Server entries, see \"appserver --show -domain <local domain ID>\". Either disable registered devices or issue \"firmwaredownload\" with single mode option enabled."
BNA_IMPORTED_TEMPLATE_NOTSUPPORTED="One or more imported crypto template(s) consists \"X509v3, Protocol or Log\" group's attributes that are not supported in pre-8.1.0 versions. Please delete the same using \"secCryptoCfg --delete\" to downgrade."
BNA_UNSUPPORTED_SNMP_FIPS_PASS_LEN="Upgrade is not allowed since one or more snmpv3 users have auth/priv password length lesser than 8 in FIPS mode"
BNA_UNSUPPORTED_SNMP_PASS_LEN="WARNING: one or more snmpv3 users have auth/priv password length lesser than 8"
BNA_UNSUPPORTED_SNMP_FIPS_AUTH_MD5="Upgrade is not allowed since one or more snmpv3 users have unsupported auth protocol MD5 configured in FIPS mode"
BNA_SNMP_USER_PASSWD_ENCRYPTION_WARN="WARNING: SNMP functionality may be affected if snmpv3 users have authentication and privacy password length lesser than 8. Please use snmpconfig --set snmpv3 to update the authentication and privacy password and it must be between 8 and 32 characters length."
BNA_REMOTE_FOSEXEC_CONFIGURED="Downgrade is not allowed because the Remote Fosexec feature is configured on the switch. Please use the \"configure\" command to disable Remote Fosexec mode on"
BNA_SNMP_GROUPNAME_RO="Downgrade is not allowed since SNMP V1/V3 is set to RO group. Please default the group name configuration before downgrade."
ANAKIN_BLADE_IS_PRESENT="FC32-64 blade is not supported by the targeted firmware.Please remove the blade before downgrade."
BNA_RASLOG_MODE_PRESENT="Custom Raslog Mode is not supported in pre-8.2.0. MAPS generates default RASLOGs-1001-4 for all the monitoring systems in default raslog mode"
BNA_AUL_MISS_BLK_DWLD="Firmware downgrade is not permitted. Please install Analytics Upgrade License to allow downgrade."
BNA_ENCRYPTION_ON_WEDGE64="Downgrade is not allowed because one or more ports have encryption configured. Please disable encryption configuration on all such ports before downgrade."
BNA_VTAP_ENABLED="Downgrade is not allowed as vTap flow is activated"
BNA_ANALYZER_VTAP_ENABLED="Downgrade is not allowed as Analyzer and vTap flow are active"
BNA_ZONE_TI_MAXZONENAME="One or more TI zone name length is 64 characters. TI zone name with 64 characters may not work as expected in pre-FOS 8.2.0 releases. Execute \"zone --delete\" command to remove the TI zone names with 64 characters."
BNA_ISL_RRDY_BS="Downgrade is not allowed because ISL R_RDY mode is enabled on a port in the Base Switch. Please disable using \"portcfgislmode\" before downgrading."
BNA_FIPSSIMULATE_NOTSUPPORTED="FIPS Simulate is not supported in the target version. Please disable the same using \"fipscfg --disable simulate\" to upgrade."
BNA_FIPSINSIDE_NOTSUPPORTED="FIPS Inside mode is not supported in the target version and the configuration will be void on downgrade. Please disable the same using \"fipscfg --disable fipsinside\" to downgrade.\nUpon successful downgrade, FIPS mode can be configured, if required."
BNA_FCOE_CONFIG_PRESENT="FCOE configurations are present in database. Please remove them using \"fcoe --default\" before downgrading"
BNA_FCOE_CONFIG_PRESENT_ON_TYR="FCOE configurations are not supported for this platform in targeted version. Please remove them using \"fcoe --default\" before upgrading."
BNA_ETHERNET_CONFIG_PRESENT_ON_TYR="Ethernet configurations are not supported for this platform in targeted version. Please convert them to FC using \"portCfgFlexPort --proto fc <[Slot/]Port>\" before upgrading."
BNA_LACP_GLOBAL_CONFIG_PRESENT="Global LACP configurations are present in database. Set it to default using \"lacp --config -sysprio 32768\" before downgrading"
BNA_LLDP_CONFIG_PRESENT="LLDP configurations are present in database. Please remove them using \"lldp --default\" before downgrading"
BNA_LACP_LAG_NAME_VLAN_PRESENT="LAG present with name staring with vlan. Please remove them using \"portcfg lag <name> --delete\" before upgrading"
BNA_GEN5_GEN6_PS_MISMATCH_WARN_MSG="Warning: Gen5 Power Supply is in use. Please replace it with Gen6 Power Supply for high availability operation"
UNSUPPORTED_PASSWORDLESS_LOGIN_MSG="Passwordless login for root account is not supported in the target version.Please disable the same using \"sshutil delpubkeys\" before upgrading\n"
BNA_UNSUPPORTED_PASSWORDLESS_LOGIN_MSG="Passwordless login for root account is not supported in the target version.Please disable the same using \"sshutil delpubkeys\" before upgrading\n"
BNA_MAX_IPFILTER_POLICY="More than four custom ipfilter policies are defined. Please limit the custom ipfilter polcies to four by deleting ipfilter policies using \"ipfilter --delete\""
BNA_IPFILTER_POLICY_NAME="One or more custom ipfilter policy(ies) are named \"default_ipv4_2\" or \"default_ipv6_2\". Please rename the policy(ies) by cloning them with a different name using \"ipfilter --clone\" and then deleting the \"default_ipv4_2\"/\"default_ipv6_2\" using \"ipfilter --delete\""
BNA_FMC_NOTSUPPORTED="Downgrade is not allowed because Ethernet Rate Limiting feature is enabled on Management Ports. Please disable this feature by using \"configure\" command before downgrading."
BNA_TOM_CHEW_UNSUPPORTED_DOWNGRADE="Firmware Downgrade to version 8.2.0 or below is not permitted on this platform."
BNA_DEVICE_QUARANTINED_ON_AG="Error: Firmaware downgrade not allowed due to devices/F-ports are quarantined by SDDQ feature in Access Gateway mode. Please recover Devices/F-ports from quarantine state and proceed with downgrade"
BNA_ENCRYPTION_TRUNKING_ON_SKYWALKER="Downgrade is not allowed because both Trunking and Encryption are configured together on one or more ports on a FC32-48 port blade. Please check portCfgShow and disable either Trunking or Encryption on affected ports before downgrade."
BNA_MAPS_RULE_WITH_INVALID_THRESHOLD_LEN="Downgrade is not allowed because one of more user defined MAPS rules have threshold length greater than 16 characters"
BNA_AMP30_COL_UPG_WARN="WARNING:AMPOS2.2 MAPS and Collection configurations are NOT compatible to AMPOS3.0. Upgrading to AMPOS3.0 will clear the custom configurations."
BNA_AMP30_CFG_ERR_MSG="Downgrade to AMPOS2.2 or lower version is NOT compatible to binded management server. Use the CLI mgmtapp --unbind to clear the existing configurations before downgrade."
BNA_AMP30_MD_RULE_ERR_MSG="Downgrade is not allowed because MAPS user defined configuration have incompatible rule/monitor name(s).Please refer the admin guide to remove the incompatible user defined rule(s) using \"mapsconfig --purge\" or \"mapsrule --delete <rule name>\" commands"
FDW_SNMPV1_WARNING="WARNING: SNMPv1 has default community string. Please disable SNMPv1 or reconfigure."
FDW_82_CHEWBACCA_TOM2_WARN="\nWARNING: Once firmware is upgraded to the target version, firmware downgrade to versions lower than FOS 8.2.1 is not allowed."
BNA_CHANGE_DEFAULT_PWD="Password(s) for admin/user are at default. Kindly change the password to non-default value before proceeding."
BNA_HALF_DUPLEX_CONFIG_PRESENT="firmwareDownload is not allowed because half duplex is configured.  Use ethif --set to clear half duplex configuration before upgrade."
BNA_IPSEC_DISABLE_WARN="IPSec feature is enabled. Please disable it by using \"ipsecConfig --disable\" CLI command, as it is deprecated in target release."
BNA_IPSEC_DISABLE_WARN_STANDBY="IPSec feature is enabled. Firmware upgrade will disable IPsec as it is deprecated in target release."
BNA_LDAPS_CONFIGURED_WARN_MSG="WARNING: LDAPS (default port 636) is not supported in the target firmware version. Please change the server configuration to StartTLS (default port 389) instead."
#######################################################
###################################################
###################################################
####                                           ####
####                                           ####
####       PRESINSTALL CHECK SECTION           ####
####    ------------------------------         ####
####                                           ####
###################################################
###################################################


#
# Check if Application Server-Header supported on this platform:
#   If supported, then disruptive downgrade is required - returns STS_ERR
#   If not supported, then non-disruptive downgrade is allowed - return STS_OK
#
check_app_server_disruptive_downgrade_required() {


	# If on standby CP then before you attempt to run appserver (which may not exists) to do this check
	# first check if the Actve CP has appserver
	if [ ! $ACTIVECP ] ; then
		appserverDoesNotExist=$(correcthost ls -al /fabos/cliexec/appserver  2> ${NULL} | grep -c "No such file or directory")
		if [ $appserverDoesNotExist ]; then
			return $STS_OK;
		fi
	fi

       correcthost_all_vfs /fabos/cliexec/appserver --show -domain local | /bin/grep "Entity ID" > $APPSERVER_STATUS_FILE

       app_server_check=`cat $APPSERVER_STATUS_FILE | /bin/grep -c "Entity ID"`

	if [ "$app_server_check" -ne "0" ]; then
		is_fwdl_arg "s"
		if [ $? -ne 0 ]; then
               	rm $APPSERVER_STATUS_FILE >/dev/null 2>&1
			return $STS_ERR
		fi
	fi

	rm $APPSERVER_STATUS_FILE >/dev/null 2>&1
	return $STS_OK
}

#
# 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

}

# extn_check_field()
#
# Check field parameter for invalid chars
extn_check_field()
{
	field=$@

	if [[ $field == *[';']* ]]; then
		return 1
	fi
}

# extn_check_binary_field()
#
# Check binary field parameter for invalid chars
extn_check_binary_field()
{
	field=$1
	out=""

	# get length of the string
	str_len=${#field}

	# sanity check for binary strings
	mod=$((str_len%2))
	if [ $mod -ne 0 ]; then
		return 0
	fi

	for ((i=0; i<$str_len; i+=2)); do
		out=$out`echo -e "\\x${field:$i:2}" | cat`
	done

	extn_check_field $out
	if [ $? -ne 0 ]; then
		return 1
	fi
}

# extn_check_psk_field()
#
# check portshow output for psk with semi-colons
extn_check_psk_field()
{
	obj_name=$1
	TMP_FILE=/tmp/extnipsec.txt

	echo "" > $TMP_FILE
	str_name=""
	for ((j=0; j<${#obj_name}; j+=2)); do
		str_name=$str_name`echo -e "\\x${obj_name:$j:2}" | cat`
	done

	if [ $CUR_MAJOR -gt 8 ]; then
		set_p=1
	elif [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -ge 1 ]; then
		set_p=1
	else
		set_p=0
	fi

	if [ $set_p -eq 1 ]; then
		pstring="$str_name -d -p"
		correcthost_all_vfs /fabos/link_bin/portshow ipsec-policy ${pstring} >> $TMP_FILE
	else
		pstring="$str_name -d"
		correcthost_all_vfs /fabos/link_bin/portshow ipsec-policy ${pstring} >> $TMP_FILE
	fi

	data=`cat $TMP_FILE | grep Preshared-Key`

	pos=16
	limit=${#data}

	while [ "${data:$pos:1}" == " " ]; do
		if [ $pos -eq $limit ]; then
			break
		fi
		pos=$((pos+1))
	done

	extn_check_field ${data:$pos}
	if [ $? -ne 0 ]; then
		return 1
	fi
}

extn_print_obj_string()
{
	str_in=$1
	obj_type=$2
	field_type=$3
	field_name=$4
	out_str=""
	pos=0

	if [ "${str_in:0:7}" != "extnCfg" ]; then 
		return 1
	fi

	type_str=""
	if [ "$obj_type" == "SLA" ]; then
		type_str=$obj_type
		cmd_str="'portcfg sla <name>'"
	elif [ "$obj_type" == "SBTCL" ]; then
		type_str="TCL"
		cmd_str="'portcfg tcl <name>'"
	elif [ "$obj_type" == "SBLAG" ]; then
		echo "LAG TYPE FOUND!"
		type_str="LAG"
		cmd_str="'portcfg lag <name>'"
	elif [ "$obj_type" == "IPSECPOLICY" ]; then
		type_str="IPSec Policy"
		cmd_str="'portcfg ipsec-policy <name>'"
	elif [ "$obj_type" == "FILTERSET" ]; then
		type_str="Filter Set"
		cmd_str="'portcfg filter <name>'"
	elif [ "$obj_type" == "APPINFO" ]; then
		type_str="App-Type"
		cmd_str="'portcfg app-type <name>'"
	elif [ "$obj_type" == "SBTUNNEL" ]; then
		type_str="Tunnel"
		cmd_str="'portcfg fciptunnel <VE>'"
	fi

	# Check for name based objects and print an error
	if [[ "$obj_type" == "SLA" || "$obj_type" == "SBTCL" ||
			"$obj_type" == "IPSECPOLICY" || "$obj_type" == "FILTERSET" ||
			"$obj_type" == "APPINFO" ]]; then

		IFS=,
		for i in $str_in; do
			if [[ "${i:0:4}" == "name" || "${i:0:4}" == "Name" ]]; then

				if [ $field_type == "string" ]; then
					pstring=${i:5}
				elif [ $field_type == "binary" ]; then
					tmp=${i:5}
					pstring=""
					for ((j=0; j<${#tmp}; j+=2)); do
						pstring=$pstring`echo -e "\\x${tmp:$j:2}" | cat`
					done
				else
					echo "Error parsing string (${str_in:0:32}...)"
				fi

				# SEND ERROR OUTPUT STRING
				if [[ $pstring == *[';']* ]]; then
					out_str="$type_str $pstring has semi-colon(s) in its name. Please use $cmd_str to delete and recreate without any semi-colons."
				else
					out_str="$type_str $pstring has semi-colon(s) in its $field_name field. Please remove them using $cmd_str"
				fi
				echo $out_str >> $FCIP_STATUS_FILE
			fi
		done
		unset IFS

		# We do not need to continue from here
		return 0
	fi

	# ignore 'extnCfg.' and move on
	pos=8

	# get slot information
	regex_match=`echo "${str_in:$pos:2}" | sed -n '/^S[0-9]/p'`
	if [ "$regex_match" != "" ]; then
		slot_based=1
		pos=$((pos+1))
		slot=${str_in:$pos:1}

		# if the next char is a number we must append it to the slot
		pos=$((pos+1))
		if [ "${str_in:$pos:1}" != "." ]; then
			slot="$slot${str_in:$pos:1}"
			pos=$((pos+1))
		fi
		pos=$((pos+1))
	else
		slot=0
	fi

	if [ "$obj_type" == "SBTUNNEL" ]; then
		regex_match=`echo "${str_in:$pos:4}" | sed -n '/^VE[0-9][0-9]/p'`
		if [ "$regex_match" != "" ]; then
			pos=$((pos+2))
			ve_num=${str_in:$pos:2}
		fi

		# SEND ERROR OUTPUT STRING
		if [ $slot -ne 0 ]; then
			out_str="$type_str $slot/$ve_num has semi-colon(s) in its $field_name field. Please remove them all with $cmd_str."
		else
			out_str="$type_str $ve_num has semi-colon(s) in its $field_name field. Please remove them all with $cmd_str."
		fi
		echo $out_str >> $FCIP_STATUS_FILE
		return 0
	fi
}

extn_obj_char_check()
{
	input_str=$1
	obj_type=$2
	rc=0
	field_name=""
	obj_name=""
	check_psk=0
	psk_string=""
	LAG_NAME=""

	IFS=,
	for i in $input_str; do
		unset IFS

		# check lag name separately since its the very first field
		if [ "$obj_type" == "SBLAG" ]; then
			if [ "${i:18:4}" == "name" ]; then 
				field_name="name"
				extn_check_field ${i:23}
				if [ $? -ne 0 ]; then
					LAG_NAME=${i:23}
					rc=3
					break
				fi
			fi
			# need to handle varying prefix string lengths (ID values >= 10)
			if [ "${i:19:4}" == "name" ]; then 
				field_name="name"
				extn_check_field ${i:24}
				if [ $? -ne 0 ]; then
					LAG_NAME=${i:24}
					rc=3
					break
				fi
			fi
		fi

		# Check NAME
		if [ "${i:0:4}" == "name" ]; then 
			field_name="name"
			extn_check_field ${i:5}
			if [ $? -ne 0 ]; then
				rc=1
				break
			fi
			extn_check_binary_field ${i:5}
			if [ $? -ne 0 ]; then
				rc=2
				break
			fi
		fi
		# Check NAME
		if [ "${i:0:4}" == "Name" ]; then 
			field_name="name"
			tmp_str=${i:5}
			extn_check_field ${i:5}
			if [ $? -ne 0 ]; then
				rc=1
				break
			fi
			extn_check_binary_field ${i:5}
			if [ $? -ne 0 ]; then
				rc=2
				break
			fi
			# handle preshared key case for ipsec-policy
			if [ "$obj_type" == "IPSECPOLICY" ]; then
				field_name="preshared-key"
				extn_check_psk_field "$tmp_str"
				if [ $? -ne 0 ]; then
					rc=2
					break
				fi
			fi
		fi
		# Check DESCRIPTION
		if [ "${i:0:11}" == "description" ]; then 
			field_name="description"
			extn_check_field ${i:12}
			if [ $? -ne 0 ]; then
				rc=1
				break
			fi
			extn_check_binary_field ${i:12}
			if [ $? -ne 0 ]; then
				rc=2
				break
			fi
		fi
		IFS=,
	done
	unset IFS

	if [ $rc -eq 1 ]; then
		extn_print_obj_string "$input_str" "$obj_type" "string" "$field_name"
	elif [ $rc -eq 2 ]; then
		extn_print_obj_string "$input_str" "$obj_type" "binary" "$field_name"
	elif [ $rc -eq 3 ]; then
		out_str="LAG $LAG_NAME has semi-colon(s) in its name. Please use 'portcfg lag <name>'  to delete and recreate without any semi-colons."
		echo $out_str >> $FCIP_STATUS_FILE
	fi

	return $rc
}

#
# 7840/SX6
# Check HCL readiness of extension tunnels
# Does not actually return a failure. Will just print any messages and treat
# them as warnings. Then will use the normal FWDL prompt to confirm from the
# user if they want to proceed.
#
check_extn_hcl()
{
	case ${SWBD##SWBD} in
		'148' | '165' | '166')
		allow_disruptive_single_mode_fwdl
		if [ $? -ne $STS_OK ]; then
			# Only perform the HCL checks if doing a non-disruptive download
			HCL_TUNNEL_CHECK=`correcthost_to_curr_vfid /fabos/link_bin/portshow fciptunnel all --hcl-status --preinst`
			echo -e "$HCL_TUNNEL_CHECK"
			echo -e "$HCL_TUNNEL_CHECK" >> $BNA_WARN_STATUS_FILE
			echo ""
		fi
			;;

		*)
			;;
	esac

	return $STS_OK
}

#
# check_extn_certs
#
# Check if extn related certificates are present in the switch.
# if present, we need to block downgrade to v8.0 and/or below.
# This check can be removed after 8.3
#
check_extn_certs ()
{
	extn_cert_found=0
	ret=$STS_OK

	/fabos/cliexec/seccertmgmt show -csr extn 2>&1 | grep -e "No  *CSR  *found." -e "This is not supported in non-extension platforms" -e "command not found" > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		ret=$STS_ERR
	fi
	/fabos/cliexec/seccertmgmt show -cert extn 2>&1 | grep -e "No  *CERT  *found." -e "This is not supported in non-extension platforms" -e "command not found" > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		ret=$STS_ERR
	fi
	/fabos/cliexec/seccertmgmt show -ca extn 2>&1 | grep -e "No  *CA  *found." -e "This is not supported in non-extension platforms" -e "command not found" > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		ret=$STS_ERR
	fi
	return $ret
}

check_extn_certs_name()
{
	ROOT_DIR=/etc/fabos
	EXTN_DIR=$ROOT_DIR/certs/extn

	case ${SWBD##SWBD} in
	'148' | '165' | '166' | '178')

	if [ ! -d "$EXTN_DIR" ]; then
		return $STS_OK
	fi	

	for file in $EXTN_DIR/*.csr $EXTN_DIR/*.pvt_key $EXTN_DIR/*.pem \
		$EXTN_DIR/*.hash $EXTN_DIR/*.crt $EXTN_DIR/*.cer $EXTN_DIR/*.psk; do		
			[ -f "$file" ] || continue
			filename=${file##*/}
			echo "${filename%.*}" | grep -v "[^a-zA-Z0-9~@%_+:.-]" > /dev/null 2>&1
			if [ ! $? -eq 0 ]; then
				return $STS_ERR	
			fi
		done

	esac

	return $STS_OK
}			

check_extn_chars()
{
	CHAR_TMP_FILE=/tmp/extnchars.txt

	case ${SWBD##SWBD} in
	'148' | '165' | '166')

	correcthost_all_vfs /fabos/link_bin/configshow -pat extnCfg > $CHAR_TMP_FILE
	ALL_ENTRIES=`cat $CHAR_TMP_FILE`

	# Loop on respective entry type and call handler
	# to check for invalid chars and to throw an error
	# if necessary

	# Check Tunnels
	echo "$ALL_ENTRIES" | grep SBTUNNEL | while read line; do
		extn_obj_char_check "$line" "SBTUNNEL"
	done
	# Check SLA
	echo "$ALL_ENTRIES" | grep SLA | while read line; do
		extn_obj_char_check "$line" "SLA"
	done
	# Check LAG
	echo "$ALL_ENTRIES" | grep SBLAG | while read line; do
		extn_obj_char_check "$line" "SBLAG"
	done
	# Check IpSec Policies
	echo "$ALL_ENTRIES" | grep IPSECPOLICY | while read line; do
		extn_obj_char_check "$line" "IPSECPOLICY"
	done
	# Check TCLs
	echo "$ALL_ENTRIES" | grep SBTCL | while read line; do
		extn_obj_char_check "$line" "SBTCL"
	done
	# Check filterset 
	echo "$ALL_ENTRIES" | grep FILTERSET | while read line; do
		extn_obj_char_check "$line" "FILTERSET"
	done
	# Check app-types
	echo "$ALL_ENTRIES" | grep APPINFO | while read line; do
		extn_obj_char_check "$line" "APPINFO"
	done

	esac
}

#
# 7840/SX6
# Check TCL limit to see if per-DP limit is exceeded. Fixed in FOS-802403, so we
# need to prevent upgrade if per-DP limit is currently exceeded.
#
check_extn_tcl_limit()
{
	case ${SWBD##SWBD} in
	'148' | '165' | '166')
		# Only perform TCL check when upgrading to v8.2.1 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 1 ]; then
			# For some reason, the configs can show up in both the default LS and
			# the chassis configDB. So first we need to sort them and get all unique
			# entries, then we can extract the info we need to count the totals
			PER_DP_TCLS=`correcthost_to_curr_vfid /fabos/link_bin/configshow -all | grep extnCfg.SBTCL | grep AdminStatus=1 | sort | uniq | sed -e 's/.*Dp=\([0-9]*\),.*/\1/' | sort -n | uniq -c | awk '{print $1}' | sort -n | tail -n 1`
			ALL_DP_TCLS=`correcthost_to_curr_vfid /fabos/link_bin/configshow -all | grep extnCfg.SBTCL | grep AdminStatus=1 | sort | uniq | grep Action=1 | grep Dp=4294967295 | wc -l`
			#echo "PER_DP:$PER_DP_TCLS"
			#echo "ALL_DP:$ALL_DP_TCLS"
			#echo "TOTAL:$(( PER_DP_TCLS + ALL_DP_TCLS ))"
			if [ $(( PER_DP_TCLS + ALL_DP_TCLS )) -gt 128 ]; then
				echo "There are more than 128 TCLs configured and enabled on at least one DP. Unable to upgrade. Please disable or remove TCLs to be under the per-DP limit of 128 enabled TCLs using the 'portcfg tcl <name> modify --admin-status disable' or the 'portcfg tcl <name> delete' command." >> $FCIP_STATUS_FILE
			fi
		fi
		;;

	*)
		;;

	esac
}

#
# 7800/FX8-24/7840/SX6
# Check is any FCIP restrictions are exceeded.
#
check_extn_features()
{
    ret=$STS_OK

	case ${SWBD##SWBD} in
	'62' | '77' | '83' | '148' | '165' | '166' | '178')

	correcthost_all_vfs /fabos/link_bin/portShow fciptunnel all --validate ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH} > $FCIP_STATUS_FILE
	correcthost_all_vfs /fabos/link_bin/portShow ipif all --validate ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH} >> $FCIP_STATUS_FILE

	check_extn_chars

	check_extn_tcl_limit

	err_output=`wc -l $FCIP_STATUS_FILE | awk '{ print $1 }'`

	if [ "$err_output" -ne "0" ]; then

		ret=$STS_ERR
		cat $FCIP_STATUS_FILE >> $STATUS_FILE
		cat $FCIP_STATUS_FILE >> $BNA_STATUS_FILE
	fi
		;;
	*)
		ret=$STS_OK
		;;
	esac

	rm $FCIP_STATUS_FILE >/dev/null 2>&1
    return $ret
}

# FX8-24, 7840, SX6
# Prep systems for FWDL to specified version
#
prep_extn_features()
{
	if [ ! -f $CHECK_FEATURES_FILE ]; then
		# no check features file
		return $STS_OK
	fi

	extn_fwdl_prep_supported=`grep -c "EXTN_FWDL_PREP_SUPPORTED" $CHECK_FEATURES_FILE`
	if [ "$extn_fwdl_prep_supported" = "0" ]; then
		# fwdl_prep command not supported
		return $STS_OK
	fi

	# v8.1.0+ prep systems for FWDL
	case ${SWBD##SWBD} in
	'62' | '77' | '83' | '148' | '165' | '166' | '178')
		if [ $PEER_MAJOR -gt 8 ] || [ $PEER_MAJOR -ge 8 -a $PEER_MINOR -ge 1 ]; then
			correcthost_to_curr_vfid /fabos/link_sbin/extncfg --fwdl-prep --version ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH} --preinst
		fi
		;;

	*)
		;;
	esac

	return $STS_OK
}

# FX8-24, 7840, SX6
# [Abort] Prep systems for FWDL to specified version
#
prep_extn_features_abort()
{
	if [ ! -f $CHECK_FEATURES_FILE ]; then
		# no check features file
		return $STS_OK
	fi

	extn_fwdl_prep_supported=`grep -c "EXTN_FWDL_PREP_SUPPORTED" $CHECK_FEATURES_FILE`
	if [ "$extn_fwdl_prep_supported" = "0" ]; then
		# fwdl_prep command not supported
		return $STS_OK
	fi

	# v8.2.0+ ABORT prep systems operations for FWDL
        if [ $CUR_MAJOR -gt 8 ] || [ $CUR_MAJOR -ge 8 -a $CUR_MINOR -ge 2 ]; then

		case ${SWBD##SWBD} in
		'62' | '77' | '83' | '148' | '165' | '166' | '178')

			correcthost_to_curr_vfid /fabos/link_sbin/extncfg --fwdl-prep --version ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH} --preinst --abort
			;;

		*)
			;;
		esac
	fi

	return $STS_OK
}

check_C2_core_blades() {
	result=`/fabos/cliexec/slotshow -m | grep -E "CR4S-8|CORE8" | wc -l`
    if [ $result -ge 1 ]; then
                return $STS_ERR
    else
       return $STS_OK
    fi
}

#
# ethsw_enabled
#
# Check whether ETHSW is enabled
# both Active and Standby have this information
#
check_ethsw_enabled() {
        /fabos/bin/fosconfig --show | grep "Ethernet Switch Service" | grep enabled > /dev/null 2>&1

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

}

# ethport_configured
#
# Check whether ETH port is present
# both Active and Standby have this information
#
check_ethport_configured() {
	result=`/fabos/bin/switchshow | grep "ETH" | wc -l`
    if [ $result -ne 0 ]; then
       return $STS_ERR
    else
       return $STS_OK
    fi

}

convert_hex2ascii()
{
	str=`echo $1 | tr -d \\x`
	pos=1
	len=$(( ${#str} + 1 ))

	while [ $pos -lt $len ]
	do
    	    hex='\x'`echo $str | cut -c $pos-$(( pos + 1 ))`
	        strhex=$strhex$hex
	        pos=$(( pos + 2 ))
	done
	echo -e $strhex
}

#
# in 8.2.0 & higher the pre-shared key length for IPsec policies (in extension platforms) should be atleast
# 32 characters long. This is applicable only in FIPS mode.
# This check is to block the upgrade if the user has PSK less than 32B in older versions.
#
check_extn_fips_pvt_key_len()
{
	err_flag=0

    grep "FIPSMODE:Fips=on" /etc/fabos/esm_chassis.conf > /dev/null 2>&1
    # not in DP FIPS mode, hence no need to check further
    if [ "$?" != "0" ];then
        return $STS_OK
    fi
	
	# Check all the non-encrypted policies
    for i in `/fabos/cliexec/configshow | grep extnCfg.IPSECPOLICY | grep ,Key`; do
		ipsec_key=`echo $i | awk -F : '{print $2}' | awk -F , '{print $3}' | awk -F = '{print $2}'`
		key_sz=${#ipsec_key}

		ipsec_pol=`echo $i | awk -F : '{print $2}' | awk -F , '{print $2}' | awk -F = '{print $2}'`
		ascii_pol=$(convert_hex2ascii $ipsec_pol)
		if [ "$key_sz" -lt 66 ]; then
			echo "IPsec policy $ascii_pol (FID:$glb_vf_id) has key length less than 32 characters" 
			err_flag=1
		fi
	done

	# Check all the encrypted policies
	for i in `/fabos/cliexec/configshow | grep extnCfg.IPSECPOLICY | grep EncrKey`; do
		ipsec_key=`echo $i | awk -F : '{print $2}' | awk -F , '{print $3}' | awk -F = '{print $2}'`
		ascii_key=$(convert_hex2ascii $ipsec_key)

		ipsec_pol=`echo $i | awk -F : '{print $2}' | awk -F , '{print $2}' | awk -F = '{print $2}'`
		ascii_pol=$(convert_hex2ascii $ipsec_pol)

		ipsec_dec_key=`/fabos/cliexec/esmcmd tools decrypt $ascii_key  | grep "Clear string" |  awk -F : '{print $2}'`
		key_sz=${#ipsec_dec_key}
		key_sz=$((key_sz-1))

		if [ "$key_sz" -lt 32 ]; then
			echo "IPsec policy $ascii_pol (FID:$glb_vf_id) has key length less than 32 characters" 
			err_flag=1
		fi
	done

	#Clear the key
	ipsec_dec_key=""

	if [ $err_flag -eq 1 ];then
		return $STS_ERR
	fi
	return $STS_OK

}

check_extn_fips_pvt_key_len_in_context()
{
	if [ $VF_ENABLED -ne $STS_OK ]; then
		CHASSISCMD="cmd_chassis"
		if [ $ACTIVECP ] ; then
			for_all_contexts check_extn_fips_pvt_key_len
		else
			for_all_contexts_standby check_extn_fips_pvt_key_len
		fi
	else
		check_extn_fips_pvt_key_len
	fi

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

#
# check_hcl_switchstate
#
# Check the switchState if it is Faulty to block HCL
#
check_hcl_switchstate()
{
	hashow_cmd="/fabos/bin/hashow"

	case "$($hashow_cmd | ( read a; echo $a ))" in
		*"Not supported"*)
		;;
		*)
		return $STS_OK
		;;
	esac

	switch_state=`/fabos/bin/switchshow | sed -n -e 's/switchState://gp' | tr -d '\t'`
	switch_state=`echo $switch_state  | sed $'s/[ \t]//g'`

	if [ "$switch_state" == "Faulty" ]; then
		is_fwdl_arg "s"
		if [ $? -ne 0 ]; then
			return $STS_ERR
		fi
	fi

	return $STS_OK

}

#Block firmware upgrade to v8.2.0 if
#any Ex-Port is configured in IM5 mode.
check_ex_ports_IM5()
{
	if [ $TO_MAJOR -ge 8 -a $TO_MINOR -ge 2 -a $TO_PATCH -ge 0 ]; then
		$ECHO $TO_MAJOR $TO_MINOR $TO_PATCH
		check_vf_enabled
		if [ $? -ne $STS_OK ]; then
			# VF enabled
			CHASSISCMD="cmd_chassis"
			if [ $ACTIVECP ] ; then
			    for_all_contexts check_ex_ports_IM5_configured
			else
			    for_all_contexts_standby check_ex_ports_IM5_configured
			fi
		else
		       # VF disabled
		    check_ex_ports_IM5_configured
		fi
		if [ $? -ne $STS_OK ]; then return $STS_ERR ; fi
	fi
	return $STS_OK
}

check_ex_ports_IM5_configured()
{
	#prefix correcthot_to_curr_vfid prior to execute in vf/chassis/active context.
    if err=`correcthost_to_curr_vfid /fabos/cliexec/fcrdbgport_cfg_exports  --allport | grep "Brocade NOS"` ; then
        add_err_status "$NOS_EX_PORT_RESTRICTION"
        add_err_status "Port    Admin           State           Mode"
        add_err_status "$err"
     return $STS_ERR
    fi
    if [ $? -eq $STS_ERR ] ; then return $STS_ERR ; fi
        #The return above exits the subshell started by the pipe
        #return here if the subshell exited early.
    if [ $? -eq $STS_ERR ] ; then return $STS_ERR ; fi
    return $STS_OK
}

check_max_lsan_dev_count()
{
	lsan_dev_cnt=`/fabos/cliexec/fcrdbgportshow --lsancount |grep -ic "command is not supported"`
	if [ $lsan_dev_cnt -eq 1 ]; then
		return $STS_OK
	fi
	
	lsan_dev_cnt=`/fabos/cliexec/fcrdbgportshow --lsancount`
	lsan_cnt=`echo $lsan_dev_cnt | cut -d" " -f2`
	dev_cnt=`echo $lsan_dev_cnt | cut -d" " -f6`
	range_rc=`echo $lsan_dev_cnt | cut -d" " -f8`

	if [ $lsan_cnt -gt 5000 ]; then
		return $STS_ERR
	fi

	if [ $dev_cnt -gt 10000 ]; then
		return $STS_ERR
	fi

	if [ $range_rc -eq 1 ]; then
		return $STS_ERR
	fi
    
	return $STS_OK
}

# Check for maximum supported zoneDB size across all partitions for any platform
check_max_supported_zoneDB_size() {
	totalUserConfiguredSize=0
	cfgsize=0

	# Do not perform cfgsize check on AMP platform as it consumes the zoneDB
	# from remote source switch and does not create zoneDB on its own
	analyticsmode=`correcthost /fabos/link_bin/switchshow | grep "Analytics" -c`
	if [ $analyticsmode -eq 1 ]; then
		return $STS_OK
	fi

	if [ $VF_ENABLED -ne $STS_OK ]; then
		if [ $ACTIVECP ] ; then
			FID_LIST=${CONTEXTS}
		else
			/bin/ln -s /fabos/cliexec/lscfg_util /fabos/link_sbin/lscfg_test 2> /dev/null
			export PATH=/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/link_rbin:/fabos/factory:/fabos/xtool
			STANDBY_FIDS=`lscfg_test --all | grep -e "[0-9]" | grep -v "Total" | awk '{ print $2 }'`
			FID_LIST=$STANDBY_FIDS
		fi

		for FID in $FID_LIST ; do
			context_switch $FID
			cfgsize=`/fabos/cliexec/cfgsize | grep "committed -" | awk {'print $3'}`
			# totalUserConfiguredSize = sum of cfgSize CLI "committed" field for all Logical Switches
			# Note: totalUserConfiguredSize does NOT include any reserved buffer space overhead and only
			# contains actual user-committed zoneDB data.
			totalUserConfiguredSize=`expr $totalUserConfiguredSize + $cfgsize`
		done
	else
		cfgsize=`/fabos/cliexec/cfgsize | grep "committed -" | awk {'print $3'}`
		# totalUserConfiguredSize = sum of cfgSize CLI "committed" field for all Logical Switches
		# Note: totalUserConfiguredSize does NOT include any reserved buffer space overhead and only
		# contains actual user-committed zoneDB data.
		totalUserConfiguredSize=`expr $cfgsize`
	fi

	# Check if the "totalUserConfiguredSize" is within the "totalChassisUserAvailableSize" limit.
	# totalUserConfiguredSize = sum of user-configured zonedb across all Logical Switches (calculated above)
	# totalChassisSizeLimit = total available memory pool for ZONEd usage for the entire chassis in bytes
	# totalChassisReservedBufferSpace = NumLS * (adMbrHdr_size of each LS + 74 DefZoneNoAccess-padding) bytes
	# Note: The per-Ls reserved buffer space is reserved to allow creation of MaxNumLS which a chassis can
	# support with no zoneDB deficiency.
	# The reserved space includes DefZoneNoAccess-padding in order to allow a user to at least change
	# DefZone to NoAccess after they've created a new Logical Switch even in the case of no user-available
	# db space.  The NumLS value is the total number of logical switches a platform supports as opposed to
	# the actual number of Logical Switches currently configured on the switch.  This creates
	# an issue for platforms that aren't VF-capable (i.e. Chewbacca, Embedded Switches) as they will end up
	# reserving more space than they need to which could result in a case where a user could configure a zoneDB
	# larger than what is allowed in the firmwareupgrade script.  To avoid having to hardcode each non-VF platform
	# in the ZONEd size logic, engineering has elected to pool these non-VF platforms into the VF-capable pizzabox
	# category with the idea being that the risk is low to encounter this particular corner case in the field.
	# totalChassisUserAvailableSize = totalChassisSizeLimit - totalChassisReservedBufferSpace in bytes
	# **Final check - if (totalUserConfiguredSize > totalChassisUserAvailableSize) --> Flag An Error
	pizzabox=$(/fabos/link_bin/hashow | grep -c "Not supported on this platform") 2>/dev/null

	if [ $pizzabox -eq 1 ]; then
		# PizzaBox Max Num LS: 4
		# PizzaBox totalChassisSizeLimit = 1045274 bytes
		# PizzaBox totalChassisReservedBufferSpace = 4 * (adMbrHdr_size of each LS + 74 DefZoneNoAccess-padding) = 3274 bytes
		# PizzaBox totalChassisUserAvailableSize = 1045274 - 3274 = 1042000 bytes
		if [ $totalUserConfiguredSize -gt 1042000 ]; then
			add_err_status "Error: Upgrade to Fabric OS 8.1.0 is not allowed because the total chassis-wide zone configuration database size ($totalUserConfiguredSize bytes) exceeds the maximum supported size of 1042000 bytes across all VFs. Please reduce the size of the zone configuration database and retry firmware upgrade."
			return $STS_ERR
		fi
	else
		# GEN 6 Chassis Max Num LS: 16
		# GEN 6 Chassis totalChassisSizeLimit = 2092741 bytes
		# GEN 6 Chassis totalChassisReservedBufferSpace = 16 * (adMbrHdr_size of each LS + 74 DefZoneNoAccess-padding) = 16241 bytes
		# GEN 6 Chassis totalChassisUserAvailableSize = 2092741 - 16241 = 2076500 bytes
		case ${SWBD##SWBD} in
		 '165' | '166')
			if [ $totalUserConfiguredSize -gt 2076500 ]; then
				add_err_status "Error: Upgrade to Fabric OS 8.1.0 is not allowed because the total chassis-wide zone configuration database size ($totalUserConfiguredSize bytes) exceeds the maximum supported size of 2076500 bytes across all VFs. Please reduce the size of the zone configuration database and retry firmware upgrade."
				return $STS_ERR
			fi
			;;
			*)
			;;
		esac
		# GEN 5 Chassis Max Num LS: 8
		# GEN 5 Chassis totalChassisSizeLimit = 2092741 bytes
		# GEN 5 Chassis totalChassisReservedBufferSpace = 8 * (adMbrHdr_size of each LS + 74 DefZoneNoAccess-padding) = 8241 bytes
		# GEN 5 Chassis totalChassisUserAvailableSize = 2092741 - 8241 = 2084500 bytes
		if [ $totalUserConfiguredSize -gt 2084500 ]; then
			add_err_status "Error: Upgrade to Fabric OS 8.1.0 is not allowed because the total chassis-wide zone configuration database size ($totalUserConfiguredSize bytes) exceeds the maximum supported size of 2084500 bytes across all VFs. Please reduce the size of the zone configuration database and retry firmware upgrade."
			return $STS_ERR
		fi
	fi

	return $STS_OK
}

# Check for the Gen5 PS in Gen6 chassis and Warn the user to replace the same during
# upgrade to 8.2.0

check_for_powersupply_mismatch_in_gen6_chassis() {

	case ${SWBD##SWBD} in
		'165' | '166')

			warning=0

			expected_ps="23-0000161 23-0000162 23-0000163 23-0000164"

			for i in `correcthost /fabos/cliexec/psshow | grep -v "Power Supply" | grep -v "No system control" | cut -d ',' -f 3 | cut -d '-' -f 1-2`
			do
				#echo "from PSshow==>"$i

				for j in $expected_ps
				do
					#echo "Expected PS=======>"$j

					if [ "$i" == "$j" ]
					then
						warning=0
						break
					else
						warning=1
					fi
				done				
			done

			if [ $warning -eq 1 ]
			then
				echo "$GEN5_GEN6_PS_MISMATCH_WARN_MSG"
				add_warn_status "$BNA_GEN5_GEN6_PS_MISMATCH_WARN_MSG"
			fi

			;;

		*)
			;;
	esac

	return $STS_OK
}
#
# maps_enabled_check
#
# Check whether the switch is currently in auto csctl mode
#
maps_enabled_check() {
 # on active cp we need diffrent command than the stand by. dont know the reason why?
	ret=`CONFIGSHOW -chassis | grep maps.migrated:1 |wc -l`
	# need to truncate all the leading blank characters 
	last=`echo $ret | tr -d ' '`
	# 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}
	# 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 if there is decom action configured in any logical switch.
# If decom is present, the firmwaredownload should not be allowed.

check_for_maps_action_config()
{
	actions=''
	action_bitmask=$1
	maps_enabled_check
	if [ $? -le 0 ]; then
		return $STS_OK
	fi
	
	CONFIGSHOW_ADV > xxx

	actions=`cat xxx |grep '^maps\.actions:' 2> /tmp/.fwdl_mapsconfig_out.txt`
	ret=$?
	if [ $ret -eq 0 ]; then
		actions=`echo $actions| cut -f2 -d":"`
	else
		return $STS_OK
	fi
	let ret="$actions & $action_bitmask"
	if [ $ret -ne 0 ]; then
	    return $STS_ERR
	fi

	rm -f /tmp/.fwdl_mapsconfig_out.txt
	return $STS_OK
}

# check if user defined rules have decom action.
# If so, the firmwaredownload should not be allowed.


# check if user defined rules have decom action.
# If so, the firmwaredownload should not be allowed.

check_for_actions_present_in_maps_rules_cfg()
{
    actionStr=$1
    maps_enabled_check
    if [ $? -le 0 ]; then
	return $STS_OK
    fi
    CONFIGSHOW > /tmp/.fwdl_configshow_out1.txt
    # get the list of rule names.
    awk '/^maps\.rule\./' /tmp/.fwdl_configshow_out1.txt >/tmp/.fwdl_configshow2.txt

    if [ ! -f "/tmp/.fwdl_configshow2.txt" ]; then
	return $STS_OK
    fi
    if [ ! -s "/tmp/.fwdl_configshow2.txt" ]; then
	return $STS_OK
    fi
    rule_check_failed=0
    echo $rule_check_failed > /tmp/.fwdl_decom_rule_err.txt
    cat /tmp/.fwdl_configshow2.txt|
    while read line
    do
      action_list=`echo $line| cut -f2 -d" "`
      echo $action_list | grep -i $actionStr > /dev/null
      if [ $? -eq 1 ]; then
	continue
      fi
      rule_check_failed=1
      echo $rule_check_failed > /tmp/.fwdl_decom_rule_err.txt
    done

    check_return_val=`cat /tmp/.fwdl_decom_rule_err.txt`
    rm -f /tmp/.fwdl_*.txt
    if [ $check_return_val -eq 1 ]; then
	return $STS_ERR
    else
	return $STS_OK
    fi
}

warnTokenList=""

# check one token or MAPS feature in the configuration if it is present then 
# add that token in the tokenList
# Arguments to this function as follows - 
# token, FOS version, configuration Buffer
check_maps_one_810_feature_to_give_warning() {
	result=""
	listOfTokens=""
	ret=$STS_OK
	configBuffer=`CONFIGSHOW`
	token=$1
	version=$2
	warningDisplayed=0
	result=`echo $configBuffer | grep $token`

    if [ -n "$result" ]
    then
        if [ $token == "qt=" ]
        then
           token="Quiet time"
		fi
		if [ $token == "severity=" ]
        then
           token="Severity"
        fi
        if [ -n "$listOfTokens" ]
        then
           listOfTokens="$token, $listOfTokens"
        else
           listOfTokens="$token"
        fi
    fi
    if [ -n "$listOfTokens" ]
    then
        let "warningDisplayed=warningDisplayed+1"
        if [ $warningDisplayed -eq 1 ]
        then
			if [ ! -f "/tmp/.warningDisplayed_810" ]
			then
              warnStr="MAPS user defined rules for $token will not be monitored in pre-FOS $version. Please delete these rules from FID: $glb_vf_id"
			  touch /tmp/.warningDisplayed_810
			else
			  warnStr=" ,$glb_vf_id"
			fi
        fi
        if [ $warningDisplayed -ge 1 ]
           then
           echo -n $warnStr >> ${MAPS_WARN_FILE}
        fi
    fi
    return $ret
}

check_maps_ror_length_to_block() {

	CONFIGSHOW > /tmp/x1

	# The maximum rule name len in 8.0.1 is 40 and maps.rule. takes 10 chars.
	# So if length is 50 or more, block the firmware. 
	awk '{FS=":"} {print $1}' /tmp/x1 | grep "maps\.rule\." > /tmp/x2
	file="/tmp/x2"
	while read line
	do
		rule_name_key="$line"
		rule_name_key_len=${#rule_name_key}
		if [ -n "$rule_name_key_len" ]
		then
			if [ $rule_name_key_len -gt 50 ]
			then
				return $STS_ERR
			fi
		fi
	done < $file
	return $STS_OK
}

check_821_maps_re_imbalance_present()
{
	funcArgs="1048576"
	check_for_maps_action_config $funcArgs
	if [ $? -eq $STS_ERR ]
	then
	    warnStr="$MAPS_RE_BALANCE_CONFIG_ERR$glb_vf_id"
	   
	    echo $warnStr >> ${MAPS_WARN_FILE}
	fi
	return $STS_OK
}


check_821_maps_rule_length_check()
{
	ruleTh=`/fabos/cliexec/configshow -a | grep -i "maps.rule\." | cut  -d '/' -f2 | cut -d ')' -f1 | tr ">" " " | tr "<" " " | tr "=" " " | tr -s " " | cut -d " " -f2`
	for i in $ruleTh; do
		len=`echo $i | wc -c`
		if [ $len -gt 17 ]; then
			return $STS_ERR
		fi
	done
	return $STS_OK
}

# Function to handles features of MAPS
# This function handles all the features of MAPS and give warning if they present
#
#
check_821_warning_maps_features()
{
    version="8.2.1"
    bnaErr=0
    warningDisplayed=0
    tokenList="DEV_LOGIN_DIST ALL_25Km_32GELWL_SFP"

    rm -f ${MAPS_WARN_FILE}

    if [ $VF_ENABLED -ne $STS_OK ]; then
        if [ $ACTIVECP ] ; then
            for_all_contexts check_all_features_of_maps_for_warning "$tokenList" "$version"
        else
            for_all_contexts_standby check_all_features_of_maps_for_warning  "$tokenList" "$version"
        fi
    else
        check_all_features_of_maps_for_warning "$tokenList" "$version"
    fi

    if [ -f "${MAPS_WARN_FILE}" ]
    then
        cat ${MAPS_WARN_FILE}
        rm ${MAPS_WARN_FILE}
        bnaErr=1
    fi


    if [ $bnaErr -ne 0 ]
    then
        add_warn_status "$MAPS_DEV_LOGIN_DIST_ERR"
        add_warn_status "$BNA_821_WARN"
    fi

    rm -f ${MAPS_WARN_FILE}
    bnaErr=0
    
    check_maps_821_features_ip_extn_flow_wrapper
    
    rm -f ${MAPS_WARN_FILE}
    bnaErr=0

    
    if [ $VF_ENABLED -ne $STS_OK ]; then
        if [ $ACTIVECP ] ; then
            for_all_contexts check_821_maps_re_imbalance_present 
        else
            for_all_contexts_standby check_821_maps_re_imbalance_present
        fi
    else
        check_821_maps_re_imbalance_present tokenList $version
    fi

    if [ -f "${MAPS_WARN_FILE}" ]
    then
        cat ${MAPS_WARN_FILE}
        rm ${MAPS_WARN_FILE}
        bnaErr=1
    fi

    if [ $bnaErr -ne 0 ]
    then
	add_warn_status "$BNA_MAPS_RE_BALANCE_CONFIG_ERR"
    fi
}

#
# This function check all 8.2.3 features for downgrade to 8.2 or 8.1
#
check_823_features()
{
		$ECHO check_823_features
# Warn user if LDAPS configuration exists
		check_ldaps_configured

		return $STS_OK
}

check_810_blocking_maps_features() 
{
    data="262144:BNA_MAPS_UNQUAR_CONFIG_ERR:MAPS_UNQUAR_CONFIG_ERR 524288:BNA_MAPS_UNINSTALL_VTAP_CONFIG_ERR:MAPS_UNINSTALL_VTAP_CONFIG_ERR"

    data1="UNQUAR:BNA_MAPS_UNQUAR_RULES_CONFIG_ERR:MAPS_UNQUAR_RULES_CONFIG_ERR UNINSTALL_VTAP:BNA_MAPS_UNINSTALL_VTAP_RULES_CONFIG_ERR:MAPS_UNINSTALL_VTAP_RULES_CONFIG_ERR"
	cliRuleLenErr="MAPS_81_RULES_CONFIG_ERR"
	bnaRuleLenErr="BNA_81_RULES_CONFIG_ERR"
	cliRORRuleErr="MAPS_81_ROR_RULES_CONFIG_ERR"
	bnaRORRuleErr="BNA_81_ROR_RULES_CONFIG_ERR"

    # check for 8.1 features
    for var in $data
    do
#      echo "var=$var"
      funcArgs=`echo $var | awk -F: ' { print $1 } ' `
      bnaErr=`echo $var | awk -F: ' { print $2 } ' `
      cliErr=`echo $var | awk -F: ' { print $3 } ' `
#      error=$(eval echo $`echo $error`);
#      echo " error = $error funcArgs=$funcArgs"
      TEST_FIDS_ADV check_for_maps_action_config $cliErr $bnaErr funcArgs="$funcArgs"
    done

    # check for 8.1 features
    for var in $data1
    do
      funcArgs=`echo $var | awk -F: ' { print $1 } ' `
      bnaErr=`echo $var | awk -F: ' { print $2 } ' `
      cliErr=`echo $var | awk -F: ' { print $3 } ' `
#      error=$(eval echo $`echo $error`);
#      echo " error = $error funcArgs=$funcArgs"

      TEST_FIDS_ADV check_for_actions_present_in_maps_rules_cfg $cliErr $bnaErr funcArgs="$funcArgs"
    done

    TEST_FIDS_ADV check_maps_ror_length_to_block $cliRuleLenErr $bnaRuleLenErr funcArgs=""
    TEST_FIDS_ADV check_maps_ror_feature_to_block $cliRORRuleErr $bnaRORRuleErr funcArgs=""
}

check_maps_ror_feature_to_block() {
    result=""
    listOfTokens=""
    ret=$STS_OK
    CONFIGSHOW > /tmp/xxx
    token=$1
	version=$2
	warningDisplayed=0

	awk '/^maps\.rule\./' /tmp/xxx | grep "ruleType=1" > /dev/null
	if [ $? -eq 0 ]
	then
			return $STS_ERR
	fi
    return $STS_OK
}

# The configBuffer is sent in pre 8.1.0 and in 
# release 8.1.0, we have to call check_maps_one_810_feature_to_give_warning
# to create the buffer and processes the tokens.
check_maps_one_feature_to_give_warning() {
	result=""
	ret=$STS_OK

	token=$1
	version=$2
	configBuffer=$3


	if [ -n "$configBuffer" ]
	then
	result=`echo $configBuffer | grep $token`
    #echo "result",$result
	if [ -n "$result" ]
	then
		if [ $token == "qt=" ]
		then
		token="Quiet time"
		fi
		if [ $token == "severity=" ]
		then
		token="Severity"
		fi

		if [ -n "$warnTokenList" ]
		then
		warnTokenList="$token, $warnTokenList"
		else
		warnTokenList="$token"
		fi
	#echo "warnTokenList",   $warnTokenList,$token
	fi
	else
	check_maps_one_810_feature_to_give_warning $token $version
	fi
    
    return $ret
}
# this function checks for each token and add error string to a file for each
# logical switch
# Arguments to this function as follows - tokenList, FOS version

check_all_features_of_maps_for_warning() {
    ret=$STS_OK

    #configuration for each logical switch
    CONFIGSHOW_ADV>xxx

    configBuffer=`awk '/^maps\.rule\./' xxx`
    
    if [ -z "$configBuffer" ]
    then
	return $ret
    fi

    tokenList=$1
    version=$2

    for token in $tokenList
    do 
        check_maps_one_feature_to_give_warning $token $version "$configBuffer"
    done

    # if token has been found then add the error string to a file and reset 
    # warnTokenList buffer

    if [ ! -z "$warnTokenList" ]
    then
	warnStr="WARNING:MAPS user defined rules for $warnTokenList will not be monitored in pre-$version release. Please delete these rules from FID: $glb_vf_id"
	echo $warnStr >> ${MAPS_WARN_FILE}
	warnTokenList=""
    fi    
    return $ret
}

check_maps_80_features_to_give_warning()
{
    version="8.0.1"
    bnaErr=0
    warningDisplayed=0
    tokenList="GE_CRC GE_LOS_OF_SIG DAYS_TO_EXPIRE EXPIRED_CERTS RD_STATUS_TIME_LT_8K RD_STATUS_TIME_8_64K RD_STATUS_TIME_64_512K RD_STATUS_TIME_GE_512K WR_STATUS_TIME_LT_8K WR_STATUS_TIME_8_64K WR_STATUS_TIME_64_512K WR_STATUS_TIME_GE_512K RD_1stDATA_TIME_LT_8K RD_1stDATA_TIME_8_64K RD_1stDATA_TIME_64_512K RD_1stDATA_TIME_GE_512K WR_1stXFER_RDY_LT_8K WR_1stXFER_RDY_8_64K WR_1stXFER_RDY_64_512K WR_1stXFER_RDY_GE_512K RD_PENDING_IO_LT_8K RD_PENDING_IO_8_64K RD_PENDING_IO_64_512K RD_PENDING_IO_GE_512K WR_PENDING_IO_LT_8K WR_PENDING_IO_8_64K WR_PENDING_IO_64_512K WR_PENDING_IO_GE_512K ALL_4_32GSWL_QSFP ALL_32GSWL_SFP ALL_32GLWL_SFP ALL_25Km_16GLWL_SFP"
    tokenList="$tokenList IP_UTIL IP_PKTLOSS IP_RTT IP_JITTER ALL_TUNNEL_IP_HIGH_QOS ALL_TUNNEL_IP_MED_QOS ALL_TUNNEL_IP_LOW_QOS ALL_CIRCUIT_IP_HIGH_QOS ALL_CIRCUIT_IP_MED_QOS ALL_CIRCUIT_IP_LOW_QOS IT_FLOW ALL_LOCAL_PIDS ALL_EXT_GE_PORTS FAN_AIRFLOW_MISMATCH"
	  rm -f ${MAPS_WARN_FILE}
   
    if [ $VF_ENABLED -ne $STS_OK ]; then
	if [ $ACTIVECP ] ; then
	    for_all_contexts check_all_features_of_maps_for_warning "$tokenList" $version
        else
	    for_all_contexts_standby check_all_features_of_maps_for_warning  "$tokenList" $version
        fi
    else
	check_all_features_of_maps_for_warning $tokenList $version
    fi


    if [ -f "${MAPS_WARN_FILE}" ]
    then
        cat ${MAPS_WARN_FILE}
        rm ${MAPS_WARN_FILE}
        bnaErr=1
    fi
    
    if [ $bnaErr -ne 0 ]
    then
        add_warn_status "$BNA_MAPS_80_WARN"
    fi
}

check_maps_821_features_ip_extn_flow() {
    ret1=0
    version="8.2.1"
    bnaErr=0
    #configuration for each logical switch
    CONFIGSHOW_ADV>xxx

    ruleBuffer=`cat xxx | grep "maps.rule" | grep "IP_EXTN_FLOW"`
    if [ -z "$ruleBuffer" ]
    then
          return $ret1
    else
        warnStr="WARNING: MAPS user defined rules for IP_EXTN_FLOW will be monitored as absolute number prior $version. Version $version and above IP_EXTN_FLOW rules are monitored as percentage. Please delete these rules and create them post firmware installation, from FID: $glb_vf_id"
	echo $warnStr >> ${MAPS_WARN_FILE}
    fi
}

# Handles the upgrade and downgrade both - warn user to delete the IP_EXTN_FLOW
check_maps_821_features_ip_extn_flow_wrapper()
{
    version="8.2.1"
    bnaErr=0

    if [ $VF_ENABLED -ne $STS_OK ]; then
        if [ $ACTIVECP ] ; then
            for_all_contexts check_maps_821_features_ip_extn_flow 
        else
            for_all_contexts_standby check_maps_821_features_ip_extn_flow  
        fi
    else
        check_all_features_of_maps_for_warning 
    fi

    if [ -f "${MAPS_WARN_FILE}" ]
    then
        cat ${MAPS_WARN_FILE}
        rm ${MAPS_WARN_FILE}
        bnaErr=1
    fi

    if [ $bnaErr -ne 0 ]
    then
        add_warn_status  "$BNA_MAPS_81_WARN"
    fi

}


check_maps_820_features_to_give_warning()
{
    version="8.2.0"
    bnaErr=0
    warningDisplayed=0
    tokenList="IP_EXTN_FLOW ALL_ETH_PORTS ALL_FCOE_40G_QSFP ALL_FCOE_10G_SFP ALL_FCOE_25G_SFP"
    tokenList="$tokenList RD_IOPS_LT_8K RD_IOPS_8_64K RD_IOPS_64_512K RD_IOPS_GE_512K WR_IOPS_LT_8K"
    tokenList="$tokenList WR_IOPS_8_64K WR_IOPS_64_512K WR_IOPS_GE_512K RD_RATE_LT_8K RD_RATE_8_64K RD_RATE_64_512K"
    tokenList="$tokenList RD_RATE_GE_512K WR_RATE_LT_8K WR_RATE_8_64K WR_RATE_64_512K WR_RATE_GE_512K ALL_FCOE_100G_SR4_QSFP sys_mon_all_fports"
	tokenList_amp="IP_EXTN_FLOW ALL_ETH_PORTS ALL_FCOE_40G_QSFP ALL_FCOE_10G_SFP ALL_FCOE_25G_SFP"
	tokenList_amp="$tokenList_amp ALL_FCOE_100G_SR4_QSFP"
    rm -f ${MAPS_WARN_FILE}

	# The ios MS are applicable for AMP platform.
	if [ ${SWBD##SWBD} == '171' ]; then
		tokenList=$tokenList_amp
	fi
    if [ $VF_ENABLED -ne $STS_OK ]; then
        if [ $ACTIVECP ] ; then
            for_all_contexts check_all_features_of_maps_for_warning "$tokenList" $version
        else
            for_all_contexts_standby check_all_features_of_maps_for_warning  "$tokenList" $version
        fi
    else
        check_all_features_of_maps_for_warning $tokenList $version
    fi

    if [ -f "${MAPS_WARN_FILE}" ]
    then
        cat ${MAPS_WARN_FILE}
        rm ${MAPS_WARN_FILE}
        bnaErr=1
    fi

    if [ $bnaErr -ne 0 ]
    then
        add_warn_status  "$MAPS_82_WARN"
    fi

    #raslog mode key does not fit in our existing infra structure so need to handle sepratly
    #and generates warning if the 'custom' raslog mode is enabled
    CONFIGSHOW_ADV -chassis>xxx
    configBuffer=`awk '/^maps\.raslogMode:1/' xxx`

    # buffer must not be NULL and should not be default
    if [ -z "$configBuffer" ]
    then
	return $ret
    fi

     add_warn_status "$BNA_RASLOG_MODE_PRESENT"
     echo "WARNING:"
     echo "$RASLOG_MODE_PRESENT"
}


check_ldaps_configured() {
	CUT=`/usr/bin/which cut`
	GREP=`/usr/bin/which grep`
# If LDAPS mode configured, warn that LDAP authentication will not work after downgrade
	ldap_tls_mode_list=`/fabos/cliexec/configshow -c | $GREP "ldap" | $GREP "tlsMode" | $CUT -d ":" -f 2`
	ldaps_port_list=`/fabos/cliexec/configshow -c | $GREP "ldap" | $GREP "port" | $CUT -d ":" -f 2`
	for j in $ldaps_port_list; do
		if [ $j -eq 636 ]; then
			for i in $ldap_tls_mode_list; do
				if [ $i -eq 1 ]; then
					echo -e $LDAPS_CONFIGURED_WARN_MSG
					add_warn_status "$BNA_LDAPS_CONFIGURED_WARN_MSG"
					exit 1;
				fi
			done
		fi
	done
}


#check if ICL connections are within the allowed limit
check_icl_port_configuration()
{
	#Check for ICL license
	icl_lic=`/fabos/bin/licenseshow |grep "Inter Chassis Link" | wc -l`

	if [ $icl_lic -eq 0 ]; then
		return $STS_OK
	fi

	if [ $VF_ENABLED -ne $STS_OK ]; then
		CHASSISCMD="cmd_chassis"
		for_all_contexts check_icl_limit
	else
		check_icl_limit
	fi

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

check_icl_limit()
{
	sw_idx=0
	mac_idx=0
	wwn_cnt=0
	icl_cnt=0
	naa=0

	#Unique MAC address computation will be done only for C3 blades
	check_c3=`/fabos/bin/slotshow | grep -E "96|97|98|99" | wc -l`
	if [ $check_c3 -eq 0 ]; then
		return $STS_OK
	fi

	#Get ICL slots
	icl_slots=`/fabos/bin/slotshow -m | grep "CORE" | awk {'print $1'}`

	for slt in $icl_slots
	do
		#Get Switch WWN list of E/EX-Ports
		wwn_list=`/fabos/bin/switchshow -slot $slt |grep -v 'E-Port|EX-Port' | awk {'print $10'} | grep ":" | uniq | sort`

		for wwn in $wwn_list
		do
			wwn_arr[$sw_idx]=$wwn
			sw_idx=`expr $sw_idx + 1`
		done
	done

	wwn_arr_uniq="`for wwn in ${wwn_arr[@]}; do echo ${wwn}; done | sort -u`"
	wwn_cnt=`echo $wwn_arr_uniq | wc -w`

	local_wwn=`/fabos/cliexec/licenseidshow | cut -b 1-20 | tr -d ':'`

	#Get Domain ID and MAC Address
	for sw_wwn in $wwn_arr_uniq
	do
		trunc_sw_wwn=`echo $sw_wwn | cut -b 1-20 | tr -d ':'`
		#
		# Fetch the MAC address only if the switch WWN is different from
		# local switch WWN
		#
		if [ "$trunc_sw_wwn" != "$local_wwn" ]; then
			naa=`echo $sw_wwn | cut -c-1`

			# Check whether $naa is numeric or character.
			# For segmented port it will 's' and mac_idx need not 
			# be incremented. 
			if [[ $naa = *[[:digit:]]* ]]; then
				#naa is 1 for edge switch and 5 for FCR switch
				if [ $naa -eq 1 ]; then
					mac[$mac_idx]=`echo $sw_wwn | cut -b 16-22 | tr -d ':'` 
				elif [ $naa -eq 5 ]; then
					mac[$mac_idx]=`echo $sw_wwn | cut -b 11-18 | tr -d ':'`
				fi
				mac_idx=`expr $mac_idx + 1`
			fi
		fi
	done

	mac_uniq="`for wwn in ${mac[@]}; do echo ${wwn}; done | sort -u`"

	#Get ICL count with each unique MAC Address
	icl_cnt=`echo $mac_uniq | wc -w`

	#Check for EICL license present
	eicl_lic=`/fabos/bin/licenseshow |grep "Enterprise ICL license" | wc -l`

	if [ $eicl_lic -eq 0 ] && [ $icl_cnt -gt 3 ]; then
		return $STS_ERR
	elif [ $eicl_lic -eq 1 ] && [ $icl_cnt -gt 9 ]; then
		return $STS_ERR
	else
		return $STS_OK
	fi
}

#
#
# This routine check if Manual gateway ipv6 is configured
#
check_manual_gwyipv6_configuration()
{

	manual_gwy=`CONFIGSHOW -chassis | grep "ipadm.max.gw.1" | cut -d ':' -f 2 | awk '$1'`
	for gwy_index in $manual_gwy 
                do
                if [ $gwy_index -eq 1 ] ; then
                        return $STS_ERR
                fi
                done
        return $STS_OK

}

#
#
# This routine check if type1miss|type2miss|type6miss" discard frame type is enabled
#
check_DiscFrameType()
{	
	local disc_frm_type=`correcthost_to_curr_vfid /fabos/sbin/framelog --status | grep -e "type1miss" -e "type2miss" -e "type6miss"`

	if [ "$disc_frm_type" ]; then
		return $STS_ERR
	fi

	return $STS_OK
}

#
# This Fuction is used to check if Alias Peer Zone are configured and thereby block 
# firmware downgrade from FOS v8.1.0 to FOS v8.0.x.
#
check_Alias_Peer_Zone_feature ()
{
   	aliasPeerZoneEna=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
    	aliasPeerZoneEna=`/fabos/cliexec/zone stateshow | grep "Alias Peer Zoning = Configured" | wc -l`
	if [ $aliasPeerZoneEna -eq 1 ]; then
	    # Alias Peer Zones Exist on this FID/switch, flag error
	    return $STS_ERR
	else
		return $STS_OK
	fi
}

#
# This Fuction is used to check if Enhanced Zone Object Naming are configured and thereby block 
# firmware downgrade from FOS v8.1.0 to FOS v8.0.x.
#
check_Enhanced_Zone_Object_Name_Feature () {
	enhancedZoneEna=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
    	enhancedZoneEna=`/fabos/cliexec/zone stateshow | grep "Enhanced Zone Object Naming = Configured" | wc -l`
	if [ $enhancedZoneEna -eq 1 ]; then
	    # Enhanced Zone Name Objects Exist on this FID/switch, flag error
	    return $STS_ERR
	else
		return $STS_OK
	fi
}


#
# Check if ficon switch is enabled
#
check_ficon_logical_switch_presence() {
        export PATH=/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/link_rbin:/fabos/factory:/fabos/xtool

        local retvar=`correcthost_to_curr_vfid /fabos/link_bin/switchshow | grep -c 'Ficon Switch: Yes'`
        if [ $retvar -ne 0 ]; then
            # ficon switch present, flag error
            return $STS_ERR
        else
            return $STS_OK
        fi

    return $STS_OK
}


#check if Port Mirror Connections exist
check_port_mirror_conns()
{
	$ECHO check_port_mirror_conns

        count=`/fabos/link_sbin/portmirror --show | grep -i "DEFINED" -c`
        count2=`/fabos/link_sbin/portmirror --show | grep -i "ENABLED" -c`
        if [ $count -eq 0 ] && [ $count2 -eq 0 ]; then
                return $STS_OK
        fi
        return $STS_ERR
}


check_port_mirror_conns_standby()
{
	$ECHO check_port_mirror_conns_standby

        count3=`correcthost_to_curr_vfid /fabos/cliexec/config get mirror.portmirrorcnt 5`

	if [ "$count3" != "" ]; then
		if [ $count3 -eq 0 ]; then
			return $STS_OK
		else
			return $STS_ERR
		fi
	else
		return $STS_OK
	fi
}


#check if password hash type of the system or any user is set to SHA2
check_801_pw_hash()
{
	if [ $TO_MAJOR -eq 8 ] && [ $TO_MINOR -eq 0 ] && [ $TO_PATCH -eq 0 ]; then
		type=2
		local pw_hash=`CONFIGSHOW -chassis | /bin/grep "passwdcfg.hash" | /usr/bin/cut -d ':' -f2`
		if [ ! -z "$pw_hash" ]; then
			if [ "$pw_hash" != "md5" ]; then
				return $STS_ERR
			fi
			/fabos/bin/userhashchk $type 

			stat=$?
			if [ $stat -ne 0 ]; then
				return $STS_ERR
			fi
		else
			return $STS_ERR

		fi
		check_801_opw_hash 	
	fi
	return $STS_OK
}

check_801_user_access_time_check()
{
	if [ $TO_MAJOR -eq 8 ] && [ $TO_MINOR -eq 0 ] && [ $TO_PATCH -eq 0 ]; then

		 if [ -s /etc/time.conf ]; then
			#If /etc/time.conf file has an entry other than "0000-0000",
			#for any user, then return error.
			grep -v "0000-0000" /etc/time.conf > /dev/null 2>&1
			check=$?
			if [ "$check" -ne "0" ]; then
				return $STS_OK
			else 
				return $STS_ERR
			fi
		fi
	else 
		return $STS_OK
	fi
	return $STS_OK
}

check_default_dynamic_portname()
{
	dynamic_portname=`/fabos/cliexec/config get switch.dynamicPortname 2`
	format=`/fabos/cliexec/config get switch.dynamicPortnameFormat 5`

	# For default portname format "S.T.I.A" Config key will not be available
	# Config get will return empty string for default portname format.
	if [ "$dynamic_portname" == "1" ] && [ "$format" != "" ] ;then
		return $STS_ERR
	else
		return $STS_OK
	fi
}

check_801_dynamic_portname()
{
	if [ $VF_ENABLED -ne $STS_OK ]; then
		CHASSISCMD="cmd_chassis"
		if [ $ACTIVECP ] ; then
			for_all_contexts check_default_dynamic_portname
		else
			for_all_contexts_standby check_default_dynamic_portname
		fi
	else
		check_default_dynamic_portname
	fi

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

#check if opassword hash of any user is set to SHA2
check_801_opw_hash()
{
	type=3
	/fabos/bin/userhashchk $type 
	stat=$?
	if [ $stat -ne 0 ]; then
		echo "WARNING !!!!! Password hash in the history contains non-MD5 hash for user(s) which must be cleared to proceed with downgrade." 
		echo "Please confirm with [Y/N] to proceed further, when prompted for."
		add_warn_status "$UNSUPPORTED_OPWHASH_MSG"
	fi
	return $STS_OK
}

#
# Check for Compression enable on C4 ports before downgrading to lower version 8.0.0
#
check_compression_fwdl() {
	case ${SWBD##SWBD} in
	'161' | '162')
	if [ $TO_MAJOR -eq 8 ] && [ $TO_MINOR -eq 0 ] && [ $TO_PATCH -eq 0 ]; then
		if `correcthost_to_curr_vfid /fabos/rbin/enccomp_fwdl_check | grep -q "Compression"`; then
			return $STS_ERR
		else
			return $STS_OK
		fi
	fi
	esac
}

#
# Check if any encryption-enabled ports are active.  "Acive" means they are
# online and connected as E-port, EX-port, etc.  If there are Active
# encryption ports, block downgrade.  The user needs to disable these
# ports to be able to downgrade.
#
check_encryption_block_downgrade() {

	do_encryption_fwdl_check=0;
	if [ $TO_MAJOR -eq 8 ]; then
		if [ $TO_MINOR -lt 2 ]; then
			do_encryption_fwdl_check=1;
		elif [ $TO_MINOR -eq 2 ] && [ $TO_PATCH -lt 1 ]; then
			do_encryption_fwdl_check=1;
		fi
	fi
	if [ $do_encryption_fwdl_check -eq 1 ]; then
		correcthost_all_vfs /fabos/link_bin/portenccompshow > $ENC_BLOCK_DGRD_FILE
		enc_blk_dgrd_check=`cat $ENC_BLOCK_DGRD_FILE | /bin/grep -c "Yes.\+Yes.\+[YN][oe].\+[YN][oe]"`

		if [ $enc_blk_dgrd_check -ne 0 ]; then
			rm $ENC_BLOCK_DGRD_FILE >/dev/null 2>&1
			return $STS_ERR
		fi
	fi

	rm $ENC_BLOCK_DGRD_FILE >/dev/null 2>&1
	return $STS_OK
}

#
# Check for Encryption enable on C4 ports before downgrading to lower version 8.0.x
#
check_encryption_fwdl() {
	# For Gen6 chassis block downgrade to 8.0.x when Encryption is enabled
	case ${SWBD##SWBD} in
	'165' | '166')
	if [ "$TO_MAJOR.$TO_MINOR" == "8.0" ]; then
		if `correcthost_to_curr_vfid /fabos/rbin/enccomp_fwdl_check | grep -q "Encryption"`; then
			return $STS_ERR
		else
			return $STS_OK
		fi
	fi
	esac
}

#
# Check for Encryption and Trunking configuration enable on Skywalker blade before
# downgrading to lower firmware version 8.1.x and 8.2.0 from 8.2.1.
#
check_encryption_trunking_on_skywalker() {
	case ${SWBD##SWBD} in
	'165' | '166')
	if `correcthost_to_curr_vfid /fabos/rbin/encr_trunk_fwdl_check | grep -q "Encryption"`; then
		return $STS_ERR
	else
		return $STS_OK
	fi
	esac
}

#
# Check for Encryption enable on C4 ports before downgrading to lower version 8.1.x
#
check_encryption_on_wedge64_fwdl() {
	# For Gen6 chassis block downgrade to 8.1.x when Encryption is enabled
	case ${SWBD##SWBD} in
	'162')
	if [ "$TO_MAJOR.$TO_MINOR" == "8.1" ]; then
		if `correcthost_to_curr_vfid /fabos/rbin/enccomp_fwdl_check | grep -q "Encryption"`; then
			return $STS_ERR
		else
			return $STS_OK
		fi
	fi
	esac
}

#
# Check for Compression enable on ports 44-47 before upgrading to version 8.2.0
#
check_compression_on_wedge64() {
	port_list=`correcthost_to_curr_vfid /fabos/bin/switchshow | awk '$1~/[4][4-7]/{print $1}'`
	for port in $port_list
	do
		Compression=`/fabos/link_bin/portcfgshow $port | grep "Compression" | awk '{print $2}'`
		if [ "$Compression" == "ON" ] ; then
			return $STS_ERR;
		fi
	done
	return $STS_OK
}

check_compression_on_wedge64_in_all_contexts() {
	if [ ${SWBD##SWBD} == '162' ]; then
		for_all_contexts check_compression_on_wedge64
		if [ $? -ne $STS_OK ]; then
			return $STS_ERR;
		fi
	fi
	return $STS_OK
}


#
# Check multiple switch role mapping is configured
#
check_multiple_switchRole_mapping()
{
if [ $TO_MAJOR -lt 8 -o $TO_MAJOR -eq 8 -a $TO_MINOR -eq 0 ]; then
	if [ -f /etc/fabos/ldap.map ]; then
	result=`/bin/awk '/;/{print}' /etc/fabos/ldap.map | wc -l`
		if [ $result -ge 1 ]; then
			return $STS_ERR
		fi
	fi
fi
return $STS_OK
}


# Check if flows are defined on VE Ports in current context.
VE_PORT_FLOWS_FID_FILE="/tmp/.preinst_ve_port_flows_fid.txt"
check_801_ve_port_flows()
{
	flow_ports=`/fabos/link_sbin/flow --show | grep -v -E "^-|^ " | cut -d "|" -f 5 | grep -v "\*" | grep -v "^-";/fabos/link_sbin/flow --show | grep -v -E "^-|^ " | cut -d "|" -f 6 | grep -v "\*" | grep -v "^-"`

	for port in $flow_ports
	do
		/fabos/link_bin/portshow $port | grep ^portFlags| grep -q VIRTUAL
		if [ $? -eq 0 ]; then
			# VE Port flows exist
			echo -n " $glb_vf_id" >> $VE_PORT_FLOWS_FID_FILE
			return $STS_OK
		fi
	done
	return $STS_OK
}

# Check if flows are defined on VE Ports on Skybolt.
check_801_ve_port_flows_in_all_contexts()
{
	if [ ${SWBD##SWBD} == '148' ]; then

		/bin/rm -f $VE_PORT_FLOWS_FID_FILE

		correcthost_all_vfs check_801_ve_port_flows
		
		if [ -f $VE_PORT_FLOWS_FID_FILE ]; then
			VE_PORT_FLOW_FIDS=`cat $VE_PORT_FLOWS_FID_FILE`
		fi

		if [ "$VE_PORT_FLOW_FIDS" != "" ]; then
			if [ $VF_ENABLED -ne $STS_OK ]; then
				add_err_status "The flows on VE Ports are created in switch FID(s):$VE_PORT_FLOW_FIDS"
			fi
			return $STS_ERR
		fi

		/bin/rm -f $VE_PORT_FLOWS_FID_FILE
	fi
	return $STS_OK
}

VTAP_QOS_FID_FILE="/tmp/vtap_qos_fid.txt"
#This function checks if vtap_qos mode is ON/OFF
check_vtap_qos_mode ()
{

	vtap_qos_mode=`/fabos/cliexec/config get fos.vTapQosHiZnCompMode 1`

	if [ "$vtap_qos_mode" == "1" ]; then
                vtap_qos_fid="`correcthost_to_curr_vfid /fabos/cliexec/configshow | sed -n 's/Fabric ID =//p'`"
                echo $vtap_qos_fid > $VTAP_QOS_FID_FILE

        fi
}

#This function checks if the build version supports vtap & QoS comp mode ON
check_vtap_QOS_comp_mode()
{
	#vTap  & QOS comp mode is not supported in v8.0.0 and lower
	#Block downgrade to those releases if this mode is on

	if [ $TO_MAJOR -lt 8 -o $TO_MAJOR -eq 8 -a $TO_MINOR -eq 0 -a $TO_PATCH -eq 0  ]; then

                echo "" > $VTAP_QOS_FID_FILE
                if [ $VF_ENABLED -ne $STS_OK ]; then
                        if [ $ACTIVECP ] ; then
                                for_all_contexts check_vtap_qos_mode
                        else
                                for_all_contexts_standby check_vtap_qos_mode
                        fi
                else
                        check_vtap_qos_mode
                fi

                vtap_qos_fid=`cat $VTAP_QOS_FID_FILE`

                /bin/rm $VTAP_QOS_FID_FILE

                if [ "$vtap_qos_fid" != "" ]; then
                        #if [ $VF_ENABLED -ne $STS_OK ]; then
                         #       add_err_status "The vTap and QOS compatibility mode is ON. Please turn off Compatibility Mode using configurechassis command"
                        #fi
                        return $STS_ERR
                fi

                return $STS_OK

        fi
        return $STS_OK

}

VTAP_ECB_FID_FILE="/tmp/vtap_ecb_fid.txt"

#This function checks if vtap_ECB mode is ON/OFF
check_vtap_ecb_mode ()
{

	vtap_ecb_mode=`/fabos/cliexec/config get fos.vTapECBcoexistMode 1`

	if [ "$vtap_ecb_mode" == "1" ]; then
                vtap_ecb_fid="`correcthost_to_curr_vfid /fabos/cliexec/configshow | sed -n 's/Fabric ID =//p'`"
                echo $vtap_ecb_fid > $VTAP_ECB_FID_FILE

        fi
}

#This function checks if the build version supports vtap & ECB co-existance
check_vtap_ECB_coexist_mode()
{
	#vTap  & ECB coexist mode is not supported in v8.1.0 and lower
	#Block downgrade to those releases if this mode is on

	if ! [ $TO_MAJOR -ge 8 -a $TO_MINOR -ge 1 -a $TO_PATCH -gt 0  ]; then

                echo "" > $VTAP_ECB_FID_FILE
                if [ $VF_ENABLED -ne $STS_OK ]; then
                        if [ $ACTIVECP ] ; then
                                for_all_contexts check_vtap_ecb_mode
                        else
                                for_all_contexts_standby check_vtap_ecb_mode
                        fi
                else
                        check_vtap_ecb_mode
                fi

                vtap_ecb_fid=`cat $VTAP_ECB_FID_FILE`

                /bin/rm $VTAP_ECB_FID_FILE

                if [ "$vtap_ecb_fid" != "" ]; then
                        return $STS_ERR
                fi

                return $STS_OK

        fi
        return $STS_OK

}

VTAP_FID_FILE="/tmp/vtap_fid.txt"

#This function checks if vtap is ON/OFF
check_vtap_enabled ()
{
	if /fabos/link_sbin/flow --show|grep "sys_analytics_vtap"|grep "mir+" > /dev/null; then
		echo -n " $glb_vf_id" >> $VTAP_FID_FILE
		return $STS_OK
	fi
	return $STS_OK
}

#downgrade needs to be blocked from 8.2 if vtap flow is active because of newly introduced
#ficon frame mirroring
#FCP/FICON RFM would work only if this file is present, so return ok if file is not present.
check_vtap_active()
{
	if [ ! -f '/etc/sys_analytics_vtap_ficon' ]; then
		return $STS_OK
	fi

	if [ $TO_MAJOR -lt 8 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -lt 2 ]; then
                echo "" > $VTAP_FID_FILE
                if [ $VF_ENABLED -ne $STS_OK ]; then
                        if [ $ACTIVECP ] ; then
                                for_all_contexts check_vtap_enabled
                        else
                                for_all_contexts_standby check_vtap_enabled
                        fi
                else
                        check_vtap_enabled
                fi

                vtap_fid=`cat $VTAP_FID_FILE`

                /bin/rm $VTAP_FID_FILE

                if [ "$vtap_fid" != "" ]; then
					if [ $VF_ENABLED -ne $STS_OK ]; then
						add_err_status "Vtap flow is active on switch FID(s):$vtap_fid"
					fi
                    return $STS_ERR
                fi

                return $STS_OK

        fi
        return $STS_OK
}

#downgrade needs to be blocked from 8.2 if both analyzer and vtap flow are active. 
check_analyzer_vtap_active()
{
	if [ ! -f '/etc/sys_analyzer_flow' ]; then
		return $STS_OK
	fi

	if [ $TO_MAJOR -lt 8 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -lt 2 ]; then
                echo "" > $VTAP_FID_FILE
                if [ $VF_ENABLED -ne $STS_OK ]; then
                        if [ $ACTIVECP ] ; then
                                for_all_contexts check_vtap_enabled
                        else
                                for_all_contexts_standby check_vtap_enabled
                        fi
                else
                        check_vtap_enabled
                fi

                vtap_fid=`cat $VTAP_FID_FILE`

                /bin/rm $VTAP_FID_FILE

                if [ "$vtap_fid" != "" ]; then
					if [ $VF_ENABLED -ne $STS_OK ]; then
						add_err_status "Vtap flow is active on switch FID(s):$vtap_fid"
					fi
                    return $STS_ERR
                fi

                return $STS_OK

        fi
        return $STS_OK
}
RRDY_PORT_FILE="/tmp/rrdy_port.txt"

#This function checks if the switch is a base switch, and if so,
#whether any port is configured ISL R_RDY mode.
check_isl_rrdy_bs()
{
	BASE=`correcthost_to_curr_vfid /fabos/bin/switchshow | grep "Base Switch:" | cut -d ' ' -f 6 | cut -d ',' -f 1`
	if [ "$BASE" == "Yes" ]; then
                correcthost_to_curr_vfid /fabos/cliexec/portcfgshow | grep "ISL R_RDY" | grep ON >> $RRDY_PORT_FILE
		port_list=`correcthost_to_curr_vfid /fabos/bin/switchshow | grep " FC " | grep "Online " | awk '{print $1}'`
		for port in $port_list
		do
                	correcthost_to_curr_vfid /fabos/cliexec/portshow -i $port | grep E_Port | grep "control mode 2" >> $RRDY_PORT_FILE
		done
	fi
	return $STS_OK
}

#This function checks if FMC configuration is enabled on switch.
check_is_fmc_enabled()
{
	case ${SWBD##SWBD} in
	'165' | '166')
		if ! [ $TO_MAJOR -ge 8 -a $TO_MINOR -ge 2 -a $TO_PATCH -gt 0  ]; then
			FMC_CFG=`/fabos/cliexec/configshow -a| sed -n 's/system.eth_rate_limit://p'`
			if [ "$FMC_CFG" == "1" ] ; then
				return $STS_ERR
			fi
		fi
		;;
	*)
		;;
	esac

	return $STS_OK
}
#This function checks if the build version supports ISL R_RDY on base switch
check_isl_rrdy_bs_in_all_contexts()
{
	# ISL R_RDY on base switch is not supported in 8.2.0 and earlier
	# Block downgrade to those releases if ISL R_RDY is configured on base switch port

	if ! [ $TO_MAJOR -ge 8 -a $TO_MINOR -ge 2 -a $TO_PATCH -gt 0  ]; then

        	touch $RRDY_PORT_FILE
                if [ $VF_ENABLED -ne $STS_OK ]; then
                        if [ $ACTIVECP ] ; then
                                for_all_contexts check_isl_rrdy_bs
                        else
                                for_all_contexts_standby check_isl_rrdy_bs
                        fi
                fi

		num_rrdy_lines=`cat $RRDY_PORT_FILE | wc -l`
		/bin/rm $RRDY_PORT_FILE

		if [ $num_rrdy_lines -ge 1 ]; then
			return $STS_ERR

		fi
        fi

        return $STS_OK
}

FMS_FID_FILE="/tmp/fms_fid.txt"

#This function checks if FICON CUP configured on current LS
check_fms_enabled()
{
        fms_enabled=`/fabos/bin/ficoncupshow fmsmode | grep Enabled 2>/dev/null`

        if [ "$fms_enabled" != "" ] ; then
                fid="`correcthost_to_curr_vfid /fabos/cliexec/configshow | sed -n 's/Fabric ID = //p'`"
                did="`correcthost_to_curr_vfid /fabos/cliexec/configshow | sed -n 's/fabric.domain://p'`"
                echo "$fid($did)" >> $FMS_FID_FILE
        fi


}

#This function checks if FICON CUP configured on more than four partitions.
check_multiple_FMS_enabled()
{
        touch $FMS_FID_FILE
        if [ $VF_ENABLED -ne $STS_OK ]; then
                if [ $ACTIVECP ] ; then
                        for_all_contexts check_fms_enabled
                else
                        for_all_contexts_standby check_fms_enabled
                fi
        fi
        num_of_FMS_enabled=`cat $FMS_FID_FILE | wc -l`
        FMS_fids=`cat $FMS_FID_FILE | tr '\r\n' ' '`

        /bin/rm $FMS_FID_FILE

        if [ $num_of_FMS_enabled -gt 4 ]; then
                echo "$1"
                echo "FIDs (Domain IDs):  $FMS_fids"
        fi
        return $STS_OK

}

#
# Congestion and latency monitoring being obsolete
#
check_74_BD_to_maps_migration_warn()
{
	migrate=0
    migrate=`CONFIGSHOW -all | /bin/grep "bottleneck.enabled:1" | wc -l`

    #
    # before upgrade to 8.0, if BD is enabled, then display the warnings.
	#
	if [ -n "$migrate" ]; then
        if [ "$migrate" -gt 0 ]; then
            echo -e $BD_TO_MAPS_MIGRATION
			# log warn msg to BNA status file
            echo -e $BNA_BD_TO_MAPS_MIGRATION >> $BNA_STATUS_FILE
		fi
	fi
	return $STS_OK

}

check_maps_810_features_to_give_warning()
{
   bnaErr=0
   warningDisplayed=0

   FOS_VER="8.1.0"
   tokenList="severity="

   > ${MAPS_WARN_FILE}

	if [ ! -f "${MAPS_WARN_FILE}" ]
	then
		touch ${MAPS_WARN_FILE}
	fi
	rm -f /tmp/.warningDisplayed_810 > /dev/null 2>&1
    for token in $tokenList
    do
      if [ $VF_ENABLED -ne $STS_OK ]; then
          if [ $ACTIVECP ] ; then
              for_all_contexts check_maps_one_feature_to_give_warning $token "$FOS_VER" ""
          else
              for_all_contexts_standby check_maps_one_feature_to_give_warning $token "$FOS_VER" ""
          fi
      else
	  check_maps_one_feature_to_give_warning $token "$FOS_VER" ""
      fi
	done
        warningDisplayed=0
    if [ -s "${MAPS_WARN_FILE}" ]
      then
        echo -e "\n" >> ${MAPS_WARN_FILE}
        echo "WARNING:"
        warnDisplayed=1
        cat ${MAPS_WARN_FILE}
        rm ${MAPS_WARN_FILE}
        bnaErr=1
    fi
	rm -f /tmp/.warningDisplayed_810 > /dev/null 2>&1
	rm -f /tmp/.warningDisplayed_810_ror > /dev/null 2>&1
    if [ $bnaErr -ne 0 ]
    then
#       echo "bna is being logged.."
        add_warn_status  "$BNA_MAPS_810_WARN"
    fi
}

 
check_rekey_configuration()
{

rekeyintval=`/bin/cat /etc/sshd_config  | /bin/grep "#RekeyInterval"`

if [ "$rekeyintval" != '' ]; then
	return $STS_OK
else 
	rekeyintval=`/bin/cat /etc/sshd_config  | /bin/grep "RekeyInterval" | /bin/awk '{print $2}'`
	if [ "$rekeyintval" != '' ]; then
		return $STS_ERR	
	fi

	return $STS_OK
fi

}

check_ldapuser_rolemap_root()
{
  if [ -f '/etc/fabos/ldap.map' ]; then

	  rootUser=`/bin/awk -F ':' '{print $2}' /etc/fabos/ldap.map |/bin/grep -w root`

  	if [ ! -z $rootUser ]; then
		return $STS_ERR	
  	fi
  fi
  return $STS_OK
}

check_ls_support()
{
	LS=`/fabos/link_rbin/hasmtest dump | grep "SGI fcsw" | cut -d ':' -f 2 | awk '$1'`
	for LS_index in $LS
                do
                if [ $LS_index -gt 7 ] ; then
			return $STS_ERR
		fi
		done
	return $STS_OK
}


#
# Check multiple switch role mapping is configured
#
check_multiple_switchRole_mapping()
{
if [ $TO_MAJOR -lt 8 -o $TO_MAJOR -eq 8 -a $TO_MINOR -eq 0 ]; then
	if [ -f /etc/fabos/ldap.map ]; then
	result=`/bin/awk '/;/{print}' /etc/fabos/ldap.map | wc -l`
		if [ $result -ge 1 ]; then
			return $STS_ERR
		fi
	fi
fi
return $STS_OK
}
#check any mirror flows are configured in the switch
check_ag_flow_mirror()
{
	ag_mode_enabled
	if [ $? -gt 0 ]; then
		mir_count=`/fabos/link_sbin/flow --show | grep "mir" | grep -v "sys_analytics_vtap" -c`
		if [ $mir_count -ne 0 ]; then
			return $STS_ERR
		fi
	else
		return $STS_OK
	fi
}

#Check for Mirror port configuration in AG mode
check_Mirror_configuration()
{
	ag_mode_enabled
	if [ $? -gt 0 ]; then
	port_list=`/fabos/bin/switchshow | grep " FC " | awk '{print $4}'`
	index=0
	for port in $port_list
		do
		if [ $port == "cu" ] ; then
			index=`expr $index + 1`
			continue;
		fi
		Trunk=`/fabos/link_bin/portcfgshow $index | grep "Mirror Port" | awk '{print $3}'`
		if [ "$Trunk" == "ON" ] ; then
			return $STS_ERR
		fi
		index=`expr $index + 1`
	done
		return $STS_OK
	else
		return $STS_OK
	fi
}

#Check for Remote Fosexec feature in AG mode
check_remote_fosexec()
{
	ag_mode_enabled
	if [ $? -gt 0 ]; then
		fosexec_set=`/fabos/cliexec/config get fabric.remoteFosexec 2`
		if [ $fosexec_set -ne 0 ]; then
			return $STS_ERR
		fi
	else
		return $STS_OK
	fi
}

check_dhcpv6_enable()
{
dhcpv6_support=0
if [ $CUR_MAJOR -ge 8  -a $TO_MAJOR -eq 7 ]; then
	for ver in 117 129 156 157 158; do
		if [ ${SWBD##SWBD} == "$ver" ]; then
			dhcpv6_support=1
		fi
	done

	if [ $dhcpv6_support -eq 0 ]; then
		result=`/fabos/cliexec/ipaddrshow | grep "DHCPv6: On" | wc -l`
		if [ $result -eq 1 ]; then
			return $STS_ERR
		fi
	fi
		
fi
return $STS_OK
}

# Not allowed to upgrade to this version if FCOE blade is present
check_europa_blade() {
    result=`/fabos/cliexec/slotshow -m | grep "FCOE10-24" | wc -l`
    if [ $result -ge 1 ]; then
		return $STS_ERR
    else
       return $STS_OK
    fi
}

# Not allowed to upgrade to this version if Lance blade is present
check_lance_blade() {
    result=`/fabos/cliexec/slotshow -m | grep "FS8-18" | wc -l`
    if [ $result -ge 1 ]; then
        return $STS_ERR
    else
       return $STS_OK
    fi
}

# Check if Chassis contains a Harpoon blade
check_harpoon_blade() {
	result=`/fabos/cliexec/slotshow -m | grep "SX6" | wc -l`
	if [ $result -ge 1 ]; then
		return 1
	else
		return 0
	fi
}

#Check if Admin domain are enabled in the switch.
check_admin_domain_enabled() {
	if [ $CUR_MAJOR -gt 8 -o $CUR_MAJOR -eq 8 -a $CUR_MINOR -ge 2 ]; then
		return $STS_OK
	fi
    result=`/fabos/abin/ad --exec 255 "ad --show" | grep -E "State: Active|State: Inactive" | wc -l`
    if [ $result -ge 1 ]; then
        return $STS_ERR
    else
        return $STS_OK
    fi
}


check_combo_bit_license_migration_check()
{
    LICENSE_SHOW_FILE=/tmp/licenseshow.txt
    /fabos/bin/licenseshow > $LICENSE_SHOW_FILE

    colon=0
    nlines=0
    nfirst=0
    nsecond=0
    nfull=0

    # following code would be needed to skip the check completely for AWING platforms...
    case ${SWBD##SWBD} in '178')
            return $STS_OK
            ;;
    esac

    while IFS='' read -r line || [[ -n "$line" ]]; do
        #echo "$line"

        # skip optional extraneous lines for each license
        if echo "$line" | grep -q "Capacity";
        then
            continue
        fi
        if echo "$line" | grep -q "Consumed";
        then
            continue
        fi
	if echo "$line" | grep -q "Configured";
        then
            continue
        fi
        if echo "$line" | grep -q "Expiry Date";
        then
            continue
        fi
        if echo "$line" | grep -q "License has expired";
        then
            continue
        fi

        # look for colon in the line (license string)
        colon=`echo $line | grep : | wc -l`
        if [ "$colon" -eq 1 ] ; then
            #clear counters
            nlines=0
            nfirst=0
            nsecond=0
            nfull=0
        else
            nlines=$((nlines +1))
	            n1=`echo $line | grep "First Ports" | wc -l`
            n2=`echo $line | grep "Second Ports" | wc -l`
            n3=`echo $line | grep "Full Ports" | wc -l`
            nfirst=$((nfirst+n1))
            nsecond=$((nsecond+n2))
            nfull=$((nfull+n3))
            #echo $nlines $nfirst $nsecond $nfull

            # only two lines allowed for POD licenses - license string and feature name
            if [ "$nlines" -gt 1 ] ; then
                if [ "$nfirst" -gt 0 -o "$nsecond" -gt 0 -o "$nfull" -gt 0 ]; then
                    # extra lines implies other combo features included
                    #echo ">>>>>>>>>>>detected disallowed combo license"
                    rm $LICENSE_SHOW_FILE
                    return $STS_ERR
                fi
            fi
        fi
    done < $LICENSE_SHOW_FILE

    rm $LICENSE_SHOW_FILE
    return $STS_OK
}





#
# Disallow upgrade with 24-bit/legacy licenses present except for selected OUI's
#
check_24_bit_license_migration_check()
{
    OLD_LICENSE_FILE=/etc/fabos/licenses

# following code would be needed to skip the check completely for Gen6 platforms...
    case ${SWBD##SWBD} in
        '161' | '162' | '165' | '166' | '169' | '170' | '178')
            # no-op for Gen6 hardware...
            #echo "Skip 24-bit license check for Gen6"
            return $STS_OK
            ;;
    esac

    # if no file, no older licenses are installed
    if [ ! -e $OLD_LICENSE_FILE ] ; then
        # echo "No older licenses found"
        return $STS_OK
    fi
    # echo "Older licenses found" # REMOVE ME

    licenses=`ls -l $OLD_LICENSE_FILE | awk -F " " '{ print $5 }'`

    if [ -n "$licenses" ]; then
        if [ "$licenses" -gt 0 ]; then
            oui=`/fabos/cliexec/licenseidshow | awk -F ":" '{ print $3 $4 $5 }'`
            if  [ $oui == "50eb1a" ] ; then return $STS_OK; fi
            if  [ $oui == "0027f8" ] ; then return $STS_OK; fi
            if  [ $oui == "006069" ] ; then return $STS_OK; fi
            if  [ $oui == "00051e" ] ; then return $STS_OK; fi
            if  [ $oui == "00110a" ] ; then return $STS_OK; fi
            if  [ $oui == "000533" ] ; then return $STS_OK; fi

            return $STS_ERR
        fi
    fi
    return $STS_OK
}

check_fips_snmp_md5()
{
	FIPSMODE=`CONFIGSHOW -all | /bin/grep "fips.mode" | /usr/bin/cut -d ':' -f2`
	if [ "$FIPSMODE" != "1" ];then
		return $STS_OK
	fi
	for (( i = 0; i < 6; i++ ))
	do
		# Skip the .default key using -v
		AUTHPROTO=`CONFIGSHOW -all | /bin/grep "snmp.snmpv3Usm.$i.usmAuthProtocol" | /bin/grep -v "snmp.snmpv3Usm.$i.usmAuthProtocol.default" | /usr/bin/cut -d ':' -f2`
		if [ "$AUTHPROTO" -eq "1" ];then
			return $STS_ERR
		fi
	done

	return $STS_OK
}

check_fips_snmp_pass_len()
{
	FIPSMODE=`CONFIGSHOW -all | /bin/grep "fips.mode" | /usr/bin/cut -d ':' -f2`
	if [ "$FIPSMODE" != "1" ];then
		return $STS_OK
	fi
	for (( i = 0; i < 6; i++ ))
		do
		AUTHPROTO=`CONFIGSHOW -all | /bin/grep "snmp.snmpv3Usm.$i.usmAuthProtocol" | /bin/grep -v "snmp.snmpv3Usm.$i.usmAuthProtocol.default" | /usr/bin/cut -d ':' -f2`
			# Skip password check if NOAUTH is configured
		if [ "$AUTHPROTO" != "3" ];then
			# Skip the .default key using -v
			AUTHLEN=`CONFIGSHOW -all | /bin/grep "snmp.snmpv3Usm.$i.usmAuthSecret" | /bin/grep -v "snmp.snmpv3Usm.$i.usmAuthSecret.default" | /usr/bin/cut -d ':' -f2 |  wc -c`
			PRIVLEN=`CONFIGSHOW -all | /bin/grep "snmp.snmpv3Usm.$i.usmPrivSecret" | /bin/grep -v "snmp.snmpv3Usm.$i.usmPrivSecret.default" | /usr/bin/cut -d ':' -f2 |  wc -c`
			#
			# Decrementing by 1 because wc -c returns number of characters including null 
			#
			AUTHLEN=$((AUTHLEN-1))
			PRIVLEN=$((PRIVLEN-1))
			if [ "$AUTHLEN" -lt "8" ] || [ "$PRIVLEN" -lt "8" ];then
				return $STS_ERR
			fi
		fi
		done
	return $STS_OK
}
#FOS-807914
check_snmp_password_len()
{

	SNMP_USER_PASSWD_ENC=`CONFIGSHOW -all | /bin/grep "snmp.usmUserPaswdEncFlag" | /usr/bin/cut -d ':' -f2`
	if [ "$SNMP_USER_PASSWD_ENC" == "1" ];then
			echo -e "$SNMP_USER_PASSWD_ENCRYPTION_WARN"
			add_warn_status "$BNA_SNMP_USER_PASSWD_ENCRYPTION_WARN"
			return $STS_OK
	fi

	date > /tmp/snmp_config.txt
	CONFIGSHOW -all >> /tmp/snmp_config.txt
    for (( i = 0; i < 6; i++ ))
        do
        AUTHPROTO=`/bin/cat /tmp/snmp_config.txt  | /bin/grep "snmp.snmpv3Usm.$i.usmAuthProtocol" | /bin/grep -v "snmp.snmpv3Usm.$i.usmAuthProtocol.default" | /usr/bin/cut -d ':' -f2`
            # Skip password check if NOAUTH is configured
        if [ "$AUTHPROTO" != "3" ];then
            # Skip the .default key using -v
            AUTHLEN=`/bin/cat /tmp/snmp_config.txt | /bin/grep "snmp.snmpv3Usm.$i.usmAuthSecret" | /bin/grep -v "snmp.snmpv3Usm.$i.usmAuthSecret.default" | /usr/bin/cut -d ':' -f2 |  wc -c`
            PRIVLEN=`/bin/cat /tmp/snmp_config.txt | /bin/grep "snmp.snmpv3Usm.$i.usmPrivSecret" | /bin/grep -v "snmp.snmpv3Usm.$i.usmPrivSecret.default" | /usr/bin/cut -d ':' -f2 |  wc -c`
            #
            # Decrementing by 1 because wc -c returns number of characters
            # including null 
            #
            AUTHLEN=$((AUTHLEN-1))
            PRIVLEN=$((PRIVLEN-1))
			if [ "$AUTHLEN" -lt "8" ] || [ "$PRIVLEN" -lt "8" ];then
                echo -e "$UNSUPPORTED_SNMP_PASS_LEN"
                add_warn_status "$BNA_UNSUPPORTED_SNMP_PASS_LEN"
                return $STS_ERR
            fi
        fi
        done
	rm -rf /tmp/snmp_config.txt 2>/dev/null
    return $STS_OK
}

check_snmp_user_encrypted_passwd()
{
	SNMP_USER_PASSWD_ENC=`CONFIGSHOW -all | /bin/grep "snmp.usmUserPaswdEncFlag" | /usr/bin/cut -d ':' -f2`
	if [ "$SNMP_USER_PASSWD_ENC" == "1" ];then
		return $STS_ERR
	fi
}

check_imported_template()
{
        #### Downgrade from 8.1 is prevented if templates other than default templates
        #### have attributes that are not supported pre 8.1

	if [ $TO_MAJOR -eq 8 ] && [ $TO_MINOR -eq 0 ]; then
        	TEMPLATE_DIR="/etc/fabos/templates"
        	TEMPLATE_CC="default_cc"
        	TEMPLATE_FIPS="default_fips"
        	TEMPLATE_GENERIC="default_generic"
        	TEMPLATE_STRONG="default_strong"
        	TEMPLATES=`/bin/ls $TEMPLATE_DIR/ -I $TEMPLATE_CC -I $TEMPLATE_FIPS -I $TEMPLATE_GENERIC -I $TEMPLATE_STRONG 2>/dev/null`

        	if [ ! -z "$TEMPLATES" ]; then
                	for i in $TEMPLATES
                	do
                        	if [ -s "$TEMPLATE_DIR/$i" ]; then
					/bin/grep '^[^#]' $TEMPLATE_DIR/$i | /bin/grep 'Syslog\|Protocol\|Validation' > /dev/null 2>&1
                                	check=$?
                                	if [ $check = 0 ]; then
                                        	return $STS_ERR
                                	fi
                        	fi
                	done
        	fi
	fi
	return $STS_OK
}

check_32G_brkout_qsfp()
{
    # 32G_BRKOUT_QSFP is not supported older firmware.
    # Check if any 32G breakout QSFPs on any ports. If so then block the downgrade.
    qsfp_32G_brkout_fwdl_ret=`correcthost_to_curr_vfid /fabos/bin/breakout_32G_qsfp_fwdl_check 2>/dev/null | grep -E "ZUA serial numbered QSFP"`
	if [ $? -eq 0 ]; then
		let rc=$rc+1
		echo -e $rc:	$qsfp_32G_brkout_fwdl_ret >> $STATUS_FILE
		echo -e $QSFP_32G_FWDL_BLOCK  >> $STATUS_FILE
		echo -e $rc:	$qsfp_32G_brkout_fwdl_ret >> $BNA_STATUS_FILE
		echo -e $QSFP_32G_FWDL_BLOCK  >> $BNA_STATUS_FILE
		return $STS_ERR;
	fi
    return $STS_OK
}

check_fips_mode_support()
{
	FIPSSIMULATE=`CONFIGSHOW -all | /bin/grep "fips.simulate" | /usr/bin/cut -d ':' -f2`
	if [ "$FIPSSIMULATE" == "1" ];then
		return $STS_ERR
	fi
	FIPSMODE=`CONFIGSHOW -all | /bin/grep "fips.mode" | /usr/bin/cut -d ':' -f2`
	if [ "$FIPSMODE" == "1" ];then
		echo -e $FIPSMODE_NOTSUPPORTED
		add_warn_status "$FIPSMODE_NOTSUPPORTED"
	fi
	return $STS_OK
}

check_fips_inside_support()
{
	FIPSINSIDE=`CONFIGSHOW -all | /bin/grep "fips.inside" | /usr/bin/cut -d ':' -f2`
	if [ "$FIPSINSIDE" == "" ];then
		return $STS_OK # handle cases where the fips.inside key does not exist
	fi
	if [ "$FIPSINSIDE" -ne "0" ];then
		return $STS_ERR # block if fips.inside config set to 1
	fi

	return $STS_OK
}

check_max_ipfilter_policy()
{
	if [ $CUR_MAJOR -lt 8 ]  || [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -lt 2 ] || [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -eq 2 -a $CUR_PATCH -lt 1 ]; then
		if [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 2 -a $TO_PATCH -eq 1 ]; then
			MAX_POLICY=`/fabos/abin/ipfilter --show | /bin/grep "Name" -c`
			if [ "$MAX_POLICY" -gt 6 ]; then
				return $STS_ERR
			fi
		fi
	fi
	return $STS_OK
}

check_ipfilter_policy_name()
{
	if [ $CUR_MAJOR -lt 8 ]  || [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -lt 2 ] || [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -eq 2 -a $CUR_PATCH -lt 1 ]; then
		if [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 2 -a $TO_PATCH -eq 1 ]; then
			POLICY_NAME=`/fabos/abin/ipfilter --show | /bin/grep "default_ipv4_2\|default_ipv6_2" -c`	
			if [ "$POLICY_NAME" -ne 0 ]; then 
				return $STS_ERR
			fi
		fi
	fi
	return $STS_OK
}
INS_STR='7.4.0_ins'
INS1_STR='7.4.0_ins[0-9a-zA-Z_]'
#
# perform Inspur rev check and block firmwaredownload when a Tianlong board
# loading from ins1 to ins (Shenlong) version
#
check_ins_version()
{
    case ${SWBD##SWBD} in
    '167')
    # only apply check for Tianlong; Shenlong is free to fwdl around
    /bin/cat /proc/system/Tianlong | grep "1" > /dev/null
    if [ $? == 0 ]; then
            /bin/cat $RELEASE_FILE | /fabos/bin/grep -e $INS_STR 2>&1 1>/dev/null
            if [ $? == 0 ] ; then   # check if fwdl ver has ins str
                # yes, now check if has insX, X?
                /bin/cat $RELEASE_FILE | /fabos/bin/grep -e $INS1_STR 2>&1 1>/dev/null
                if [ $? != 0 ] ; then   # check if fwdl having X?
                    # no X, means fwdl to ins ver, blocked fwdl
                    add_err_status "$INS_REV_MSG";
                    return $STS_ERR
                else
                    return $STS_OK
                fi
            fi
    fi
    esac
    return $STS_OK
}

add_obsolete_accounts()
{
	if [ $TO_MAJOR -eq 8 ] && [ $TO_MINOR -eq 0 ] && [ $TO_PATCH -eq 0 ]; then
		/bin/grep "^factory:" /mnt/etc/group > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
		then 
	        	/bin/echo "factory::601:factory,root" >> /mnt/etc/group
		fi
		/bin/grep "^disk:" /mnt/etc/group > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
		then 
		        /bin/echo "disk::6:root" >> /mnt/etc/group
		fi
		/bin/grep "^kmem:" /mnt/etc/group > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
		then 
		        /bin/echo "kmem::9:" >> /mnt/etc/group
		fi
		/bin/grep "^tty:" /mnt/etc/group > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
		then 
		        /bin/echo "tty::5:" >> /mnt/etc/group
		fi
		/bin/grep "^bin:" /mnt/etc/group > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
		then 
		        /bin/echo "bin::1:root,bin,daemon" >> /mnt/etc/group
		fi
		/bin/grep "^bin:" /mnt/etc/passwd > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
		then 
		        /bin/echo "bin:*:1:1:bin:/bin:" >> /mnt/etc/passwd
		fi
	        rand_pass=`/usr/bin/openssl rand 16 -base64 2> /dev/null`
		/bin/grep "^factory:" /mnt/etc/passwd > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
		then 
		        /bin/echo "factory:$rand_pass:0:601:Diagnostics:/fabos/users/diag:/bin/rbash" >> /mnt/etc/passwd
		fi
		/bin/grep "^factory:" /mnt/etc/shadow > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
		then 
		        /bin/echo "factory:$rand_pass:::::::" >> /mnt/etc/shadow
		fi
	fi
}

check_if_Analytics()
{
	case ${SWBD##SWBD} in
        '148')
    isSOLO=`/fabos/bin/switchshow | grep switchMode | grep -c Analytics`

	if [ $isSOLO -ne 0 ]; then
		add_err_status "$UNSUPPORTEDANALYTICSMSG" "$BNA_UNSUPPORTEDPLATFORMMSG"
		return ${STS_ERR}
	fi
	esac
	return ${STS_OK}
}

check_anakin_blade() {
    result=`/fabos/cliexec/slotshow -m | grep "FC32-64" | wc -l`
    if [ $result -ge 1 ]; then
        return $STS_ERR
    else
       return $STS_OK
    fi
}

check_multiple_secure_syslog_configuration()
{
	if [ $CUR_MAJOR -lt 8 ] || [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -lt 1 ]; then
	    certcount=0
    	secureserverscount=0

	    certs=`/bin/ls /etc/syslog-ng/ca.d/*.pem 2> /dev/null`

    	if [ ! -z "$certs" ]; then
        	for i in $certs
	        do
    	    if [ -s "$i" ]; then
        	    certcount=`/usr/bin/expr $certcount  + 1`
	        fi
    	    done
	    fi

    	if [ $certcount -gt 1 ]; then
        	return $STS_ERR
	    fi
	fi

    return $STS_OK
}

check_snmp_groupname_ro()
{
	g_value=`CONFIGSHOW -all | /bin/grep "snmp.groupname" | /usr/bin/cut -d ':' -f2`
	if [ "$g_value" -gt "0" ];then
		return $STS_ERR
	fi

	return $STS_OK
}

check_TI_MAX_ZONENAME_exists() {
	correcthost_all_vfs /fabos/cliexec/zone --show | /bin/grep "TI Zone Name" | /bin/awk '{ len=length($4); if (len >= 64) {exit 1} }'
	return $?
}

check_au_license_installed()
{
	# Check for Analytics Upgrade License
	au_lic=`/fabos/bin/licenseshow | grep "Analytics Upgrade license" | wc -l`

	if [ $au_lic -eq 0 ]; then
		return $STS_ERR
	fi

	return $STS_OK
}

check_dynamic_lags_exist()
{
	for i in `CONFIGSHOW_ADV -all | grep ^lacpd\.lag\.type\.[0-9][0-9]*: | sed -e 's/.*://'`; do
		if [ $i -eq 1 ]; then
			return $STS_ERR;
		fi
	done
	return $STS_OK;
}

check_Thalassa8G_blade() {
	result=`/fabos/cliexec/slotshow -m | grep "FC8-48E" | wc -l`
	if [ $result -ge 1 ]; then
		return $STS_ERR
	else
		return $STS_OK
	fi
}

check_lacp_global_config_exist()
{
        is_lacp_global_config_exist=`CONFIGSHOW | grep "lacpd.systemprio" | wc -l`

        if [ $is_lacp_global_config_exist -eq 0 ]; then
                return $STS_OK
        fi

        return $STS_ERR
}

check_lldp_config_exist()
{
        is_lldp_config_exist=`CONFIGSHOW | grep "lldp" | wc -l`

        if [ $is_lldp_config_exist -eq 0 ]; then
                return $STS_OK
        fi

        return $STS_ERR
}

check_fcoe_config_exist()
{
        is_fcoe_config_exist=`CONFIGSHOW | grep "fcoed.fabmap" | wc -l`

        if [ $is_fcoe_config_exist -ne 0 ]; then
                return $STS_ERR
        fi

        is_fcoe_config_exist=`CONFIGSHOW | grep "fcoed.numberof.enodes" | wc -l`

        if [ $is_fcoe_config_exist -ne 0 ]; then
                return $STS_ERR
        fi

        is_fcoe_config_exist=`CONFIGSHOW | grep "fcoed.numberof.fcoeports" | wc -l`

        if [ $is_fcoe_config_exist -ne 0 ]; then
                return $STS_ERR
        fi

        is_fcoe_config_exist=`CONFIGSHOW | grep "fcoed.port.provision" | wc -l`

        if [ $is_fcoe_config_exist -ne 0 ]; then
                return $STS_ERR
        fi

        is_fcoe_config_exist=`CONFIGSHOW | grep "fcoed.port.lag" | wc -l`

        if [ $is_fcoe_config_exist -ne 0 ]; then
                return $STS_ERR
        fi

        return $STS_OK
}

check_8bit_route()
{
		if [ $VF_ENABLED -ne $STS_OK ]; then
			if [ -f "/fabos/link_sbin/lscfg_test" ]; then
				rm -rf /fabos/link_sbin/lscfg_test   
			fi
			/bin/ln -s /fabos/cliexec/lscfg_util /fabos/link_sbin/lscfg_test 2> /dev/null
                        export PATH=/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/link_rbin:/fabos/factory:/fabos/xtool
			default_fid=`lscfg_test --all | grep -i default | sed 's/ \+/ /g' | cut -f3 -d" "`
			rm -rf /fabos/link_sbin/lscfg_test
			context_switch $default_fid
		fi

		is_8bit_route=`correcthost /fabos/link_sbin/portaddress --show -fc32-48 |grep "8 bit" | grep -v "Y" |wc -l`

		if [ $is_8bit_route -ne 0 ]; then
			return $STS_ERR
		fi
        return $STS_OK
}

#check passwordless login (using public key) exists in 8.0 or 8.1 or 8.2.0
check_passwordless_login()
{
	#check passwordless login allowed for root
	if [ -e $AUTHORIZED_KEYS_PATH/authorized_keys.root ];then
		return $STS_ERR
 	fi
 	return $STS_OK
}

#
# Check AG-SDDQ Devices (Applicable to 8.2.1 downgrade scenarios)
#
check_ns_ag_sddq_devices() {
	totalSddqAgDevs=0
	sddqAgDevs=0

	# Skip AMP - No locally connected devices
	analyticsMode=`correcthost /fabos/link_bin/switchshow | grep "Analytics" -c`
	if [ $analyticsMode -eq 1 ]; then
		return $STS_OK
	fi

	# AG-SDDQ not supported prior to FOS 8.2.1
	if ! [ $TO_MAJOR -ge 8 -a $TO_MINOR -ge 2 -a $TO_PATCH -gt 0  ]; then
		# Check all VF contexts
		if [ $VF_ENABLED -ne $STS_OK ]; then
			if [ $ACTIVECP ] ; then
				FID_LIST=${CONTEXTS}
			else
				/bin/ln -s /fabos/cliexec/lscfg_util /fabos/link_sbin/lscfg_test 2> /dev/null
				export PATH=/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/link_rbin:/fabos/factory:/fabos/xtool
				STANDBY_FIDS=`lscfg_test --all | grep -e "[0-9]" | grep -v "Total" | awk '{ print $2 }'`
				FID_LIST=$STANDBY_FIDS
			fi

			for FID in $FID_LIST ; do
				context_switch $FID
				sddAgDevs=`/fabos/cliexec/ns chk_ag_sddq`
				totalSddqAgDevs=`expr $totalSddqAgDevs + $sddAgDevs`
			done
		else
			sddAgDevs=`/fabos/cliexec/ns chk_ag_sddq`
			totalSddqAgDevs=`expr $sddAgDevs`
		fi

		# If total AG SDDQ device count is non-zero, block non-disruptive downgrade
		if [ $totalSddqAgDevs -gt 0 ]; then
               	is_fwdl_arg "s"
			if [ $? -ne 0 ]; then
				add_err_status "Error: Non-disruptive downgrade not allowed due to AG-connected devices quarantined by SDDQ feature. Either disable or unquarantine said devices, or issue \"firmwaredownload\" with single mode option enabled."
				return $STS_ERR
                       fi
		fi
	fi

	return $STS_OK
}

#
# Check SDDQ Devices in AG Mode(Applicable to 8.2.1 downgrade scenarios)
#
check_ag_sddq_devices() {
	sddqAgDevs=0
	totalSddqAgDevs=0
	totalsddqAgPorts=0

	# SDDQ is not supported in AG mode prior to FOS 8.2.1
	if ! [ $TO_MAJOR -ge 8 -a $TO_MINOR -ge 2 -a $TO_PATCH -gt 0  ]; then
		ag_mode_enabled
		if [ $? -gt 0 ]; then
			sddqAgDevs=`/fabos/cliexec/agdbg --dump | grep "SDDQ Device Count:" | awk '{print $4}'`
			totalSddqAgDevs=`expr $sddqAgDevs`
			totalsddqAgPorts=`/fabos/bin/sddquarantine --show | grep "Ports marked as Slow Drain Quarantined in the Local Switch" -A 1 | sed -n 2p  | grep -c "None"`

			# If total AG SDDQ device count is non-zero, block firmware downgrade
			if [ $totalSddqAgDevs -gt 0 -o $totalsddqAgPorts -eq 0 ]; then
				return $STS_ERR
			fi
		fi
	fi

	return $STS_OK
}

#
# Block downgrade from FOS8.2.1 on TOM2 and Chewbacca 
#
check_Tom_Chew_Plat()
{

        $ECHO check_Tom_Chew_Plat 
	# check if the current release permits downgrade to V81X_TEST_ONLY_RELEASE
	# if yes then bypass this check to block downgrade from FOS8.2.1 on TOM2 and Chewbacca
	downgrade_upgrade_from_v81x_test_only_supported=`grep -c DOWNGRADE_UPGRADE_FROM_V81X_TEST_ONLY_SUPPORTED $PREINST`

	case ${SWBD##SWBD} in
        '118' | '170')
			if [ $downgrade_upgrade_from_v81x_test_only_supported -eq 0 ]; then
				return $STS_ERR
			fi
			# This firmware supports downgrade to v81x_test_only_release
			# Now check if the target release is  v81x_test_only_release
			v81x_test_only_release=`grep -c V81X_TEST_ONLY_RELEASE /tmp/preinst`
			if [ $v81x_test_only_release -eq 0 ]; then
				return $STS_ERR		# Target is not v81x_test_only_release. Return Error
			fi
    	        ;;
        *)
                ;;
        esac
        return $STS_OK

}

#
# HCL is not supported for downgrade due to difference in DP U-boot versions between 8.2.1 and prior versions
# No Firmware version checks are performed here, the version check is done from the caller
#
additionalreboot(){
	
	if [ ${SWBD##SWBD} -eq 148 ]; then
		echo "WARNING: $ADDITIONAL_REBOOT_SKYB"
		add_warn_status "$ADDITIONAL_REBOOT_SKYB"
	elif [ ${SWBD##SWBD} -eq 165 -o ${SWBD##SWBD} -eq 166 ]; then
		check_harpoon_blade
		if [ $? -eq 1 ]; then
			echo "WARNING: $ADDITIONAL_REBOOT_HRPN"
			add_warn_status "$ADDITIONAL_REBOOT_HRPN"
		fi
	fi
}

check_821_asc_support(){

		certs=`/bin/ls /etc/fabos/certs/asc/*.pem 2> /dev/null`

		if [ ! -z "$certs" ]; then
			return $STS_ERR
		else
			return $STS_OK
		fi
}

lldp_repopulate_default_sys_desc(){
# LLDP is supported on Allegiance, Venator, Skybolt and AWing only
	case ${SWBD##SWBD} in
	'148' | '165' | '166' | '178')
		lldp_sys_desc_exists=`CONFIGSHOW | grep "lldp.global.sysdescr" | wc -l`
		if [ $lldp_sys_desc_exists -eq 0 ]; then
			/fabos/bin/lldp --config -sysdesc Brocade_Switch
			/fabos/cliexec/config remove lldp.global.sysdescr
			/fabos/cliexec/config update
		fi
	esac
}

lag_name_char_check(){
	input_str=$1
	obj_type=$2
	rc=-1
	vlan_string="vlan"
	LAG_NAME=""

	IFS=,
	for i in $input_str; do
		unset IFS

		if [ "$obj_type" == "SBLAG" ]; then
			if [ "${i:18:4}" == "name" ]; then
				LAG_NAME=${i:23:4}
				if [ `echo $LAG_NAME | tr [:upper:] [:lower:]` =  `echo $vlan_string | tr [:upper:] [:lower:]` ]; then
					rc=1
				else
					rc=0
				fi

				if [ $rc -eq 1 ]; then
					return $rc
				fi
			fi

			# need to handle varying prefix string lengths (ID values >= 10)
			if [ "${i:19:4}" == "name" ]; then
				LAG_NAME=${i:24:4}
				if [ `echo $LAG_NAME | tr [:upper:] [:lower:]` =  `echo $vlan_string | tr [:upper:] [:lower:]` ]; then
					rc=1
				else
					rc=0
				fi

				if [ $rc -eq 1 ]; then
					return $rc
				fi
			fi
		fi
		IFS=,
	done
	unset IFS

	return $rc
}

lag_name_char_check_81_82(){
	LAG_TMP_FILE=/tmp/lagname.txt

	case ${SWBD##SWBD} in
	'148' | '165' | '166')

	correcthost_all_vfs /fabos/link_bin/configshow -pat extnCfg > $LAG_TMP_FILE
	ALL_ENTRIES=`cat $LAG_TMP_FILE`

	# Check LAG
	echo "$ALL_ENTRIES" | grep SBLAG | while read line; do
		lag_name_char_check "$line" "SBLAG"
	done

	esac

	local RETURN_CODE=$?

	rm -f ${LAG_TMP_FILE}

	if [ $RETURN_CODE -eq 1 ]; then
		return $STS_ERR
	else
		return $STS_OK
	fi
}

check_ethif_hd_config(){
	slot_based=`/fabos/bin/slotshow | grep "Not supported on this platform"`

	#
	# ethif command was promoted to cli only from v8.0.1
	# prior to that it was a utility in /fabos/sbin for root access only
	# hence need to set proper path for seamless access in prior versions
	#
	if [ -f /fabos/cliexec/ethif ]; then
		ethifcmd=/fabos/cliexec/ethif;
	else
		if [ -f /fabos/sbin/ethif ]; then
			ethifcmd=/fabos/sbin/ethif;
		else
			ethifcmd=/fabos/standby_sbin/ethif;
		fi;
	fi;
	
	if [ "$slot_based" == "" ]; then
		if [ $VF_ENABLED -eq $STS_OK ]; then
			RSH_CMD="/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 CURRENT_AD=0"
		else
			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

		mycpeth0=`$ethifcmd --show eth0 | grep "Link mode:" | grep -cE "half duplex|HD"`
		mycpeth3=`$ethifcmd --show eth3 | grep "Link mode:" | grep -cE "half duplex|HD"`
		othcpeth0=`$RSH_CMD 2>/dev/null $ethifcmd --show eth0 | grep "Link mode:" | grep -cE "half duplex|HD"`
		othcpeth3=`$RSH_CMD 2>/dev/null $ethifcmd --show eth1 | grep "Link mode:" | grep -cE "half duplex|HD"`

		if [ "$mycpeth0" -gt 0 -o "$mycpeth3" -gt 0 -o "$othcpeth0" -gt 0 -o "$othcpeth3" -gt 0 ]; then
			return $STS_ERR
		fi
	else
		ethzero=`$ethifcmd --show eth0 | grep "Link mode:" | grep -cE "half duplex|HD"`
		if [ $ethzero -gt 0 ]; then
			return $STS_ERR
		fi
	fi
	return $STS_OK
}

check_for_ipsec_feature()
{
	SPMD_FILE=/var/run/spmd.pid
	PS=/bin/ps
	WC=/usr/bin/wc
	CHKCONFIG=`/usr/bin/which chkconfig`
	GREP=`/usr/bin/which grep`
	#check if spmd file is present
	if [[ $(ls $SPMD_FILE 2>/dev/null) ]]; then
		content=`cat $SPMD_FILE 2>null`
		spmd_pid=`$PS -A | $GREP $content 2>/dev/null | $GREP spmd 2>/dev/null  | $WC -c`
		#if spmd_pid is not empty then IPSec is enabled
		if [[ $spmd_pid -gt 0 ]]; then
			# If current cp is stanby then warn user and continue with firmwarae upgrade
			if [ $HA_ROLE == "STANDBY" ]; then
				echo "$IPSEC_DISABLE_WARN_STANDBY"
				add_warn_status "$BNA_IPSEC_DISABLE_WARN_STANDBY"
				return $STS_OK
			fi
			# Block firmware upgrade as ipsec is enabled
			return $STS_ERR
		fi
	fi
	# For internal testing purpose. if upgrading from 9.0 to 9.0 and chkconfig ipsec is
	# "on" then disabale it and continue with upgrade.
	if [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -eq 2 -a $CUR_PATCH -eq 2 ]; then
		ipsec_state=`$CHKCONFIG | grep ipsec | sed -n 's/.*\(on\|off\).*/\1/p'`
		if [ "$ipsec_state" != "off" ] ; then
			$CHKCONFIG ipsec off >/dev/null 2>&1
		fi
	fi
	return $STS_OK
}

####################################################################
#                                                                  #
#     ALL FEATURE CHECK FUNCTIONS SHOULD BE ABOVE THIS SECTION     #
#                                                                  #
####################################################################



#
# This function checks 8.1 features to block upgrade to 8.2.
#
check_81_to_82_features()
{
	$ECHO check_81_to_82_features

	# Disallow certain POD combination licenses.	
	TEST check_combo_bit_license_migration_check "$ERROR_24_BIT_LICENSES" "$BNA_ERROR_24_BIT_LICENSES"
	# Check if any IPSEC policies of key length less than 32
	TEST check_extn_fips_pvt_key_len_in_context "$EXTN_FIPS_UNSUPP_PSK_LEN" "$BNA_EXTN_FIPS_UNSUPP_PSK_LEN"
	# Disallow NOS (IM5) mode Ex-Ports.
	TEST check_ex_ports_IM5

	TEST check_fips_mode_support "$FIPSSIMULATE_NOTSUPPORTED" "$BNA_FIPSSIMULATE_NOTSUPPORTED"
	# Provide warning when Gen5 PS is in Gen6 chassis
	check_for_powersupply_mismatch_in_gen6_chassis  
	# check for passwordless login support and block fwdl
	TEST check_passwordless_login "$UNSUPPORTED_PASSWORDLESS_LOGIN_MSG" "$BNA_UNSUPPORTED_PASSWORDLESS_LOGIN_MSG"
	# Check for LAG name should not start with vlan
	TEST lag_name_char_check_81_82 "$LACP_LAG_NAME_VLAN_PRESENT" "$BNA_LACP_LAG_NAME_VLAN_PRESENT"
#	TEST check_max_ipfilter_policy "$MAX_IPFILTER_POLICY" "$BNA_MAX_IPFILTER_POLICY"

#	TEST check_ipfilter_policy_name "$IPFILTER_POLICY_NAME" "$BNA_IPFILTER_POLICY_NAME"
	return $STS_OK
}

#
# This function checks 8.0 features to block upgrade to 8.1.
#
check_80_to_81_features()
{

	$ECHO check_80_to_81_features
	
	TEST check_C2_core_blades "$UNSUPPORTEDPLATFORMMSG" "$BNA_UNSUPPORTEDPLATFORMMSG"
	TEST check_fips_snmp_pass_len "$UNSUPPORTED_SNMP_FIPS_PASS_LEN" "$BNA_UNSUPPORTED_SNMP_FIPS_PASS_LEN"
	TEST check_fips_snmp_md5 "$UNSUPPORTED_SNMP_FIPS_AUTH_MD5" "$BNA_UNSUPPORTED_SNMP_FIPS_AUTH_MD5"
	TEST check_admin_domain_enabled "$ADMIN_DOMAIN_SUPPORT_RESTRICTION" "$BNA_ADMIN_DOMAIN_SUPPORT_RESTRICTION"
	TEST check_24_bit_license_migration_check "$ERROR_24_BIT_LICENSES" "$BNA_ERROR_24_BIT_LICENSES"
	TEST check_combo_bit_license_migration_check "$ERROR_24_BIT_LICENSES" "$BNA_ERROR_24_BIT_LICENSES"
	TEST check_multiple_secure_syslog_configuration "$UNSUPPORTED_MULTIPLE_SECURE_SYSLOG" "$BNA_UNSUPPORTED_MULTIPLE_SECURE_SYSLOG"
	
	TEST check_max_supported_zoneDB_size
	
	return $STS_OK
}


#
# This is upgrade to 8.2 case
#
handle_to_82()
{
	$ECHO handle_to_82

	# We don't allow 7.4 and previous to upgrade to this version
	#
	if [ $CUR_MAJOR -eq 7 -a $CUR_MINOR -le 4 -o $CUR_MAJOR -lt 7 ]; then
			add_err_status "$UNSUPPORTED_UP_VERMSG" "$BNA_UNSUPPORTED_UP_VERMSG"
			return $STS_ERR
		fi

	if ( [ $CUR_MAJOR -lt 8 ] || [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -le 2 -a $CUR_PATCH -lt 2 ] ); then
		if [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 2 -a $TO_PATCH -eq 2 ]; then
			TEST check_for_ipsec_feature "$IPSEC_DISABLE_WARN" "$BNA_IPSEC_DISABLE_WARN"
		fi
	fi
	#
	# Allow only disruptive upgrade from 8.0
	#
	if [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -eq 0 ]; then
        handle_disruptive_single_mode_fwdl
        local retvar=$?
        if [ $retvar != $STS_OK ]; then
            return $STS_ERR;
        fi
	fi

    # Block upgrade on tyr from version 8.2.0 to 8.2.0a
    if [ ${SWBD##SWBD} == '173' ]; then
        if [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -eq 2 -a $CUR_PATCH -eq 0 ]; then
            TEST_FIDS check_fcoe_config_exist "$FCOE_CONFIG_PRESENT_ON_TYR" "$BNA_FCOE_CONFIG_PRESENT_ON_TYR"
			TEST_FIDS check_ethport_configured "$ETHERNET_CONFIG_PRESENT_ON_TYR" "$BNA_ETHERNET_CONFIG_PRESENT_ON_TYR"
        fi
    fi

	#
	# Block upgrade to 8.2 if any thalassa blade is present
	#
	TEST check_Thalassa8G_blade "$THALASSA8G_BLADE_IS_PRESENT" "$BNA_THALASSA8G_BLADE_IS_PRESENT"

	TEST check_ethif_hd_config "$HALF_DUPLEX_CONFIG_PRESENT" "$BNA_HALF_DUPLEX_CONFIG_PRESENT"
	#
	#Block downgrade to 8.2.0 on Tom2 and Chewbacca
	#
	if [ $TO_PATCH -lt 1 ]; then
		TEST check_821_maps_rule_length_check "$MAPS_RULE_WITH_INVALID_THRESHOLD_LEN" "$BNA_MAPS_RULE_WITH_INVALID_THRESHOLD_LEN"
		TEST check_Tom_Chew_Plat "$TOM_CHEW_UNSUPPORTED_DOWNGRADE" "$BNA_TOM_CHEW_UNSUPPORTED_DOWNGRADE"
		# Need to call below MAPS function if we are downgrading to 8.2.0 from any higher releases
		# This case will be hit if we are downgrading from v8.2.1 or higher release to v8.2.0
		check_821_warning_maps_features
		#FOS-803677 : Requesting user to reboot after downgrade
		additionalreboot
	fi

	curVersion=${CUR_MAJOR}${CUR_MINOR}${CUR_PATCH}
	toVersion=${TO_MAJOR}${TO_MINOR}${TO_PATCH}
	isUpgrade=`echo "$toVersion" "$curVersion" | awk '{print $1 - $2}'`
	if [ $isUpgrade -gt 0 -a $TO_PATCH -ge 1 ] && [ "${CUR_MAJOR}.${CUR_MINOR}" == "8.2" ]
	then
		# Need to call below MAPS function if we are upgrading from 8.2.0 to 8.2.1 only
		# This Case will be hit if we are upgrading from v8.2.0 to v8.2.1 and above
		check_maps_821_features_ip_extn_flow_wrapper
	fi
    #
    # Block upgrade to 8.2 if any 8.2.3 specific features are enabled.
    #

    if [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 2 -a $TO_PATCH -lt 3 ]; then
        check_823_features
    fi

	#
	# Block upgrade to 8.2 if any 8.1 specific features are enabled.
	#
	check_81_to_82_features
	
	#
	# Block upgrade to 8.2 if any 8.0 specific features are enabled.
	#
	check_80_to_81_features

	#
	# Block upgrade to 8.2 if password length of snmpuser is less than minimum
	# length
	check_snmp_password_len

	#
	# Block upgrade to 8.2 on WEDGE if Compression is enabled on ports
	# 44-47.
	# Defect 659872:
	# Ensure the validation for compression enable happens on port 44-47
	# on when the firmware version is less than 8.2 (eg:- 8.1, 8.0.2 etc)
	if [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -lt 2 ]; then
		TEST check_compression_on_wedge64_in_all_contexts "$COMPRESSION_FWDL_RESTRICTION_WEDGE" "$BNA_COMPRESSION_FWDL_RESTRICTION_WEDGE"
	fi
	#
	# Block downgrade from 8.2.1 if any port on base switch is configured
	# as ISL R_RDY
	TEST check_isl_rrdy_bs_in_all_contexts "$ISL_RRDY_BS" "$BNA_ISL_RRDY_BS"

	#
	# Block downgrade from 8.2.1 if FMC configuration is enabled on the system.
	#
	TEST check_is_fmc_enabled "$FMC_NOTSUPPORTED" "$BNA_FMC_NOTSUPPORTED"
	
  	#
  	# Block downgrade from 8.2.1 if any AG-connected device is SDDQ quarantined
  	#
	TEST check_ns_ag_sddq_devices
	
	#
  	# Block downgrade from 8.2.1 if any device in AG is SDDQ quarantined
  	#
	TEST check_ag_sddq_devices "$DEVICE_QUARANTINED_ON_AG" "$BNA_DEVICE_QUARANTINED_ON_AG"

	#
  	# Block downgrade to 8.2.0 or below if any online port has
	# Encryption enabled
  	#
	TEST check_encryption_block_downgrade "$ENCRYPTION_DISRUPTIVE_FWDL" "$BNA_ENCRYPTION_DISRUPTIVE_FWDL"

	#
	# Block downgrade from 8.2.1 if any port on skywalker blade is configured
	# with encryption and trunking support.
	if [ $TO_PATCH -lt 1 ]; then
		TEST check_encryption_trunking_on_skywalker "$ENCRYPTION_TRUNKING_ON_SKYWALKER" "$BNA_ENCRYPTION_TRUNKING_ON_SKYWALKER"
	fi

	# 44-47.
	# Defect 659872:
	# Ensure the validation for compression enable happens on port 44-47
	# on when the firmware version is less than 8.2 (eg:- 8.1, 8.0.2 etc)
	if [ $CUR_MAJOR -eq 8 -a $CUR_MINOR -lt 2 ]; then
		TEST check_compression_on_wedge64_in_all_contexts "$COMPRESSION_FWDL_RESTRICTION_WEDGE" "$BNA_COMPRESSION_FWDL_RESTRICTION_WEDGE"
	fi

	#Warning message for Chewbacca and Tom2 platforms
	if [ $TO_PATCH -eq 1 ]; then
		if [ $CUR_MINOR -lt 2 ] || [ $CUR_PATCH -lt 1 ]; then
			 case ${SWBD##SWBD} in
        			'118' | '170')
				echo -e "$FDW_82_CHEWBACCA_TOM2_WARN\n"
				add_warn_status "$FDW_82_CHEWBACCA_TOM2_WARN"
			esac
		fi
	fi

	#
	# Block upgrade to >=8.2.1 if extension certs filenames have
	# unsupported chars.
	# 
	if [ $TO_MAJOR -gt 9 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -gt 3 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 2 -a $TO_PATCH -ge 1 ]; then
		TEST check_extn_certs_name "$EXTN_CERT_UNSUPP_FILENAME" "$BNA_EXTN_CERT_UNSUPP_FILENAME"
	fi

	# Defect FOS-805039. If downgrading to 8.2.0, reset lldp system
	# description to 8.2.0's default string if there was no user
	# configured lldp system description
	if [ $TO_MAJOR -eq 8 -a $TO_MINOR -eq 2 -a $TO_PATCH -eq 0 ]; then
		lldp_repopulate_default_sys_desc
	fi

	return $RET_CODE
}


#
# This function checks 7.4 features to block upgrade to 8.1.
#
check_74_to_80_features()
{
	$ECHO check_74_to_80_features

	check_74_BD_to_maps_migration_warn
	TEST check_icl_port_configuration "$UNSUPPORTED_ICL_PORT_CONFIGURATION" "$BNA_UNSUPPORTED_ICL_PORT_CONFIGURATION"
   	TEST check_C2_core_blades "$UNSUPPORTEDPLATFORMMSG" "$BNA_UNSUPPORTEDPLATFORMMSG"
	TEST check_europa_blade "$EUROPA_BLADE_IS_PRESENT" "$BNA_EUROPA_BLADE_IS_PRESENT"
   	TEST check_lance_blade  "$LANCE_BLADE_IS_PRESENT" "$BNA_LANCE_BLADE_IS_PRESENT"
	TEST check_admin_domain_enabled "$ADMIN_DOMAIN_SUPPORT_RESTRICTION" "$BNA_ADMIN_DOMAIN_SUPPORT_RESTRICTION"

	#Check Ethernet Switch Service 
	TEST check_ethsw_enabled "$ETHSW_SERVICE_ENABLED" "$BNA_ETHSW_SERVICE_ENABLED"

	return $STS_OK
}


#
# This function check all 8.2 features for downgrade to 8.1 or 8.0
#
check_821_features()
{

	#
	# Block downgrade on Tom2 and Chewbacca
	#
	TEST check_Tom_Chew_Plat "$TOM_CHEW_UNSUPPORTED_DOWNGRADE" "$BNA_TOM_CHEW_UNSUPPORTED_DOWNGRADE"

	#
	# Block downgrade from 8.2.1 if any port on skywalker blade is configured
	# with encryption support
	TEST check_encryption_trunking_on_skywalker "$ENCRYPTION_TRUNKING_ON_SKYWALKER" "$BNA_ENCRYPTION_TRUNKING_ON_SKYWALKER"

	TEST check_821_maps_rule_length_check "$MAPS_RULE_WITH_INVALID_THRESHOLD_LEN" "$BNA_MAPS_RULE_WITH_INVALID_THRESHOLD_LEN"
	#
	# warn the user if any of the 8.2.1 features are present
	check_821_warning_maps_features

	#FOS-803677 : Requesting user to reboot after downgrade
	additionalreboot

	# Block downgrade if asc certificate is imported
	TEST check_821_asc_support  "$ASC_CA_CERTIFICATE_SUPPORT"

	return $STS_OK
}

#
# This function check all 8.2 features for downgrade to 8.1 or 8.0
#
check_82_features()
{
	$ECHO check_82_features
	check_maps_820_features_to_give_warning $MAPS_82_WARN
    # Block downgrade from v8.2 to v8.1 is an Anakin blade is online
	TEST check_anakin_blade "$ANAKIN_BLADE_IS_PRESENT" 
	TEST check_dynamic_lags_exist "$DYNAMIC_LAG_PRESENT";
	TEST_FIDS check_lacp_global_config_exist "$LACP_GLOBAL_CONFIG_PRESENT" "$BNA_LACP_GLOBAL_CONFIG_PRESENT"
	TEST_FIDS check_lldp_config_exist "$LLDP_CONFIG_PRESENT" "$BNA_LLDP_CONFIG_PRESENT"
	TEST_FIDS check_fcoe_config_exist "$FCOE_CONFIG_PRESENT" "$BNA_FCOE_CONFIG_PRESENT"
	TEST check_snmp_groupname_ro "$SNMP_GROUPNAME_RO" "$BNA_SNMP_GROUPNAME_RO"
	TEST check_encryption_on_wedge64_fwdl "$ENCRYPTION_ON_WEDGE64" "$BNA_ENCRYPTION_ON_WEDGE64"
	TEST check_vtap_active "$VTAP_ENABLED" "$BNA_VTAP_ENABLED"
	TEST check_analyzer_vtap_active "$ANALYZER_VTAP_ENABLED" "$BNA_ANALYZER_VTAP_ENABLED"
	if [ $VF_ENABLED -ne $STS_OK ]; then
		TEST check_8bit_route "$CHECK_8BIT_ROUTE_STATUS_VF"
	else
		TEST check_8bit_route "$CHECK_8BIT_ROUTE_STATUS_NON_VF"
	fi
	TEST check_TI_MAX_ZONENAME_exists "$ZONE_TI_MAXZONENAME" "$BNA_ZONE_TI_MAXZONENAME"
	TEST check_fips_inside_support "$FIPSINSIDE_NOTSUPPORTED" "$BNA_FIPSINSIDE_NOTSUPPORTED"

	#
	# Block downgrade from 8.2.1 if any port on base switch is configured
	# as ISL R_RDY
	TEST check_isl_rrdy_bs_in_all_contexts "$ISL_RRDY_BS" "$BNA_ISL_RRDY_BS"

	#
	# Block downgrade from 8.2.1 if FMC configuration is enabled on the system.
	#
	TEST check_is_fmc_enabled "$FMC_NOTSUPPORTED" "$BNA_FMC_NOTSUPPORTED"

	#
	# Block downgrade from 8.2.1 if any AG-connected device is SDDQ quarantined
	#
	TEST check_ns_ag_sddq_devices
	
	#
  	# Block downgrade from 8.2.1 if any device in AG is SDDQ quarantined
  	#
	TEST check_ag_sddq_devices "$DEVICE_QUARANTINED_ON_AG" "$BNA_DEVICE_QUARANTINED_ON_AG"

	return $STS_OK

}

#
# This function check all 8.1 features for downgrade to 8.0 or 7.4
#
check_81_features()
{
	$ECHO check_81_features
	TEST check_ls_support "$LS_NUMBER_NOTSUPPORTED" "$BNA_LS_NUMBER_NOTSUPPORTED"
	TEST check_snmp_user_encrypted_passwd "$SNMP_USER_PASSWD_ENCRYPTION" "$BNA_SNMP_USER_PASSWD_ENCRYPTION"

	TEST check_810_blocking_maps_features
	check_maps_810_features_to_give_warning $MAPS_810_WARN
	TEST check_max_lsan_dev_count "$SCAL_DOWN_TO_5K_LSAN_10K_DEV" "$SCAL_DOWN_TO_5K_LSAN_10K_DEV"
	TEST check_ag_flow_mirror "$FM_ENABLED_ON_AG"
	TEST check_Mirror_configuration "$DISABLE_MIRROR_CONFIGURATION" 
	TEST check_remote_fosexec "$REMOTE_FOSEXEC_CONFIGURED"
	TEST_FIDS check_Alias_Peer_Zone_feature "$DISABLE_ALIAS_PEER_ZONE" "$BNA_DISABLE_ALIAS_PEER_ZONE"
	TEST_FIDS check_Enhanced_Zone_Object_Name_Feature "$DISABLE_ENH_ZNOBJ_NAME" "$BNA_DISABLE_ENH_ZNOBJ_NAME"
	TEST check_DiscFrameType "$DISC_FRM_TYPE_CONFIGURED" "$BNA_DISC_FRM_TYPE_CONFIGURED"
	TEST check_manual_gwyipv6_configuration "$MANUAL_IPV6_GWY_CONFIGURED" "$BNA_MANUAL_IPV6_GWY_CONFIGURED"
	TEST check_rekey_configuration "$UNSUPPORTED_SSH_REKEY_MSG"
	TEST_FIDS check_ficon_logical_switch_presence "$FICON_LS_NOT_SUPPORTED" "$BNA_FICON_LS_NOT_SUPPORTED"
	TEST check_ldapuser_rolemap_root "$UNSUPPORTED_LDAP_ROLEMAP_ROOT"
	TEST check_app_server_disruptive_downgrade_required "$GEN6_APP_SERVER_RESTRICTION" "$BNA_GEN6_APP_SERVER_RESTRICTION"
	TEST check_multiple_FMS_enabled "$MULTI_FMS_MODE_ENABLED"
	TEST check_24_bit_license_migration_check "$ERROR_24_BIT_LICENSES" "$BNA_ERROR_24_BIT_LICENSES"
	TEST check_vtap_QOS_comp_mode "$VTAP_QOS_MODE_ENABLED"
	TEST check_vtap_ECB_coexist_mode "$VTAP_ECB_COEXIST_ENABLED"
	TEST check_compression_fwdl "$COMPRESSION_FWDL_RESTRICTION" "$BNA_COMPRESSION_FWDL_RESTRICTION"
	TEST check_encryption_fwdl "$ENCRYPTION_FWDL_RESTRICTION" "$BNA_ENCRYPTION_FWDL_RESTRICTION"
	TEST check_multiple_switchRole_mapping "$UNSUPPORTED_LDAP_MULTIPLE_ROLEMAP"
	TEST check_imported_template "$IMPORTED_TEMPLATE_NOTSUPPORTED" "$BNA_IMPORTED_TEMPLATE_NOTSUPPORTED"
	TEST check_801_pw_hash "$UNSUPPORTED_PWHASH_MSG"
	TEST check_801_user_access_time_check "$UNSUPPORTED_USERCONFIG_MSG" "$BNA_UNSUPPORTED_USERCONFIG_MSG"
	add_obsolete_accounts
	TEST check_combo_bit_license_migration_check "$ERROR_24_BIT_LICENSES" "$BNA_ERROR_24_BIT_LICENSES"
	TEST check_32G_brkout_qsfp

	return $STS_OK
	
}


#
# This function checks 8.0 features for downgrade from 8.1 to 7.4
#
check_80_features()
{
	$ECHO check_80_features

	check_maps_80_features_to_give_warning $MAPS_80_WARN
	TEST check_801_pw_hash "$UNSUPPORTED_PWHASH_MSG"
	TEST check_801_user_access_time_check "$UNSUPPORTED_USERCONFIG_MSG" "$BNA_UNSUPPORTED_USERCONFIG_MSG"
	TEST check_801_dynamic_portname "$DEFAULT_FORMAT_NOT_SET" "$BNA_DEFAULT_FORMAT_NOT_SET"
	TEST check_801_ve_port_flows_in_all_contexts "$UNSUPPORTED_VE_PORT_FLOWS_MSG" "$BNA_UNSUPPORTED_VE_PORT_FLOWS_MSG"
	TEST check_dhcpv6_enable "$UNSUPPORTED_DHCPV6_OPTION" "$BNA_UNSUPPORTED_DHCPV6_OPTION"

	if [ $TO_MAJOR -lt 8 ]; then
		add_obsolete_accounts
	fi

	return $STS_OK
}

#
# This function is to check for any AMP9(amoos2.2) maps and collection
# configurations and if any, then warn before upgrade to AMP10(ampos3.0)
# since they are NOT valid in amp10. If user continue with upgrade, then
# the configurations are cleaned up in postinstall script.
#
check_AMP22_collection_cfg_n_warn()
{
	warn=$1
	bna_warn=$2

	# warn and return here. If user upgraded, postinstall will take care of cleanup
	if [ $CUR_MAJOR -eq 2 -a $CUR_MINOR -le 2 ]; then
		echo "$warn"
		add_warn_status "$bna_warn"
	fi

	return $STS_OK
}

#
# Function to check amp30 collection config and block the downgrade if any
#
check_amp30_collection_configs()
{
	$ECHO check_amp30_collection_configs

	# check for mgmt server ip
	for app_ip in `CONFIGSHOW -all | /bin/grep "http.BoundApplication" | cut -d":" -f 2`;
	do
		if [ -n "$app_ip" ]; then
			return $STS_ERR
		fi
	done

	return $STS_OK
}
check_amp30_maps_rules()
{
 	$ECHO check_amp30_maps_rules
	ruleName=`CONFIGSHOW_ADV -a | grep -i "maps.rule\." | cut  -d '/' -f1|cut -d '(' -f2`
	for i in $ruleName;
	do
		if [ "$i" == "RD_STATUS_TIME" ] || [ "$i" == "WR_STATUS_TIME" ] || [ "$i" == "RD_1stDATA_TIME" ] || [ "$i" == "WR_1stXFER_RD" ] || [ "$i" == "FABRIC_LATENCY" ] || [ "$i" == "RD_DATA_RATE" ] || [ "$i" == "WR_DATA_RATE" ] || [ "$i" == "RD_PENDING_IO" ] || [ "$i" == "WR_PENDING_IO" ]; then
			return $STS_ERR
		fi
	done
	return $STS_OK
}
check_amp30_mp_config()
{
	mp_count=`/fabos/link_bin/esmcmd dbg0 solo mp -resource | grep Total | awk {'print $3'}`

	if [ $mp_count -gt $AMP_22_CONFIG_SIZE ]
	then
		return $STS_ERR
	fi

	return $STS_OK

}

#
# This function checks AMP 2.2 features to block upgrade to AMP 3.0.
#
check_AMP22_to_AMP30_features()
{
        $ECHO check_AMP22_to_AMP30_features

		check_AMP22_collection_cfg_n_warn "$AMP30_COL_UPG_WARN"  "$BNA_AMP30_COL_UPG_WARN"

        return $STS_OK
}

#
# This function checks AMP 3.0 features to block downgrade to AMP 2.2.
#
check_AMP30_to_AMP22_features()
{
        $ECHO check_AMP30_to_AMP22_features

        TEST check_au_license_installed "$AUL_MISS_BLK_DWLD" "$BNA_AUL_MISS_BLK_DWLD"

		TEST check_amp30_collection_configs "$AMP30_CFG_ERR_MSG" "$BNA_AMP30_CFG_ERR_MSG"

		TEST check_amp30_maps_rules "$AMP30_MD_RULE_ERR_MSG" "$BNA_AMP30_MD_RULE_ERR_MSG"

		TEST check_amp30_mp_config "$AMP30_MP_ERR_MSG"
        return $STS_OK
}

#
# This function writes default values in the below config keys in all the np config files
# np.flow.feature.stats.ctrl.v3.itReserve:
# np.flow.feature.stats.ctrl.v3.itlReserve:
# np.flow.feature.stats.ctrl.v3.maxItlPerIt:
#
populate_default_it_itl_values()
{
$ECHO populate_default_it_itl_values

check_au_license_installed
if [ "$?" -eq "$STS_OK" ]; then
DEFAULT_IT="np.flow.feature.stats.ctrl.v3.itReserve.0:6000"
DEFAULT_ITL="np.flow.feature.stats.ctrl.v3.itlReserve.0:6000"
DEFAULT_ITL_PER_IT="np.flow.feature.stats.ctrl.v3.maxItlPerIt.0:255"
else
DEFAULT_IT="np.flow.feature.stats.ctrl.v3.itReserve.0:500"
DEFAULT_ITL="np.flow.feature.stats.ctrl.v3.itlReserve.0:0"
DEFAULT_ITL_PER_IT="np.flow.feature.stats.ctrl.v3.maxItlPerIt.0:255"
fi
CURR_IT="np.flow.feature.stats.ctrl.v3.itReserve.0:.*"
CURR_ITL="np.flow.feature.stats.ctrl.v3.itlReserve.0:.*"
CURR_ITL_PER_IT="np.flow.feature.stats.ctrl.v3.maxItlPerIt.0:.*"

for sw in 0
do
CONF_FILE="/mnt/etc/fabos/np."$sw".conf"
TEMP_CONF_FILE1="/mnt/etc/fabos/np.tmp1.conf"
TEMP_CONF_FILE2="/mnt/etc/fabos/np.tmp2.conf"
if [ -f $CONF_FILE ];then
#to replace default itReserve value
/bin/sed "s/$CURR_IT/$DEFAULT_IT/" $CONF_FILE > $TEMP_CONF_FILE1
#to delete existing itlReserve config key
/bin/sed "s/$CURR_ITL//g" $TEMP_CONF_FILE1 > $TEMP_CONF_FILE2
#to delete existing itlPerIT config key
/bin/sed "s/$CURR_ITL_PER_IT//g" $TEMP_CONF_FILE2 > $TEMP_CONF_FILE1

#delete all empty lines if present
/bin/sed '/^$/d' $TEMP_CONF_FILE1 > $TEMP_CONF_FILE2
#to append default itlReserve after itReserve
#keep the below two lines without indendation
#since sed takes tab space into consideration while appending new config key
/bin/sed '/'$DEFAULT_IT'/a\
'$DEFAULT_ITL'' $TEMP_CONF_FILE2 > $TEMP_CONF_FILE1
#to append default ITL_PER_IT after itlReserve
#keep the below two lines without indendation
#since sed takes tab space into consideration while appending new config key
/bin/sed '/'$DEFAULT_ITL'/a\
'$DEFAULT_ITL_PER_IT'' $TEMP_CONF_FILE1 > $TEMP_CONF_FILE2
/bin/mv $TEMP_CONF_FILE2 $CONF_FILE
/bin/rm $TEMP_CONF_FILE1
fi
done

return $STS_OK
}


#
# This is downgrade from AMP 3.0 to AMP 2.2 case
#
handle_AMP30_to_AMP22()
{

        $ECHO handle_AMP30_to_AMP22

        #
        # Allow downgrade to AMP 2.2 only on Solo
        #
        if [ ${SWBD##SWBD} != '171' ]; then
                add_err_status "$UNSUPPORTEDPLATFORMMSG" "$BNA_UNSUPPORTEDPLATFORMMSG"
                return $STS_ERR
        fi

        #
        # Block downgrade if any 8.2.1 (AMP 3.0) specific features are enabled
        # for downgrade to 8.2.0 (AMP 2.2).
        #
        check_821_features

        #
        # Block downgrade if any 3.0 specific features are enabled.
        #
        check_AMP30_to_AMP22_features

	#
	# Populate default values to the below config keys in case of downgrade from 3.0.0 to 2.2.0
	# np.flow.feature.stats.ctrl.v3.itReserve:
	# np.flow.feature.stats.ctrl.v3.itlReserve:
	# np.flow.feature.stats.ctrl.v3.maxItlPerIt:
	#
	populate_default_it_itl_values

        return $RET_CODE
}


#
# This is upgrade from AMP 2.2 to AMP 3.0 case
#
handle_AMP22_to_AMP30()
{
        $ECHO handle_AMP22_to_AMP30

        if [ "${SWBD##SWBD}" != "171" ]; then
                add_err_status "$UNSUPPORTEDPLATFORMMSG" "$BNA_UNSUPPORTEDPLATFORMMSG"
                return $STS_ERR
        fi

        if [ $CUR_MAJOR -eq 2 -a $CUR_MINOR -le 1 ]; then
                add_err_status "$UNSUPPORTED_AMP_UP_VERMSG" "$BNA_UNSUPPORTED_AMP_UP_VERMSG"
                return $STS_ERR
        fi

        #
        # Block upgrade to 8.2 if any 8.1 specific features are enabled.
        #
        check_81_to_82_features

        #
        # Block upgrade if any 2.2 specific features are enabled.
        #
        check_AMP22_to_AMP30_features

        return $RET_CODE
}


#
# This is downgrade from 8.2 to 8.1 case
#
handle_82_to_81()
{
	$ECHO handle_82_to_81

	#
	# Block downgrade if any 8.2.1 specific features are enabled.
	#
	check_821_features

	#
	# Block downgrade if any 8.2 specific features are enabled.
	#
	check_82_features

	check_823_features

	# remove CA cert store directory
	rm -rf /var/fabos/certs/extn/ca 2>/dev/null
	rm -rf /mnt/var/fabos/certs/extn/ca 2>/dev/null


    # Block downgrade from 8.1.x to 8.1.0 if vTap_ECB co-exist mode is enabled.
	TEST check_vtap_ECB_coexist_mode "$VTAP_ECB_COEXIST_ENABLED"

	#
  	# Block downgrade to 8.2.0 or below if any port has Encryption enabled
  	#
	TEST check_encryption_block_downgrade "$ENCRYPTION_DISRUPTIVE_FWDL" "$BNA_ENCRYPTION_DISRUPTIVE_FWDL"

	

	return $RET_CODE
}


#
# This is downgrade from 8.2 to 8.0 case
#
handle_82_to_80()
{

	$ECHO handle_82_to_80
	
	#
	# Allow only disruptive upgrade to 8.0
	#
	handle_disruptive_single_mode_fwdl
	local retvar=$?
	if [ $retvar != $STS_OK ]; then
		return $STS_ERR;
	fi
    #
    # Block downgrade if any 8.2.3 specific features are enabled.
    #
	check_823_features
	#
	# Block downgrade if any 8.2.1 specific features are enabled.
	#
	check_821_features

	#
	# Block downgrade if any 8.2 specific features are enabled.
	#
	check_82_features

	#
	# Block downgrade if any 8.1 specific features are enabled.
	#
	check_81_features

	# remove CA cert store directory
	rm -rf /var/fabos/certs/extn/ca 2>/dev/null
	rm -rf /mnt/var/fabos/certs/extn/ca 2>/dev/null

	return $RET_CODE
}


#
# This is downgrade to 7.4 case
#
handle_to_74_lower()
{

	$ECHO handle_to_74_lower

	# Block downgrade to version 2.0.0 on AMP
	if [ ${SWBD##SWBD} == '171' ]; then
		if [ $TO_MAJOR -eq 2 -a $TO_MINOR -le 1 -a $TO_PATCH -eq 0 ]; then
			add_err_status "$UNSUPPORTED_FWDL_AMP" "$BNA_UNSUPPORTED_FWDL_AMP"			
			return $STS_ERR
		fi
	fi
	add_err_status "$UNSUPPORTED_DL_VERMSG" "$BNA_UNSUPPORTED_DL_VERMSG"
	return ${STS_ERR}
}



handle_snmp() {
	declare -a snmpv1_community=("Secret\ C0de" "OrigEquipMfr" "private" "public" "common" "FibreChannel")

	CONFIGSHOW -all > /tmp/snmp_config_v1.txt

	v1_enable=`/bin/cat /tmp/snmp_config_v1.txt | /bin/grep "snmp.v1Enable" | /bin/grep -v "snmp.v1Enable.default"| /usr/bin/cut -d ':' -f2`
	if [ "$v1_enable" == 0 ] ; then
		rm -rf /tmp/snmp_config_v1.txt 2>/dev/null
		return
	fi
	for (( i = 0; i < 6; i++ ))
	do
		name=`/bin/cat /tmp/snmp_config_v1.txt | /bin/grep "snmp.agtParty.$i.authPrivSecret" |/usr/bin/cut -d ':' -f2| head -n 1`
		for v1 in "${snmpv1_community[@]}"
		do
			if [ "$v1" == "$name" ] ; then
				echo $FDW_SNMPV1_WARNING
				add_warn_status "$FDW_SNMPV1_WARNING"
				rm -rf /tmp/snmp_config_v1.txt 2>/dev/null
				return 1
			fi
		done
	done
	rm -rf /tmp/snmp_config_v1.txt 2>/dev/null
}


# check for default password 
#
check_default_password()
{
	#
	# Block upgrade to 9.0 if admin and/or user have not changed default passwords
	#
	/fabos/bin/chkpasswd admin
	ret=$?
	if [ $ret != $STS_OK ]; then
		return $ret
	fi

	/fabos/bin/chkpasswd user
	ret=$?
	return $ret
}

#
# main()
#
#$ECHO Requested version is ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH} Type is $TYPE

if [ -z $TYPE ]; then
	TEST check_hcl_switchstate "$SWITCH_FAULTY_MSG" "$BNA_SWITCH_FAULTY_MSG"
	RET=$?
	if [ $RET != $STS_OK ]; then
		exit $RET_CODE
	fi

	#
	# clean up to free up disk space on /mnt before firmwaredownload
	#
	$ECHO removing tracedump.dmp
	rm -f /mnt/var/tracedump.dmp
	# Overwrite raslog.int and raslog.ext file with FWDL version
	# This ensures that we do not overwrite the raslog files of new standby with
	# new active CP files.
	RASLOG_INT_FILE=/mnt/etc/raslog.int
	RASLOG_EXT_FILE=/mnt/etc/raslog.ext

	echo "RASLOG" > $RASLOG_INT_FILE
	echo "RASLOG" > $RASLOG_EXT_FILE
fi



# if skybolt is in Analytics mode prevent firmwaredownload

check_if_Analytics
RET=$?

if [ $RET != $STS_OK ]; then
        exit $RET;
fi

#
# Handle a specific firmware version
#
case "${TO_MAJOR}.${TO_MINOR}" in
	'8.2')
		handle_to_82
		RET=$?
	;;
	'8.1')
		handle_82_to_81
		RET=$?
	;;
	'8.0')
		handle_82_to_80
		RET=$?
	;;
	'3.0')
		handle_AMP22_to_AMP30
		RET=$?
	;;
	'2.2')
		handle_AMP30_to_AMP22
		RET=$?
	;;
	*)
		handle_to_74_lower
		  RET=$?
    ;;
esac

if [ $RET != $STS_OK ]; then
	exit $RET;
fi

check_default_password > /dev/null 2>&1
RET=$?
if [ $RET != $STS_OK ]; then
	add_err_status "$CHANGE_DEFAULT_PWD" "$BNA_CHANGE_DEFAULT_PWD"
	exit $RET;
fi

# Extension FWDL Prep
#
# Prior to performing any feature checks, attempt to prep extension
# platforms for FWDL to the target version. This will perform any
# necessary migrations that can occur automatically without impact
# to the user. If any user intervention is required for activated
# features, the feature checks in the 'handle_to_XX' routines will
# catch them.
prep_extn_features

# Perform main extension feature check. We process the version within the
# command, so we check it globally here instead of in the handle_to_xx
# routines.
TEST check_extn_features "$XFCIP_FEATURE_RESTRICTION" "$BNA_XFCIP_FEATURE_RESTRICTION"
RET=$?

#
# Preinstall check fails
#
if [ $RET != $STS_OK ]; then
	prep_extn_features_abort
	exit $RET;
fi

#
# Preinstall checks passed - check for HCL readiness
#
# This will not actually prevent any firmware operation from continuing
# but will just print any warnings to the user and fall through to the
# normal FWDL prompt asking if they wish to proceed.
check_extn_hcl

handle_snmp

MNT_POSTINST="/mnt/sbin/postinst" # This is the new firmware being downloaded
POSTINST="/sbin/postinst"         # This is the current / running firmware

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
}

#***** LDAPS support
ldaps_protocol_handling


#
# remove /mnt/var/images so it will not run into
# "Unable to uninstall old packages" issue when attempting to remove bpimage-swbd36
# If not doing firmwaredownload -s then remove it from the standbyCP as well
#
rm -rf /mnt/var/images/* 2>/dev/null 
is_fwdl_arg "s"
if [ $? -ne 0 ]; then
	pizzabox=$(/fabos/link_bin/hashow | grep -c "Not supported on this platform") 2>/dev/null
	if [ $pizzabox -eq 0 ]; then
		#
		# Remove these only on chassis switches
		#
		/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CURRENT_AD=0 "/bin/rm -rf /mnt/var/images/*" 2>/dev/null
	fi
fi

if [ $TO_MAJOR -lt 8 ] || [ $TO_MAJOR -eq 8 -a $TO_MINOR -lt 1 ]; then
	cmd=`cat /etc/fabos/fabos.chassis.conf | grep "system.tcptimestamp"`
	if [ "$cmd" != "" ]; then
		mode="${cmd: -1}"
		if [ $mode == "0" ]; then
			echo "Warning.... !!!" \
				"The TCP timestamp is disabled now. After firmware downgrade, TCP timestamp will be enabled."
		fi	
	fi
fi

#
# Firmwaredownload check passes, return
#
if [ -z $TYPE ]; then
	$ECHO return code is $RET
	exit $RET
fi

#
# For firmwarerestore, we will perform the firmwarerestore here.
# it will not return to the caller. That is to workaround a
# 2.4.19 kernel and 2.3.6 glibc mismatch issue. (79299). Read
# more comments in fwdl_undo() in the fwdl.c file.
#
baddev=`bootenv BadRootDev 2>/dev/null`
upgrade=`bootenv Upgrade 2>/dev/null`
softupgrade=`bootenv SoftUpgrade 2>/dev/null`
osloader=`bootenv OSLoader 2>/dev/null`

dev_p=`bootenv OSRootPartition 2>/dev/null | cut -d ';' -f 1`
dev_s=`bootenv OSRootPartition 2>/dev/null | cut -d ';' -f 2`
kern_p=`bootenv OSLoader 2>/dev/null | cut -d ';' -f 1`
kern_s=`bootenv OSLoader 2>/dev/null | cut -d ';' -f 2`

mount_p=`cat /proc/mounts | grep " / " | grep -v rootfs |sed 's? .*??g;s?^.*dev/??g'`
mount_s=`cat /proc/mounts |grep "/mnt" | sed 's? .*??g;s?^.*dev/??g'`

if [ -n "$baddev" ]; then
	add_err_status "$FWDL_RUNNING_MSG" "$BNA_FWDL_RUNNING_MSG"
    	exit 1;
fi

if [ -n "$softupgrade" ]; then
	add_err_status "$FWDL_RUNNING_MSG" "$BNA_FWDL_RUNNING_MSG"
	exit 1;
fi

if [ -z "$upgrade" ]; then
	add_err_status "$FWRESTORE_DISALLOWED_MSG" "$BNA_FWRESTORE_DISALLOWED_MSG"
	exit 1;
fi

if [ "$upgrade" == /dev/$mount_s ]; then
	add_err_status "$FWRESTORE_DISALLOWED_MSG" "$BNA_FWRESTORE_DISALLOWED_MSG"
    	exit 1;
fi


#
# prevent firmwarerestore from 6.3 to 6.1.2_cee because
# the we can not restore the PROM image in this case
#
case ${SWBD##SWBD} in
	'76')
		if [ ! -s /mnt/boot/bootrom.bin ]; then
			add_err_status "$FWRESTORE_VER_DISALLOWED_MSG" "$BNA_FWRESTORE_VER_DISALLOWED_MSG"
			exit 1;
		fi
	esac


# The following steps restores the old RBAC dynamic db
if [ $CUR_MAJOR -eq 7 -a $TO_MAJOR -eq 7 ]; then
	/usr/sbin/chroot /mnt /fabos/libexec/userdb_convert $CUR_MAJOR.$CUR_MINOR $TO_MAJOR.$TO_MINOR > /dev/null 2>&1
	cp /mnt/etc/fabos/rbac/dynamic /etc/fabos/rbac/dynamic
fi

#Push Manufacturing key to SP
if [ -f '/fabos/libexec/spmPublicKeyUpdate' ] ; then
	/fabos/libexec/spmPublicKeyUpdate
fi

# Resotoring only the 8548 and 440epx prom images
echo "Restoring the PROM image ..."
if [ -s /mnt/boot/bootrom.bin ]; then
    /usr/sbin/chroot /mnt /sbin/prominst
fi

bootenv OSRootPartition "$dev_s;$dev_p"

if [ -n "$osloader" ] ; then
	bootenv OSLoader "$kern_s;$kern_p"
fi
bootenv Upgrade "/dev/$dev_s"
bootenv SoftUpgrade "commit"

if [ $CUR_MAJOR -eq 6 -a $CUR_MINOR -le 2 ]; then
echo "The system is rebooting now!! After reboot, firmwarecommit" \
    "will be started and the partitions will be restored to the" \
    "original firmware."
/fabos/cliexec/reboot -s -r FirmwareDownload -f
fi

exit 0
