#!/bin/sh 
#
#    Copyright (c) 2004-2016 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    Description:
#
#   The preinstall script will be run as the first step after the
#	firmwaredownload command is entered and before the downloading
#	starts. It will only be invoked on the MM where the command
#	is entered. So in a chassis, if dual-MM firmwaredownload command
#	is entered (without -s) from the active MM, the script will only
#	be invoked on the active MM. If single firmwaredownload command
#	(with -s) is entered on both MMs, the script will be run on both
#	of them.
#
#	Firmwaredownload will choose the newer preinstall script to run
#	by comparing the major, minor, and patch numbers of the existing
#	and to-be-downloaded firmware. If the existing firmware is newer,
#	it will run the preinstall script that is already on the switch.
#	If the existing firmware is older or the same as the firmware
#	being downloaded, it will run the preinstall script that is part
#	of the to-be-downloaded firmware.
#
#	The preinstall script checks for the features that are currently
#	enabled on the switch and that are not supported by the new
#	firmware. If there are any, it will warn the user and return a
#	non-zero status. Firmwaredownload will be subsequently aborted.
#

PATH=/bin:/usr/bin:/sbin:/usr/sbin
#
# Passed-in version numbers
#
TO_MAJOR=$1
TO_MINOR=$2
TO_PATCH=$3

DEBUG=0
if [ $DEBUG = 1 ]; then
	ECHO='echo -e'
else
	ECHO=:
fi

#
# Reads command line args passed to firmwaredownload
# and checks if the required argument is specified
# ex: has_fwdl_option f
#     has_fwdl_option p: #option with value
#
has_fwdl_option()
{
	[ $# -gt 0 -a -e /proc/$PPID/cmdline ] || return 0 
	return `tr '\0' ' ' < /proc/$PPID/cmdline | grep -c " -[^- ]*${1}"`
}

#
# From version
#
FABOS_VERSION=`rpm -q fabos`
if [ $? -eq 0 ];then
	FROM_VER=`echo $FABOS_VERSION | cut -f 2 -d '-'`
else
	#use getfabosver since fabos rpm doesnt get installed in lc
	FROM_VER=`/sbin/getfabosver /fabos/share/version base`
fi

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

#
# Return codes
#
STS_OK=0
STS_ERR=255
RET=${STS_OK}

if [ $FROM_MAJOR -eq 2 ];then
	TYPE=$4
elif [ $FROM_MAJOR -ge 3 ]; then
	TO_RID=$4
	TYPE=$5
fi
if [ $FROM_MAJOR -gt 3 ]; then
	TO_REVISION=$6
fi

FROM_REVISION=`cat /etc/version.conf | grep IntNum | awk '{print $2}'`


#
# Get DCM cluster Mode, RC Values: 0=> FC, 1=> MC, 2=> SA 
#
get_dcm_mode()
{
	local vcsconfvalue="0000"
	local clusterconfvalue="0"
	local dcm_mode=0

	if [ -f '/etc/fabos/Dcmd/vcs.conf' ]
	then
		vcsconfvalue=`cat /etc/fabos/Dcmd/vcs.conf`
	fi

	if [ -f '/etc/fabos/Dcmd/cluster.conf' ]
	then
		clusterconfvalue=`cat /etc/fabos/Dcmd/cluster.conf`
	fi

	if [[( $vcsconfvalue != "0000" && $clusterconfvalue == "0" )]]; then
		dcm_mode=0
	elif [[( $vcsconfvalue != "0000" && $clusterconfvalue == "1" )]]; then
		dcm_mode=1
	elif [[( $vcsconfvalue == "0000" && $clusterconfvalue == "0" )]]; then
		dcm_mode=2
	else
		dcm_mode=-1
	fi

    echo "$dcm_mode"
}

VCS_MODE=$(get_dcm_mode)
if [ $VCS_MODE -eq 1 ];then
	TARGET_DB="running-config"
else
	TARGET_DB="startup-db"
fi


FIRMWARE_RESTORE=0

if [ -z $TYPE ]; then
	#NOS2.x Firmware-Download calls Preinst without 4th arg
	FIRMWARE_RESTORE=0
elif [ $TYPE == "0" ]; then
	#NOS3.x Firmware-Download calls Preinst with "0" as 5th arg
	FIRMWARE_RESTORE=0
elif [ $TYPE == "restore" ] || [ $TYPE == "1" ] ; then
	#NOS2.x Firmware-Restore calls Preinst with "restore" as 4th arg
	#NOS3.x Firmware-Restore calls Preinst with "1" as 5th arg
	FIRMWARE_RESTORE=1
fi

# This should match the file name in src/lib/upgrade/upgrade.c
STATUS_FILE=/tmp/fwdl_err.txt
echo > $STATUS_FILE

# This file contains the ISSU status
PREINST_STS_FILE=/tmp/preinst.sts
rm -f $PREINST_STS_FILE

###################################################
### The messages are for firmwarerestore.   ###
###################################################

FWDL_RUNNING_MSG="Firmware restore failed because another firmware download is running. Please wait till it completes first."

FWRESTORE_NOT_NEEDED_MSG="No need to run 'firmware restore' because firmware has already been committed, or there is no firmwaredownload performed."


###################################################
###################################################
####                                           ####
####                                           ####
####     PRESINSTALL MESSAGES SECTION          ####
####    ------------------------------         ####
####                                           ####
###################################################
###################################################

CP_INCOMPATIBILE_FW_MSG="Firmware download is not allowed because the new firmware is not compatible with this hardware."
LC_INCOMPATIBLE_FW_CFG_MSG="Firmware is not compatible with one or more line card types [6x100G, 27x40G, 48x10GT, 6X100G-POD], please cleanup config for the unsupported line card(s) (using 'no linecard') and retry."
LC_INCOMPATIBLE_FW_PWR_MSG="Firmware is not compatible with one or more line card types [6x100G, 27x40G, 48x10GT, 6X100G-POD] in the chassis, please remove the unsupported line card(s) and retry."
LC_INCOMPATIBLE_FW_PWR1_MSG="Firmware is not compatible with line card type [6X100G-POD] in the chassis, please remove the unsupported line card(s) and retry."
UNSUPPORTED_DOWNGRADE_TO_20_MSG="Downgrade from NOS 7.0 to NOS 2.0 is not supported. Please downgrade to NOS 5.0 before downgrading to NOS 2.0."
UNSUPPORTED_DOWNGRADE_TO_21_MSG="Downgrade from NOS 7.0 to NOS 2.1 is not supported. Please downgrade to NOS 5.0 before downgrading to NOS 2.1."
UNSUPPORTED_DOWNGRADE_TO_30_MSG="Downgrade from NOS 7.0 to NOS 3.0 is not supported. Please downgrade to NOS 5.0 before downgrading to NOS 3.0."
UNSUPPORTED_DOWNGRADE_TO_40_MSG="Downgrade from NOS 7.0 to NOS 4.0 or below is not supported. Please downgrade to NOS 5.0 before downloading to NOS 4.0 or lower."
UNSUPPORTED_DOWNGRADE_TO_41_MSG="Downgrade from NOS 7.0 to NOS 4.1 or below is not supported. Please downgrade to NOS 5.0.x before downloading to NOS 4.1 or lower."
UNSUPPORTED_UPGRADE_TO_41_MSG="Upgrade from the current firmware to NOS 4.1 is not supported. Please upgrade to NOS 4.0 before upgrading to 4.1."
UNSUPPORTED_UPGRADE_TO_50_KUMATAKA_MSG="Firmware download from the current firmware to NOS 5.0 is not supported."
UNSUPPORTED_UPGRADE_TO_70_MSG="Upgrade from the current firmware to NOS 7.0 is not supported. Please upgrade to NOS 5.0.x before upgrading to 7.0."
UNSUPPORTED_UPGRADE_TO_71_MSG="Upgrade from the current firmware to NOS 7.1 is not supported. Please upgrade to NOS 5.0.x before upgrading to 7.1."
UNSUPPORTED_UPGRADE_TO_72_MSG="Upgrade from the current firmware to NOS 7.2 is not supported. Please upgrade to NOS 5.0.x before upgrading to 7.2."
UNSUPPORTED_UPGRADE_TO_73_MSG="Upgrade from the current firmware to NOS 7.3 is not supported. Please upgrade to NOS 5.0.x before upgrading to 7.3."
UNSUPPORTED_UPGRADE_TO_74_MSG="Upgrade from the current firmware to NOS 7.4 is not supported. Please upgrade to NOS 5.0.x before upgrading to 7.4."
DISRUPTIVE_UPGRADE_TO_41_MSG="ISSU is not supported from current firmware to NOS 4.1.0. Please specify the manual option in the command-line for upgrading."
UNSUPPORTED_ISSU_MSG="ISSU is not supported to the target firmware version. Please specify coldboot option in the command-line for download."
LC_HAS_ONE_GOS_MSG="LC(s) has only one GOS partition! Please fix it by running p2install in the LC(s)."
AG_DOWNGRADE_ERR="Firmware cannot be downgraded from current version to lower versions if Access Gateway mode is enabled! Please disable Access Gateway mode to perform downgrade!"
FCOE_ENODES_DOWNGRADE_ERR="Firmware cannot be downgraded to 4.0 if fcoe enodes configuration is in local mode. Please apply 'enodes-config global' under fcoe fabric-map to allow downgrade"
UNSUPPORTED_DOWNGRADE_ADMINLOCK_ENABLE_CFG_MSG="Downgrade is not allowed because password-attributes admin-lockout is enabled on this switch but it is not supported in the firmware being downloaded. Please remove the configuration using \"no password-attributes admin-lockout\" and try again."
UNSUPPORTED_DOWNGRADE_DEFAULTUSERACC_DISABLE_CFG_MSG="Downgrade is not allowed because the default user account admin or user or both are disabled on this switch but it is not supported in the firmware being downloaded. Please remove the configuration using \"username admin enable true\" or \"username user enable true\" and try again."
UNSUPPORTED_DOWNGRADE_NTP_KEY_CFG_MSG="Downgrade is not allowed because ntp authentication-key is configured that is not supported in the firmware being downloaded. Please remove the ntp authentication-key configuration and disassociate key from server in case any server is configured with authentication-key."
UNSUPPORTED_DOWNGRADE_NTP_ENC_7="Downgrade is not allowed because NTP server authentication-key is configured with encryption level 7. Please change the key with encryption level to 0 and try again."
TACACS_LEN_ERROR_MSG="Downgrade to pre-4.0.1 NOS versions is not allowed. Please configure TACACS+ keys of length in the range(8-40) characters using 'tacacs-server host <server> key <secret>','copy running-config startup-config', before performing a downgrade."
UNSUPPORTED_DOWNGRADE_LOCAL_SNMP_ENGINEID_MSG="Downgrade is not allowed because local snmp EngineID is configured on this switch but it is not supported in the firmware being downloaded. Please remove the configuration using \" no snmp-server engineID local\" and try again."
UNSUPPORTED_DOWNGRADE_HTTP_DISABLE_MSG="Downgrade is not allowed because HTTP server is disabled on this switch and it is not supported in the firmware being downloaded. Please enable the http configuration using \" no http server shutdown\" and try again, 'copy running-config startup-config', before performing a downgrade"
UNSUPPORTED_DOWNGRADE_HTTPS_DISABLE_MSG="Downgrade is not allowed because HTTPS server is disabled on this switch and it is not supported in the firmware being downloaded. Please enable the HTTPS configuration using \" no https server shutdown\" and try again, 'copy running-config startup-config', before performing a downgrade"
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_FIPS_AUTH_MD5="Upgrade is not allowed since one or more snmpv3 users have unsupported auth protocol MD5 configured in FIPS mode."
DEFCONFIG_DOWNLOAD_TO_41_MSG="Download from the current firmware to NOS 4.1 is not supported. Please specify the default-config option in the command-line for this download."
DEFCONFIG_DOWNLOAD_TO_30_MSG="Download from the current firmware to NOS 3.0.x is not supported. Please specify the default-config option in the command-line for this download."
UNSUPPORTED_ISSU_TO_41_MSG="Firmware downgrade from the current version to NOS 4.0.x does not support ISSU. If any new feature of the current release is enabled, please use the default-config option for the downgrade, otherwise please use coldboot option for downgrade."

UNSUPPORTED_DOWNGRADE_ISL_BRK_MODE_ENABLED="Downgrade is not allowed because the ISLs are enabled on the breakout 40Gig ports. Please remove the configuration using \" no fabric isl enable \" and try again."
UNSUPPORTED_DOWNGRADE_BLACKBIRD_TO_MCMODE="VCS logical-chassis mode is not supported in the firmware being downloaded."
UNSUPPORTED_DOWNGRADE_BLACKBIRD_CURRENT_MCMODE="Downgrade is not allowed because VCS logical-chassis mode is enabled. Please remove the configuration using \"no vcs logical-chassis enable \" and try again."
UNSUPPORTED_DOWNGRADE_RAD_TAC_ENC_7="Downgrade is not allowed because Radius/Tacacs server key is configured with encryption level 7. Please change the key with encryption level to 0 and try again."
VIRTUAL_MAC_DOWNGRADE_ERR="Firmware cannot be downgraded to 4.0 if virtual-mac configuration is present at this rbridge. Please remove 'virtual-mac' configurations from all the vrrp-extended-group on this rbridge."
NON_UNIFORM_IVID_ISSU_MSG="Current vlan resource allocation scheme is not supported on downgrade firmware."

INCOMPATIBLE_OVERLAY_GATEWAY_CONFIG_ERR_SUFFIX="from ${FROM_MAJOR}.${FROM_MINOR}.${FROM_PATCH_STR} to ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH} is not allowed when overlay-gateway is configured. Please remove the configuration using \"no overlay-gateway\" command and try again."
INCOMPATIBLE_NSX_CONTROLLER_CONFIG_ERR_SUFFIX="from ${FROM_MAJOR}.${FROM_MINOR}.${FROM_PATCH_STR} to ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH} is not allowed when nsx-controller is configured. Please remove the configuration using \"no nsx-controller\" command and try again."
UNSUPPORTED_CFG_MSG="Firmware download to the target firmware version cannot preserve the configuration. Please specify the default-config option in the command-line for download."
RED_PROFILE_BEHAVIOUR_CHANGE_FROM_EGRESS_TO_INGRESS="QoS RED profile behaviour is changed from egress to ingress from nos5.0.0 onwards and the system has QoS RED profile applied on atleast one of the interface. Please clean up the config and try again."
ACL_USED_IN_MULTIPLE_CLASS_MAPS="Multiple MQC class-maps contain the same access-list as the match criteria. Please fix the error and try again later."
UNSUPPORTED_DOWNGRADE_USERNAME="from ${FROM_MAJOR}.${FROM_MINOR}.${FROM_PATCH_STR} to ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH} is not allowed when leading underscore in username present. So please remove the username having leading underscore using \"no username <username string>\" and try again."
UNSUPPORTED_DOWNGRADE_TACACSSRCADDR="Downgrade is not allowed because tacacs source address(chassis-ip) is configured, but it is not supported in the firmware being downloaded. Please remove the configuration using \"no tacacs-server source-ip\" and try again."
UNSUPPORTED_DOWNGRADE_PASSWD_ATTRIB_LOCKOUTDUR="Downgrade is not allowed because lockout duration is configured, but it is not supported in the firmware being downloaded. Please remove the configuration using \"no password-attributes max-lockout-duration\" and try again."

UNSUPPORTED_DOWNGRADE_FLEXPORT="Downgrade is not allowed because some of the ports in the cluster are in Fibre-channel mode. Please remove them and try again or Please specify the default-config option in the command-line for download."
UNSUPPORTED_DOWNGRADE_FLEXPORT_ON_BOP="Downgrade is not allowed because some of the breakout ports in the cluster have flexport confuguration. Please remove them before proceeding.\n\nIf in FC mode, Please run \"copy running-config startup-config\" after removing flexport configuration."



UNSUPPORTED_DOWNGRADE_SSHSERVER_CIPHER_MGS="Downgrade is not allowed because ssh server cipher is configured, but it is not supported in the firmware being downloaded. Please remove the configuration using \" no ssh server cipher \" and try again."
UNSUPPORTED_DOWNGRADE_SSHCLIENT_CIPHER_MGS="Downgrade is not allowed because ssh client cipher is configured, but it is not supported in the firmware being downloaded. Please remove the configuration using \" no ssh client cipher \" and try again."
UNSUPPORTED_DOWNGRADE_SSHSERVER_MAC_MGS="Downgrade is not allowed because ssh server mac is configured, but it is not supported in the firmware being downloaded. Please remove the configuration using \" no ssh server mac \" and try again."
UNSUPPORTED_DOWNGRADE_SSHCLIENT_MAC_MGS="Downgrade is not allowed because ssh client mac is configured, but it is not supported in the firmware being downloaded. Please remove the configuration using \" no ssh client mac \" and try again."
UNSUPPORTED_DOWNGRADE_SSHSERVER_KEX_MGS="Downgrade is not allowed because the configured ssh server key-exchange is not supported in the firmware being downloaded. Please remove the configuration using \" no ssh server key-exchange\" or change the kex-exchange to \"ssh server key-exchange dh-group-14\" and try again."
UNSUPPORTED_DOWNGRADE_SSHSERVER_CIPHER_MGS="Downgrade is not allowed because the configured ssh server cipher is not supported in the firmware being downloaded. Please remove the configuration using \" no ssh server cipher\" or change the cipher to \"ssh server cipher non-cbc\" and try again."
UNSUPPORTED_DOWNGRADE_SSHCLIENT_CIPHER_MGS="Downgrade is not allowed because the configured ssh client cipher is not supported in the firmware being downloaded. Please remove the configuration using \" no ssh client cipher\" or change the cipher to \"ssh client cipher non-cbc\" and try again."
UNSUPPORTED_DOWNGRADE_SSHCLIENT_KEX_MSG="Downgrade is not allowed because the configured ssh client key-exchange is not supported in the firmware being downloaded. Please remove the configuration using \" no ssh client key-exchange\" or change the key-exchange to \"ssh client key-exchange dh-group-14\" and try again."
UNSUPPORTED_DOWNGRADE_SSHSERVER_VRF_MGS="Downgrade is not allowed because ssh server with user-defined vrf configuration is not supported in the firmware being downloaded. Please remove the configuration using \"no ssh server use-vrf <vrf-name>\" and try again."
UNSUPPORTED_DOWNGRADE_TELNETSERVER_VRF_MGS="Downgrade is not allowed because telnet server with user-defined vrf configuration is not supported in the firmware being downloaded. Please remove the configuration using \"no telnet server use-vrf <vrf-name>\" and try again."
UNSUPPORTED_DOWNGRADE_TELNETSERVER_DEF_VRF_DISABLE_MGS="Downgrade is not allowed because telnet server on default-vrf is enabled, but it should be in same state as mgmt-vrf, please disable telnet server on default-vrf using \"[no] telnet server use-vrf default-vrf [shutdown]\" and try again."
UNSUPPORTED_DOWNGRADE_SSHSERVER_DEF_VRF_DISABLE_MGS="Downgrade is not allowed because ssh server on default-vrf is enabled, but it should be in same state as mgmt-vrf, please disable ssh server on default-vrf using \"[no] ssh server use-vrf default-vrf [shutdown]\" and try again."
UNSUPPORTED_DOWNGRADE_TELNETSERVER_DEF_VRF_ENABLE_MGS="Downgrade is not allowed because telnet server on default-vrf is disabled, but it should be in same state as mgmt-vrf, please enable telnet server on default-vrf using \"[no] telnet server use-vrf default-vrf [shutdown]\" and try again."
UNSUPPORTED_DOWNGRADE_SSHSERVER_DEF_VRF_ENABLE_MGS="Downgrade is not allowed because ssh server on default-vrf is disabled, but it should be in same state as mgmt-vrf, please enable ssh server on default-vrf using \"[no] ssh server use-vrf default-vrf [shutdown]\" and try again."
UNSUPPORTED_DOWNGRADE_AAASERVER_VRF_MGS="Downgrade is not allowed because aaa server(radius/tacacs/ldap) with user-defined vrf or defaulr-vrf configuration is not supported in the firmware being downloaded. Please remove the configuration using \"no <radius/tacacs/ldap>-server use-vrf <vrf-name>\" and try again."

UNSUPPORTED_DOWNGRADE_SYSLOG_USER_DEFINED_VRF_MGS="Downgrade is not allowed because logging syslog-server with user-defined vrf configuration is not supported in the firmware being downloaded. Please remove the configuration using \"no logging syslog-server <IP> use-vrf <vrf-name>\" and try again."
UNSUPPORTED_DOWNGRADE_SYSLOG_DEFAULT_VRF_MGS="Downgrade is not allowed because logging syslog-server with default-vrf configuration is not supported in the firmware being downloaded. Please remove the configuration using \"no logging syslog-server <IP> use-vrf <vrf-name>\" and try again."

UNSUPPORTED_DOWNGRADE_ACCESSTIME_EXISTS_MGS="Downgrade is not allowed because user-defined users with \"access-time\" configuration is not supported in the firmware being downloaded. Please remove the configuration using \"no username <user name> and try again."

UNSUPPORTED_DOWNGRADE_ROOT_ACCESS="Downgrade is not allowed because root access is configured, but it is not supported in the firmware being downloaded. Please remove the configuration using \" no root access \" and try again."

UNSUPPORTED_DOWNGRADE_NTPSRCADDR="Downgrade is not allowed because ntp source address(chassis-ip) is configured, but it is not supported in the firmware being downloaded. Please remove the configuration using \"no ntp source-ip\" and try again."
UNSUPPORTED_UPGRADE_INCOMPATIBLE_SFLOW_CONFIG="The sflow config under the overlay-gateway has vlan range overlapping with the statistics/span config.Please remove the overlapping vlan range from the overlay-gateway sflow config to proceed with the upgrade."

UNSUPPORTED_DOWNGRADE_CRYPTO_MSG="Downgrade is not allowed because crypto configuration is present, but it is not supported in the firmware being downloaded. Please remove the configuration using \"no keypair; no crypto key <label>; no trustpoint ca <trustpoint_name>;\" and try again."

UNSUPPORTED_DOWNGRADE_TIMEZONE="Downgrade is not allowed because configured timezone is not supported in the firmware being downloaded. Please remove the configuration using \"no clock timezone\" and try again."

UNSUPPORTED_OPERATION_NODE_DEFAULT_MSG="Node is configured with default config boot, firmware download will not preserve the configuration if node is in default state. Please disable it so that configuration may be preserved."

UNSUPPORTED_DOWNGRADE_NTPSHA1KEY="Downgrade is not allowed because SHA-1 key type configuration is present in ntp authentication-key, but it is not supported in the firmware being downloaded. Please remove the configuration using \"no ntp authentication-key <key-id>\" and try again."

UNSUPPORTED_DOWNGRADE_DAI_MSG="Downgrade is not allowed since target firmware does not support dynamic ARP inspection. Please remove this configuration from TCAM hardware profile.\nIf in FC mode, Please run \"copy running-config startup-config\" after updating the profile.\n"

UNSUPPORTED_DOWNGRADE_OPENFLOW_MSG="Downgrade is not allowed since target firmware does not support openflow. Please disable openflow using \"hardware-profile route-table\" command.\nIf in FC mode, Please run \"copy running-config startup-config\" after disabling openflow.\n"

UNSUPPORTED_DOWNGRADE_ECMP_MSG="Downgrade is not allowed since, only 8 ECMP maximum-paths are supported by target firmware. Please update this configuration using \"hardware-profile route-table\" command.\nIf in FC mode, Please run \"copy running-config startup-config\" after updating the configuration.\n"

UNSUPPORTED_DOWNGRADE_KAP_MSG="Downgrade is not allowed since target firmware does not support custom KAP profile. Please set this profile to default using \"hardware-profile kap default\" command.\nIf in FC mode, Please run \"copy running-config startup-config\" after updating KAP profile.\n"

UNSUPPORTED_DOWNGRADE_TCAM_IPV4ACL_MSG="Downgrade is not allowed since target firmware does not support ipv4-acl TCAM profile. Please set TCAM profile to other applicable type using \"hardware-profile tcam \" command. Please make sure that rules per ACL is within 2K in the configuration. \n If in FC mode, Please run \"copy running-config startup-config\" after updating TCAM profile.\n"

UNSUPPORTED_DOWNGRADE_RBAC_COMMANDS="Downgrade is not allowed because RBAC rules are configured for any one of following commands, \" interface Ve, interface Port-channel, interface Loopback, interface FibreChannel, interface FortyGigabitEthernet, interface HundredGigabitEthernet, interface Management <rbridge-id/port>\". It is not supported in the firmware being downloaded. Please check the configuration using \"show running-config rule\" and remove the configuration using \" no rule <rule index>\" and try again."
UNSUPPORTTED_RIGEL_MOR_10X_DOWNGRADE="Downgrade is not allowed, since the target firmware does not support the switch storage device."
UNSUPPORTED_DOWNGRADE_NON_DEFAULT_DUP_WWN_LOGIN_POLICY="Downgrade is not allowed because non-default duplicate WWN login policy is configured.Please change the configuration to default using \"(config-rbridge-id-XX)# fabric login-policy -> duplicateWWN -> precedence old-login\""
UNSUPPORTED_COBRA2_13="Downgrade is not allowed as the target firmware does not support Cobra2 revision 1.3 blade"

UNSUPPORTED_DOWNGRADE_SSH_REKEY_CFG_MGS="Downgrade is not allowed because ssh server is configured with rekey-intervals. It is not supported in the firmware being downloaded. Please remove the configuration using \"(config-rbridge-id-XX)# no ssh server rekey-interval\" and try again."

UNSUPPORTED_DOWNGRADE_SSH_REKEYVOLUME_CFG_MGS="Downgrade is not allowed because ssh server is configured with rekey-volume. It is not supported in the firmware being downloaded. Please remove the configuration using \"(config-rbridge-id-XX)# no ssh server rekey-volume\" and try again."

UNSUPPORTED_DOWNGRADE_SSH_MAXAUTHTRIES_CFG_MGS="Downgrade is not allowed because ssh server is configured with max-auth-tries. It is not supported in the firmware being downloaded. Please remove the configuration using \"(config-rbridge-id-XX)# no ssh server max-auth-tries\" and try again."

UNSUPPORTED_DOWNGRADE_SSH_MAXIDLETIMEOUT_CFG_MGS="Downgrade is not allowed because ssh server is configured with max-idle-timeout. It is not supported in the firmware being downloaded. Please remove the configuration using \"(config-rbridge-id-XX)# no ssh server max-idle-timeout\" and try again."

UNSUPPORTED_DOWNGRADE_SSH_MAXLOGINTIMEOUT_CFG_MGS="Downgrade is not allowed because ssh server is configured with max-login-timeout. It is not supported in the firmware being downloaded. Please remove the configuration using \"(config-rbridge-id-XX)# no ssh server max-login-timeout-tries\" and try again."

UNSUPPORTED_DOWNGRADE_SSH_SERVER_ALGO_HOSTKEY_CFG="Downgrade is not allowed because ssh server is configured with x509v3-ssh-rsa hostkey algorithm. It is not supported in the firmware being downloaded. Please remove the configuration using \"(config-rbridge-id-XX)# no ssh server algorithm hostkey\" and try again."

UNSUPPORTED_DOWNGRADE_SSH_SERVER_ALGO_PUBLICKEY_CFG="Downgrade is not allowed because ssh server is configured with x509v3-ssh-rsa publickey algorithm. It is not supported in the firmware being downloaded. Please remove the configuration using \"(config-rbridge-id-XX)# no ssh server algorithm publickey\" and try again."

UNSUPPORTED_DOWNGRADE_SSH_SERVER_CERT_PROFILE_TP_SIGN_CFG="Downgrade is not allowed because ssh server is configured with server certificate profile. It is not supported in the firmware being downloaded. Please remove the configuration using \"(ssh-server-cert-profile-server)# no trustpoint sign\" and try again."

UNSUPPORTED_DOWNGRADE_SSH_SERVER_CERT_PROFILE_TP_VERIFY_CFG="Downgrade is not allowed because ssh server is configured with user certificate profile. It is not supported in the firmware being downloaded. Please remove the configuration using \"(ssh-server-cert-profile-user)# no trustpoint verify\" and try again."

UNSUPPORTED_DOWNGRADE_SCPUSER_CFG="Downgrade is not allowed because \"scpuser\" configuration is present in username configuration. It is not supported in the firmware being downloaded.Please remove the configuration using \"[no] username scpuser\" and try again."

UNSUPPORTED_FWDL_SCPUSER_CFG="Firmware download is not allowed from ${FROM_MAJOR}.${FROM_MINOR}.${FROM_PATCH_STR} to ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH} with \"scpuser\" configuration in username. Please remove the \"scpuser\" using \"[no] username scpuser\" and try again."

UNSUPPORTED_UPGRADE_INCOMPATIBLE_OSPFV3_AREARANGE_CONFIG="Same area range configured under multiple area. Please remove the duplicate area range from the Ospfv3 area config to proceed with the upgrade.\n"

UNSUPPORTED_DOWNGRADE_NTPSERVER_VRF_MSG="Downgrade is not allowed because ntp server with vrf configuration is not supported in the firmware being downloaded. Please remove the configuration using \"no ntp-server <server name> use-vrf <vrf-name>\" and try again."

UNSUPPORTED_DOWNGRADE_PORTGROUP_ON_RIGEL_MOR="Downgrade is not allowed on this platform because 100G port speed is not supported by the target firmware. Please change the port speed to 40G by using the \"port-group\" command and try again."

UNSUPPORTED_DOWNGRADE_BREAKOUT_ON_RIGEL_MOR="Downgrade is not allowed on this platform because breakout mode is not supported by the target firmware. Please disable the breakout mode using the \"no sfp breakout\" command and try again."

UNSUPPORTED_NUM_RIGEL_700_VRRP_SESS="NOS7.0.0 supports only 255 VRRP/E sessions IPv4 and IPv6 included. Current configuration consists of more then 255 sessions. Please configure 255 sessions, at max, to proceed."

UNSUPPORTED_IPV6_SITELOCAL_ADDR_BGP="Downgrade is not allowed because the BGP configuration contains IPv6 sitlocal (fec::XXX) addresses. Please remove them using \"no network <site-local-addr>\" or \"no aggregate-address <site-local-addr> \ and try firmware download again."

UNSUPPORTED_BGP_EVPN="Downgrade is not allowed because BGP-EVPN is not supported. Please remove BGP-EVPN related commands under router bgp, evpn-instance and vrf mode."

UNSUPPORTED_BGP_DYN_NBR="Downgrade is not allowed because BGP Dynamic Neighbor is not supported. Please remove BGP dynamic neighbor related commands under router bgp."
UNSUPPORTED_BGP_GSHUT_NBR="Downgrade is not allowed because BGP graceful-shhutdown is not supported. please remove BGP graceful shutdown related commands under router bgp."

UNSUPPORTED_BGP_VRF_FILTER="Downgrade is not allowed because BGP-VRF-FILTER is not supported.\nPlease remove \"import/export map <name> evpn\" commands under vrf mode & \"ip extcommunity-list <100-500> {reg-expr}\" commands in global config mode.\nIf extcommunity-list is configured, also remove the correspoding match statements under route-map configuration."

UNSUPPORTED_DOWNGRADE_SSH_MAXSESSIONS_CFG_MGS="Downgrade is not allowed because ssh server is configured with max-session. It is not supported in the firmware being downloaded. Please remove the configuration using \"(config-rbridge-id-XX)# no ssh server max-session\" and try again."

UNSUPPORTED_DOWNGRADE_RBAC_SHOWCMDS="Downgrade is not allowed because RBAC rules are configured for any one of following commands, \" show rbridge-local-running-config, show rbridge-running-config, show running-config, show startup-config, show startup-db\". It is not supported in the firmware being downloaded. Please check the configuration using \"show running-config rule\" and remove the configuration using \" no rule <rule index>\" and try again."

UNSUPPORTED_DOWNGRADE_RBAC_SHOWCMDS1="Downgrade is not allowed because RBAC rules are configured for any one of following commands, \" show legacy-running-config, show local-running-config, show cli\". It is not supported in the firmware being downloaded. Please check the configuration using \"show running-config rule\" and remove the configuration using \" no rule <rule index>\" and try again."

UNSUPPORTED_FWDL_SHA256_CIPHER_CFG="Firmware download is not allowed with \"sha256\" configuration in cipherset. It is not supported in the firmware being downloaded. Please remove the configuration using \"[no] cipherset ssh sha256 \" and try again."

UNSUPPORTED_NUM_700_SAG_SESS="NOS7.0.0 supports only 32 Static Anycast IP addresses per interface for IPv4 and IPv6 included. Current configuration consists of more than 32 IP addresses per interface . Please configure 32 Static Anycast ip addresses per interface at max to proceed."
UNSUPPORTED_UPGRADE_TO_7X_VCS_MODE="Firmware download not supported. Please change the vcs mode to Logical Chassis and try again." 
UNSUPPORTED_DOWNGRADE_FROM_710="Firmware download is not allowed with reserved VCS-id 8193. It is not supported in the firmware being downloaded. Please change the VCS-id using \"vcs vcsid <x>\" and try again."
UNSUPPORTTED_RIGEL_MOR_DRAM_DOWNGRADE="A newer HW component has been detected, thus firmware download is blocked to avoid degrading the system performance of BR-VDX6940-144S platform."

UNSUPPORTTED_RIGEL_DRAM_DOWNGRADE="A newer HW component has been detected, thus firmware download is blocked to avoid degrading the system performance of BR-VDX6940-36Q platform."

UNSUPPORTED_DOWNGRADE_MAX_SSLKEY_CFG="Downgrade is not allowed because number of configured Crypto keys are more than one. It is not supported in the firmware being downloaded. Please remove the configuration using \"sw0(config-rbridge-id-XX)# no crypto key label <key name>\" and try again. It is recommended to remove keys that are not associated with a trustpoint which authenticated HTTPS"
UNSUPPORTED_DOWNGRADE_MAX_SSLTRUSTPOINT_CFG="Downgrade is not allowed because number of configured Crypto CA trustpoints are more than one. It is not supported in the firmware being downloaded. Please remove the configuration using \"sw0(config-rbridge-id-XX)# no crypto ca trustpoint <trustpoint name>\" and try again. It is recommended to remove trustpoints that are not used to authenticate HTTPS"
UNSUPPORTED_DOWNGRADE_REMOVE_SWCERT_MSG="Downgrade is not allowed because certificates are imported for LDAP/RADIUS/SYSLOG/OPENFLOW TLS client authenticaiton. It is not supported in the firmware being downloaded. Please remove the certificates using \"sw0# no crypto ca import ...\" and try again. It is recommended to not to remove certificate that is imported for HTTPS"
UNSUPPORTED_DOWNGRADE_REMOVE_CACERT_MSG="Downgrade is not allowed because CA certificates are imported for LDAP/RADIUS/SYSLOG/OPENFLOW TLS client authenticaiton. It is not supported in the firmware being downloaded. Please remove the CA certificates using \"sw0# no crypto ca authenticate ...\" and try again. It is recommended to not to remove CA certificate that is authenticated for HTTPS"
UNSUPPORTED_DOWNGRADE_REMOVE_RADIUSCA_MSG="Downgrade is not allowed because RADIUS CA certificate is imported for TLS server authentication. It is not supported in the firmware being downloaded. Please remove the certificate using \"sw0# no crypto import radiusca\" and try again."
UNSUPPORTED_DOWNGRADE_REMOVE_OPENFLOWCA_MSG="Downgrade is not allowed because Openflow CA certificate is imported for TLS server authentication. It is not supported in the firmware being downloaded. Please remove the certificate using \"sw0# no crypto import openflowca\" and try again."

DOWNGRADE_IS_NOT_ALLOWED_IF_SHA512_USERPASSWD_CONFIGURED="Downgrade is not allowed due to the below reason(s):\n - Non-default users are configured with password encryption-level 10. Encryption-level 10 passwords are not supported in the firmware being downloaded.\n   Please remove the non-default user configuration by using \"sw0(config)# no username <user-name>\"\n\n - Reset default user's (admin & user) password to factory-default by using \"sw0# execute-script factory_reset_defaultuser_passwords.sh\".\n\nPlease try the downgrade after correcting the same."

DOWNGRADE_IS_NOT_ALLOWED_IF_SHA512_DEFAULT_USERPASSWD_CONFIGURED="Downgrade is not allowed due to the below reason:\n - Reset default user's (admin & user) password to factory-default by using \"sw0# execute-script factory_reset_defaultuser_passwords.sh\".\n\nPlease try the downgrade after correcting the same."

DOWNGRADE_IS_NOT_ALLOWED_IF_SHA512_NONDEFAULT_USERPASSWD_CONFIGURED="Downgrade is not allowed due to the below reason:\n - Non-default users are configured with password encryption-level 10. Encryption-level 10 passwords are not supported in the firmware being downloaded.\n   Please remove the non-default user configuration by using \"sw0(config)# no username <user-name>\"\n\nPlease try the downgrade after correcting the same."

add_err_status() {
	echo -e "$1\n" >> $STATUS_FILE
}

# swbd
swbd() {
    /bin/sed -n -e 's/^.*\(SWBD[[:digit:]]\{1,\}\).\+$/\1/gp'
}

# Determine the system platform identifier.
SWBD=$(sin | swbd 2> /dev/null)
SLOT=`sin 2>/dev/null | grep "Slot No:" | cut -d ':' -f 2 | cut -d ' ' -f 2`

# Determine whether this is a M4
is_m4_chassis()
{
	case ${SWBD##SWBD} in
		'1000')
			return 1;;
        *)
			return 0;;
	esac
}

#
# Check whether this is a MM
#
is_mm_system()
{
	case ${SWBD##SWBD} in
		'1000' | '1001' | '1002' | '1003')
			return 1;;
        *)
			return 0;;
	esac
}

is_callisto()
{	
	case ${SWBD##SWBD} in
		'95' | '96' | '97' | '107' | '116' | '112' | '123') 
			return 1;;
		*)
			return 0;;
	esac
}

is_blackbird()
{
	case ${SWBD##SWBD} in
		'138')
			return 1;;
		*)
			return 0;;
	esac
}

is_kumataka()
{
	case ${SWBD##SWBD} in
		'138')
			/fabos/cliexec/chassisshow | grep -i "Part Num" | tail -1 | grep "HT2746"
			if [ $? -eq 0 ]; then
				return 1
			else
				return 0
			fi
			;;
		*)
			return 0;;
	esac
}

is_blackbird_and_snmp()
{
	case ${SWBD##SWBD} in
		'138')
			/fabos/cliexec/chassisshow | grep -i "Part Num" | tail -1 | grep "HT2746"
			if [ $? -eq 0 ]; then
				return 0
			else
				PARENT_PROCESS=`cat /proc/$PPID/cmdline`
				if [[ $PARENT_PROCESS == *snmpd* ]]; then
					return 1
				else
					return 0
				fi
			fi
			;;
		*)
			return 0
			;;
	esac
}

ha_role()
{
    /fabos/cliexec/hashow | while read ha; do
		case $ha in
        	*Local*Active*)
				return 1;
        	;;
        	*Local*Standby*)
				return 0;
        	;;
        	*"Not supported"*)
        		return 1; 
        	;;
        	*)
        		return 0;
        	;;
    	esac
	done
	return $?
}

get_peer_slot()
{
	peer_slot=0
	if [ -n "$SLOT" ]; then
		if [ 15 -eq $SLOT ]; then
			peer_slot=16
		elif [ 16 -eq $SLOT ]; then
			peer_slot=15
		elif [ 1 -eq $SLOT ]; then
			peer_slot=2
		elif [ 2 -eq $SLOT ]; then
			peer_slot=1
		else
			peer_slot=0
		fi
	fi
	echo "$peer_slot"
}

check_for_disruptive_options ()
{
	allow_disruptive_single_mode_fwdl
	if [ $? -ne $STS_OK ];then
		allow_disruptive_defconfig_mode_fwdl
		if [ $? -ne $STS_OK ];then
			allow_disruptive_cold_fwdl
			if [ $? -ne $STS_OK ];then
				add_err_status "$UNSUPPORTED_ISSU_MSG"
				return $STS_ERR
			fi
		fi
	fi
	return $STS_OK
}

is_issu_supported ()
{
	$ECHO "ISSU is supported"
	return 1;
}

# Use this function to
# Execute the cmd in Local(Active) if the Current MM is Active
# or
# Execute the cmd in Remote(Active) if the Current MM is Standby
run_cmd() {

	ha_role
	if [ $? -eq 1 ];then
		"$@"
	else
		# skip the rsh cmd for standby during firmware restore since it might block if active reboots before standby.
		if [ $FIRMWARE_RESTORE -ne "1" ]; then
			peer_slot=$(get_peer_slot)
			/usr/bin/rsh -n 127.2.1.$peer_slot ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 FABOS_SWITCHNO=$FABOS_SWITCHNO CURRENT_VF=$CURRENT_VF CURRENT_AD=$CURRENT_AD "$@"
		fi
    fi

	return $?
}

sync_lc_dir() {
	rm /var/log/lc_cmd.sav 2> /dev/null
	cp /var/log/lc_cmd /var/log/lc_cmd.sav 2> /dev/null
	>/var/log/lc_cmd
	is_m4_chassis
	if [ $? == 1 ]; then
		slots="7 8 9 10" 
	else
		slots="1 2 3 4 11 12 13 14" 
	fi
	for slot in $slots; do
		slotinfo='/proc/fabos/blade/$slot/info'
		[ -e $slotinfo ] || continue
		/fabos/link_sbin/rcli -as $slot "/bin/mkdir /mnt/var/images/base 2>/dev/null" >> /var/log/lc_cmd
		/fabos/link_sbin/rcli -as $slot "/bin/cp /mnt/var/images/SWBD*/* /mnt/var/images/base/" >> /var/log/lc_cmd
		n=$[`/fabos/link_sbin/rcli -as $slot "/bin/echo GOS" | /fabos/link_bin/grep -c GOS`];
		if [ $n -gt 0 -a $n -ne $[$n/4*4] ]; then
			single_partition_slots="$single_partition_slots $slot"
		fi
	done
	if [ -n "$single_partition_slots" ]; then
		add_err_status "Slot$single_partition_slots $LC_HAS_ONE_GOS_MSG"
		exit $STS_ERR
	fi
}

CONFDCMD()
{
#/fabos/bin/noscli << EOA
/usr/confd/bin/confd_cli -C --user _support_save_ --groups admin << EOA
$@
EOA
}

ag_mode_enabled() {
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    AG_EXIST=`CONFDCMD show running-config rbridge-id $rbridge_id ag | grep -c "no enable"`
    if [ $AG_EXIST -eq 0 ]; then
        SWITCH_AGMODE=1
    else
        SWITCH_AGMODE=0
    fi
    return $SWITCH_AGMODE
}

check_vid_ivid_uniformity() {
    if [ $FROM_MAJOR -ge 4 ] && [ $FROM_MINOR -ge 1 ]; then
        if [ $TO_MAJOR -eq 4 ] &&[ $TO_MINOR -eq 0 ]; then
        uniformity_config=`CONFDCMD show system internal nsm ivid | grep -c "Non-Uniform"`
        return $uniformity_config
        fi
    fi

    return $STS_OK
}

 
fcoe_enodes_config_local() {

        enodes_config_local=`CONFDCMD show running-config fcoe | grep -c "enodes-config local"`
        return $enodes_config_local

}

virtual_mac_config_local() {

		rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
        vmac_config_local=`CONFDCMD show running-config rbridge-id $rbridge_id | grep -c "virtual-mac 02e0.5200.00xx"`
        return $vmac_config_local

}

is_default_config_enabled() {

        rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
        default_config_mode=`CONFDCMD show running-config rbridge-id $rbridge_id default-config enable | grep -c "enable"`
        return $default_config_mode

}

check_rad_tac_enc_level_set() {
	rad_tac_enc_lvl=`CONFDCMD show running-config tacacs-server | grep -c "encryption-level 7"`
	if [ $rad_tac_enc_lvl -eq 0 ]; then
		rad_tac_enc_lvl=`CONFDCMD show running-config radius-server | grep -c "encryption-level 7"`
	fi
	return $rad_tac_enc_lvl
}

check_hardware_profile_config() {

	RET_VAL=$STS_OK
	rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
	tcam_profile=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id hardware-profile tcam | /bin/awk 'FNR == 2 { print $3 }'`
	route_ecmp=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id hardware-profile route | /bin/sed -n -e 's/^.*\(maximum_paths [0-9]*\).\+$/\1/gp' | /usr/bin/cut -d' ' -f2`
	kap_profile=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id hardware-profile kap | /bin/awk 'FNR == 2 { print $3 }'`

	if [ "$tcam_profile" == "dyn-arp-insp" ]; then
		add_err_status "$UNSUPPORTED_DOWNGRADE_DAI_MSG"
		RET_VAL=$STS_ERR
	elif [ "$tcam_profile" == "openflow" ]; then
		add_err_status "$UNSUPPORTED_DOWNGRADE_OPENFLOW_MSG"
		RET_VAL=$STS_ERR
	fi

	if [ "$route_ecmp" != "8" ]; then
		add_err_status "$UNSUPPORTED_DOWNGRADE_ECMP_MSG"
		RET_VAL=$STS_ERR
	fi

	if [ "$kap_profile" != "default" ]; then
		add_err_status "$UNSUPPORTED_DOWNGRADE_KAP_MSG"
		RET_VAL=$STS_ERR
	fi

	return $RET_VAL
}

# Specialized function to check the downgrade to pre 7.0 releases.
check_hardware_profile_config_tcam_ipv4acl() {
	RET_VAL=$STS_OK
	is_mm_system
	if [ $? -ne 1 ]; then
		# TCAM Ipv4ACL cannot be set on Non-MM based systems.
		return $RET_VAL
	fi

	rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
	tcam_profile=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id hardware-profile tcam | /bin/awk 'FNR == 2 { print $3 }'`

	if [ "$tcam_profile" == "ipv4-acl" ]; then
		add_err_status "$UNSUPPORTED_DOWNGRADE_TCAM_IPV4ACL_MSG"
		RET_VAL=$STS_ERR
	fi

	return $RET_VAL
}

#         
# Check if new 8548E revision 3.1 CPU
# If so then block downgrade to prior releases 
# that do not support the new CPU
#   
check_new_8548_CP_fw_compatibility()
{
	if [ $TO_MAJOR -ge "3" ]
	then
		return $STS_OK
	fi

	chipset=`cat /proc/cpuinfo | awk '/chipset/ {print $3}'`
	revision=`cat /proc/cpuinfo | awk '/revision/ {print $3}'`

	if [ -z $chipset ] || [ $chipset != 8548E ]; then
		# This is not a 8548E CP return OK
		return $STS_OK
	fi  

	if [ -n $revision ]; then
		#revision=3.1 #uncomment this to test with current 2.0 CP
		result=`expr $revision '>=' "3.1" 2>/dev/null`
		if [ $result == 1 ]; then
			# Current/Active CP is 8548E CP Rev 3.1
			# check if the firmware being downloaded supports new CP 
			new_cp_supported=`grep -c "Version Supports 8548 Rev 3.1 CP" /tmp/fwdl-$PPID/preinst`
			if [ $new_cp_supported -eq 0 ]; then
				# Cannot downgrade to fw version that does not support this CP
				return $STS_ERR
			else
				# New CP and new firmware is compatible.
				return $STS_OK
			fi
		fi
	fi
	#old/No Revision
	return $STS_OK
}



#Prevent firmware downgrade from NOS4.0.1 to any pre-4.0.1 versions,
#if any TACACS+ secret key configured is of length <=7
check_tacacs_secret_length_lessthan8()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		tac_secret=`/bin/awk '/tacacs-server/ {getline;print}' $STARTUP_CONFIG_FILE|/bin/awk '/key/ {print $2}'`
		for i in $tac_secret; do
			if [ ${#i} -le 7 ]; then
				return $STS_ERR
			fi
		done
	fi
	return $STS_OK
	
}


#Prevent firmware downgrade from NOS4.0.1 to any pre-4.0.1 versions,
#if any default/non-default user expiry date is set.(ie. its not defaulted to 'no expiry')
check_user_expire_set()
{
	
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
    	if [ -f $STARTUP_CONFIG_FILE ]; then
        	/bin/grep "expire" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
        	if [ $? -eq 0 ]; then
            		return $STS_ERR
		fi
	fi
	return $STS_OK	
}

#if ssh server rekey-interval is configured.
check_ssh_rekey_interval_set()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	SSHD_CONFIG_FILE=/etc/sshd_config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "ssh" $STARTUP_CONFIG_FILE | /bin/grep rekey-interval 2>&1 > /dev/null

		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	else
		rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
		ssh_rekey=`CONFDCMD show running-config rbridge-id $rbridge_id ssh| grep -c "rekey-interval"`
		if [ $ssh_rekey -ne 0 ]; then
			return $STS_ERR
		fi
	fi
	return $STS_OK
}

check_ssh_rekey_volume_set()
{
        STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
       
        if [ -f $STARTUP_CONFIG_FILE ]; then
                /bin/grep "ssh" $STARTUP_CONFIG_FILE | /bin/grep rekey-volume 2>&1 > /dev/null

                if [ $? -eq 0 ]; then
                        return $STS_ERR
                fi
        else
                rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
                ssh_rekey=`CONFDCMD show running-config rbridge-id $rbridge_id ssh| grep -c "rekey-volume"`
                if [ $ssh_rekey -ne 0 ]; then
                        return $STS_ERR
                fi
        fi

        return $STS_OK
}

check_ssh_max_auth_tries_set()
{
        STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
     
        if [ -f $STARTUP_CONFIG_FILE ]; then
                /bin/grep "ssh" $STARTUP_CONFIG_FILE | /bin/grep max-auth-tries 2>&1 > /dev/null

                if [ $? -eq 0 ]; then
                        return $STS_ERR
                fi
        else
                rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
                ssh_authtries=`CONFDCMD show running-config rbridge-id $rbridge_id ssh| grep -c "max-auth-tries"`
                if [ $ssh_authtries -ne 0 ]; then
                        return $STS_ERR
                fi
        fi

        return $STS_OK
}

check_ssh_max_idle_timeout_set()
{
        STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
   
        if [ -f $STARTUP_CONFIG_FILE ]; then
                /bin/grep "ssh" $STARTUP_CONFIG_FILE | /bin/grep max-idle-timeout 2>&1 > /dev/null

                if [ $? -eq 0 ]; then
                        return $STS_ERR
                fi
        else
                rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
                ssh_timeout=`CONFDCMD show running-config rbridge-id $rbridge_id ssh| grep -c "max-idle-timeout"`
                if [ $ssh_timeout -ne 0 ]; then
                        return $STS_ERR
                fi
        fi

        return $STS_OK
}

check_ssh_max_login_timeout_set()
{
        STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
 
        if [ -f $STARTUP_CONFIG_FILE ]; then
                /bin/grep "ssh" $STARTUP_CONFIG_FILE | /bin/grep max-login-timeout 2>&1 > /dev/null

                if [ $? -eq 0 ]; then
                        return $STS_ERR
                fi
        else
                rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
                ssh_timeout=`CONFDCMD show running-config rbridge-id $rbridge_id ssh| grep -c "max-login-timeout"`
                if [ $ssh_timeout -ne 0 ]; then
                        return $STS_ERR
                fi
        fi

        return $STS_OK
}

# Check for X.509v3 certificate based SSH authentication configuration
check_ssh_server_algorithm_hostekey_x509v3()
{
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    ssh_algo=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id ssh server algorithm hostkey| grep -c "ssh server algorithm hostkey"`
    if [ $ssh_algo -ge 1 ]; then
        add_err_status "$UNSUPPORTED_DOWNGRADE_SSH_SERVER_ALGO_HOSTKEY_CFG"
        return $STS_ERR
    fi
    return $STS_OK
}

check_ssh_server_algorithm_publickey_x509v3()
{
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    ssh_publickey=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id ssh server algorithm publickey | grep -c "ssh server algorithm publickey"`
    if [ $ssh_publickey -gt 1 ]; then
        add_err_status "$UNSUPPORTED_DOWNGRADE_SSH_SERVER_ALGO_PUBLICKEY_CFG"
        return $STS_ERR
    fi
    return $STS_OK
}

check_ssh_server_certificate_tp_sign_x509v3()
{
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    tp_sign=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id ssh server cert profile server | grep -c "trustpoint sign"`
    if [ $tp_sign -ge 1 ]; then
        add_err_status "$UNSUPPORTED_DOWNGRADE_SSH_SERVER_CERT_PROFILE_TP_SIGN_CFG"
        return $STS_ERR
    fi
    return $STS_OK
}

check_ssh_server_certificate_tp_verify_x509v3()
{
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    tp_verify=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id ssh server cert profile user | grep -c "trustpoint verify"`
    if [ $tp_verify -ge 1 ]; then
        add_err_status "$UNSUPPORTED_DOWNGRADE_SSH_SERVER_CERT_PROFILE_TP_VERIFY_CFG"
        return $STS_ERR
    fi
    return $STS_OK
}

check_nos730_fedcert_cli()
{
   check_ssh_rekey_volume_set
   if [ $? -ne $STS_OK ]; then
        add_err_status "$UNSUPPORTED_DOWNGRADE_SSH_REKEYVOLUME_CFG_MGS"
        return $STS_ERR
   fi
   check_ssh_max_auth_tries_set
    if [ $? -ne $STS_OK ]; then
         add_err_status "$UNSUPPORTED_DOWNGRADE_SSH_MAXAUTHTRIES_CFG_MGS"
         return $STS_ERR
    fi
   check_ssh_max_idle_timeout_set
   if [ $? -ne $STS_OK ]; then
         add_err_status "$UNSUPPORTED_DOWNGRADE_SSH_MAXIDLETIMEOUT_CFG_MGS"
         return $STS_ERR
   fi
   check_ssh_max_login_timeout_set
   if [ $? -ne $STS_OK ]; then
           add_err_status "$UNSUPPORTED_DOWNGRADE_SSH_MAXLOGINTIMEOUT_CFG_MGS"
           return $STS_ERR
   fi

   check_ssh_server_certificate_tp_verify_x509v3
   if [ $? -ne $STS_OK ]; then
       return $STS_ERR
   fi
   check_ssh_server_algorithm_publickey_x509v3
   if [ $? -ne $STS_OK ]; then
       return $STS_ERR
   fi
   check_ssh_server_certificate_tp_sign_x509v3
   if [ $? -ne $STS_OK ]; then
       return $STS_ERR
   fi   
   check_ssh_server_algorithm_hostekey_x509v3
   if [ $? -ne $STS_OK ]; then
       return $STS_ERR
   fi


   return $STS_OK
}

#Check for SSH Server MaxSessions Configuration
check_ssh_max_session_set()
{
	rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
	ssh_session=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id ssh server max-session | /bin/grep -c "max-session"`
	if [ $ssh_session -ne 0 ]; then
		return $STS_ERR
	fi

	return $STS_OK
}

#Crypto check, Security
check_one_kp_exists() {
	rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
	num_kp=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id crypto key | grep -c "crypto key label"`
	if [ $num_kp -gt 1 ]; then
		add_err_status "$UNSUPPORTED_DOWNGRADE_MAX_SSLKEY_CFG"
		return $STS_ERR
	fi
	return $STS_OK
}

check_one_tp_exists() {
	rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
	num_tp=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id crypto ca trustpoint| grep -c "crypto ca trustpoint"`
	if [ $num_tp -gt 1 ]; then
		add_err_status "$UNSUPPORTED_DOWNGRADE_MAX_SSLTRUSTPOINT_CFG"
		return $STS_ERR
	fi
	return $STS_OK
}

check_extra_swcert_exists() {
#check if swcert imported for auth_type other than https
	cert_list=(ldap radius syslog commoncert openflow)

	for cert in "${cert_list[@]}"
	do
		swcert=`/fabos/cliexec/config get ssl.swcert.$cert 5`
		if [ ! -z $swcert ]; then
			add_err_status "$UNSUPPORTED_DOWNGRADE_REMOVE_SWCERT_MSG"
		return $STS_ERR
	fi
	done
	return $STS_OK
}

check_extra_cacert_exists() {
	cert_list=(ldap radius syslog commoncert openflow)

	for cert in "${cert_list[@]}"
	do
		cacert=`/fabos/cliexec/config get ssl.cacert.$cert 5`
		if [ ! -z $cacert ]; then
			add_err_status "$UNSUPPORTED_DOWNGRADE_REMOVE_CACERT_MSG"
			return $STS_ERR
		fi
	done
	return $STS_OK
}

check_radiusca_exists() {
	if [ -f /etc/fabos/certs/radius/swRadiusca.pem ]; then
		add_err_status "$UNSUPPORTED_DOWNGRADE_REMOVE_RADIUSCA_MSG"
		return $STS_ERR
	fi
	return $STS_OK
}

check_openflowca_exists() {
	if [ -f /etc/fabos/certs/openflow/swOpenflowca.pem ]; then
		add_err_status "$UNSUPPORTED_DOWNGRADE_REMOVE_OPENFLOWCA_MSG"
		return $STS_ERR
	fi
	return $STS_OK
}

check_fwdl_downgrade_730fedcert_to_lower() {
	check_one_kp_exists
	if [ $? -ne $STS_OK ]; then
		return $STS_ERR
	fi
	check_one_tp_exists
	if [ $? -ne $STS_OK ]; then
		return $STS_ERR
	fi
	check_extra_swcert_exists
	if [ $? -ne $STS_OK ]; then
		return $STS_ERR
	fi
	check_extra_cacert_exists
	if [ $? -ne $STS_OK ]; then
		return $STS_ERR
	fi

	check_radiusca_exists
	if [ $? -ne $STS_OK ]; then
		return $STS_ERR
	fi
	check_openflowca_exists
	if [ $? -ne $STS_OK ]; then
		return $STS_ERR
	fi
}

check_unsupported_snmp_config_fips()
{
	# md5 auth protocol is not supported in fips mode. Check if md5 authtype 
	# is configured for any snmpv3 user. 
	for (( i = 0; i < 10; i++ ))
	do
 	AUTHPROTO=`/fabos/cliexec/config get  snmp.snmpv3Usm.$i.usmAuthProtocol 2`
	if [ "$AUTHPROTO" -eq "1" ];then
		add_err_status "$UNSUPPORTED_SNMP_FIPS_AUTH_MD5"
    	return $STS_ERR
	fi

 	# Skip password check if password is encrypted and auth/priv is
 	# NoAuth/NoPriv is configured

 	PRIVPROTO=`/fabos/cliexec/config get snmp.snmpv3Usm.$i.usmPrivProtocol 2`
	ENCFLAG=`/fabos/cliexec/config get snmp.snmpv3Usm.$i.usmEncPswdFlag 2`

	if [ "$ENCFLAG" != "1" ];then 
		if [ "$AUTHPROTO" != "3" ];then
			AUTHLEN=`/fabos/cliexec/config get snmp.snmpv3Usm.$i.usmAuthSecret 5 |  wc -c`
 			# Decrementing by 1 because wc -c returns number of characters
	 		# including null 
 			AUTHLEN=$((AUTHLEN-1))
			# In NOS, Each character in auth password is stored as hexadecimal
			# value seperated by space so 8 character string will have 23 character
			# in backend.
	 		if [ "$AUTHLEN" -lt "23" ];then
				add_err_status "$UNSUPPORTED_SNMP_FIPS_PASS_LEN"
 				return $STS_ERR
	 		fi
		fi
		if [ "$PRIVPROTO" != "2" ];then
			PRIVLEN=`/fabos/cliexec/config get snmp.snmpv3Usm.$i.usmPrivSecret 5 |  wc -c`
 			# Decrementing by 1 because wc -c returns number of characters
	 		# including null 
 			PRIVLEN=$((PRIVLEN-1))
			# In NOS, Each character in priv password is stored as hexadecimal
			# value seperated by space so 8 character string will have 23 character
			# in backend.
	 		if [ "$PRIVLEN" -lt "23" ];then
				add_err_status "$UNSUPPORTED_SNMP_FIPS_PASS_LEN"
 				return $STS_ERR
 			fi
		fi
	fi
 	done
	return $STS_OK
}

#Check for SSH Sha356 cipher Configuration
check_ssh_sha256_cipher()
{
	SSHD_CONFIG_FILE=/etc/sshd_config
	if [ -f $SSHD_CONFIG_FILE ]; then
		/bin/grep "^ShaValue 2" $SSHD_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	fi

	return $STS_OK
}

#check if ssh server cipher is configured
check_sshserver_cipher_set()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "ssh server cipher" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	else
		rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
		sshserver_cipher=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "server cipher"`
		if [ $sshserver_cipher -ne 0 ]; then
			return $STS_ERR
		fi
	fi

	fipsmode
	if [ $? -eq 0 ]; then
		SSHD_CONFIG=/etc/sshd_config
		if [ -f $SSHD_CONFIG ]; then
			/bin/grep "Ciphers aes128-ctr,aes192-ctr,aes256-ctr" $SSHD_CONFIG 2>&1 > /dev/null
			if [ $? -eq 0 ]; then
				return $STS_ERR
			fi
		fi
	fi
}

#check if ssh server mac is configured
check_sshserver_mac_set()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "ssh server mac" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	else
		rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
		sshserver_mac=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "server mac"`
		if [ $sshserver_mac -ne 0 ]; then
			return $STS_ERR
		fi
	fi
	return $STS_OK
}

#check if NTP server enabled on custom vrf
check_ntp_server_custom_vrf_enabled()
{
	if [ $VCS_MODE -ne 1 ];then
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "ntp server" $STARTUP_CONFIG_FILE | /bin/grep -vw "mgmt-vrf" | /bin/grep -cw "use-vrf" 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	fi
	else
		ntp_server_vrf=`CONFDCMD show running-config ntp | /bin/grep -vw "mgmt-vrf" | /bin/grep -cw "use-vrf"`
		if [ $ntp_server_vrf -ne 0 ]; then
			return $STS_ERR
		fi
	fi

	return $STS_OK
}

#check if ssh/telnet server enabled on custom vrf
check_server_custom_vrf_enabled()
{
	svr_usevrf="server use-vrf"
	defvrf="default-vrf"
	mgmtvrf="mgmt-vrf"
	if [ $VCS_MODE -ne 1 ];then
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "$1 $svr_usevrf" $STARTUP_CONFIG_FILE | /bin/grep -v "$defvrf" | /bin/grep -v "$mgmtvrf" 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	fi
	else
		rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
		no_server_vrf=`CONFDCMD show running-config rbridge-id $rbridge_id $1 | /bin/grep -v "$defvrf" | /bin/grep -v "$mgmtvrf" | /bin/grep -c "$svr_usevrf"`
		if [ $no_server_vrf -ne 0 ]; then
			return $STS_ERR
		fi
	fi
	return $STS_OK
}

is_aaa_default_vrf_enabled_runcfg()
{
	defvrf_shut="server use-vrf default-vrf shutdown"
	defvrf="server use-vrf default-vrf"

	rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
	is_defvrf_shut=`CONFDCMD show running-config rbridge-id $rbridge_id $1 | grep -c "$defvrf_shut"`

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

	is_defvrf_noshut=`CONFDCMD show running-config rbridge-id $rbridge_id $1 | grep -c "$defvrf"`
	if [ $is_defvrf_noshut -ne 0 ]; then
		 return $STS_OK
	else
		return $STS_ERR
	fi
	return $STS_OK
}

is_aaa_default_vrf_enabled_startcfg()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then

		defvrf_shut="server use-vrf default-vrf shutdown"
		defvrf="server use-vrf default-vrf"	

		/bin/grep "$1 $defvrf_shut" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi

		/bin/grep "$1 $defvrf" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_OK
		else
			return $STS_ERR
		fi
	fi
	return $STS_OK
}

#Check if AAA server on default-vrf is same as mgmt-vrf(disabled)
#return
#	STS_OK on success(default and mgmt vrf has same config
#	1 if mgmt-vrf is disabled but default-vrf is enabled
#	2 if mgmt-vrf is enabled but default-vrf is disabled

check_server_defaultvrf_status()
{
	mgmtvrf_shut="server use-vrf mgmt-vrf shutdown"
	mgmtvrf="server use-vrf mgmt-vrf"

	if [ $VCS_MODE -ne 1 ];then
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "$1 $mgmtvrf" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -ne 0 ]; then
			return $STS_OK
		fi

		is_aaa_default_vrf_enabled_startcfg $1
		aaaserver_defvrf_enabled=$?
		/bin/grep "$1 $mgmtvrf_shut" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			if [ $aaaserver_defvrf_enabled -eq $STS_OK ]; then
				return 1
			fi
		else
			if [ $aaaserver_defvrf_enabled -eq $STS_ERR ]; then
				return 2
			fi
		fi
	fi
	else
		aaaserver_mgmt=`CONFDCMD show running-config rbridge-id $rbridge_id $1 | grep -c "$mgmtvrf"`
		if [ $aaaserver_mgmt -eq 0 ]; then
			return $STS_OK
		fi

		aaaserver_mgmtvrf=`CONFDCMD show running-config rbridge-id $rbridge_id $1 | grep -c "$mgmtvrf_shut"`
		is_aaa_default_vrf_enabled_runcfg $1
		aaaserver_defvrf_enabled=$?

		if [ $aaaserver_mgmtvrf -ne 0 ]; then
			if [ $aaaserver_defvrf_enabled -eq $STS_OK ]; then
				return 1
			fi
		else
			if [ $aaaserver_defvrf_enabled -eq $STS_ERR ]; then
				return 2
			fi
		fi
	fi
	return $STS_OK
}

# Check if any aa server like radius/tacacs/ldap is configured with user defined vrf
check_aaaconf_vrf_enabled()
{
	if [ $VCS_MODE -ne 1 ];then
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
   	if [ -f "$STARTUP_CONFIG_FILE" ]; then
       	`/bin/grep -e "radius\|tacacs\|ldap" $STARTUP_CONFIG_FILE | /bin/grep -w "use-vrf" | /bin/grep -vw "mgmt-vrf" 2>&1 > /dev/null`
       	if [ $? -eq 0 ]; then
           		return $STS_ERR
		fi
	fi
	else
		radius_enabled=`CONFDCMD show $TARGET_DB radius-server | /bin/grep -w "use-vrf" | /bin/grep -vw "mgmt-vrf"`
		tacacs_enabled=`CONFDCMD show $TARGET_DB tacacs-server | /bin/grep -w "use-vrf" | /bin/grep -vw "mgmt-vrf"`
		ldap_enabled=`CONFDCMD show $TARGET_DB ldap-server | /bin/grep -w "use-vrf" | /bin/grep -vw "mgmt-vrf"`
		 if [ "$radius_enabled" != "" ] || [ "$tacacs_enabled" != "" ] || [ "$ldap_enabled" != "" ]; then	
			return $STS_ERR
		fi
	fi
	return $STS_OK	
}

# Check if any syslog-server is configured with user defined vrf
check_syslog_user_defined_vrf_enabled()
{
	syslog_user_defined_vrf=`CONFDCMD show $TARGET_DB logging syslog-server | /bin/grep -w "use-vrf" | /bin/grep -vw "mgmt-vrf" |  /bin/grep -vw "default-vrf"`

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

	return $STS_OK
}


# Check if any syslog-server is configured with default vrf, needs to block for NOS6.0.0
check_syslog_default_vrf_enabled()
{
	syslog_default_vrf=`CONFDCMD show $TARGET_DB logging syslog-server | grep -w "use-vrf default-vrf"`
	if [ "$syslog_default_vrf" != "" ]; then
		return $STS_ERR
	fi

	return $STS_OK
}

# Check if any accesstime is configured for user-defined user, needs to block for version lower than 7.0.1
# Skipped default admin and default user accesstime configuration check below. 
# Handled the same in postinst script.
check_accestime_exists()
{
	accesstime=`CONFDCMD show $TARGET_DB username | /bin/grep -w "access-time" | /bin/grep -vw "username admin " | /bin/grep -vw "username user "`
	if [ "$accesstime" != "" ]; then
		return $STS_ERR
	fi

	return $STS_OK
}

#check if ssh client cipher is configured
check_sshclient_cipher_set()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "ssh client cipher" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	else
		rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
		sshclient_cipher=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "client cipher"`
		if [ $sshclient_cipher -ne 0 ]; then
			return $STS_ERR
		fi
	fi

	fipsmode
	if [ $? -eq 0 ]; then
		SSH_CONFIG=/etc/ssh_config
		if [ -f $SSH_CONFIG ]; then
			/bin/grep "Ciphers aes128-ctr,aes192-ctr,aes256-ctr" $SSH_CONFIG 2>&1 > /dev/null
			if [ $? -eq 0 ]; then
				return $STS_ERR
			fi
		fi
	fi
}

#check if ssh client mac is configured
check_sshclient_mac_set()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "ssh client mac" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	else
		rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
		sshclient_mac=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "client mac"`
		if [ $sshclient_mac -ne 0 ]; then
			return $STS_ERR
		fi
	fi
	return $STS_OK
}

#check if ssh server kex is set to !dh-group-14
check_sshserver_kex_str()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "ssh server key-exchange dh-group-14" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_OK
		else
			/bin/grep "ssh server key-exchange" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
			if [ $? -eq 0 ]; then
				return $STS_ERR
			fi
		fi
	else
		rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
		sshserver_kexstr=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "server key-exchange dh-group-14"`
		if [ $sshserver_kexstr -ne 0 ]; then
			return $STS_OK
		else
			sshserver_kexstr=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "server key-exchange"`
			if [ $sshserver_kexstr -ne 0 ]; then
				return $STS_ERR
			fi
		fi
	fi
	return $STS_OK
}

#check if ssh server cipher is set to !non-cbc
check_sshserver_cipher_str()
{           
    STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
    if [ -f $STARTUP_CONFIG_FILE ]; then
        /bin/grep "ssh server cipher non-cbc" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
        if [ $? -eq 0 ]; then
            return $STS_OK
        else
            /bin/grep "ssh server cipher" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
            if [ $? -eq 0 ]; then
                return $STS_ERR
            fi
        fi
    else 
        rbridge_id=`/fabos/cliexec/config get fabric.domain 2` 
        sshserver_cipherstr=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "server cipher non-cbc"`
        if [ $sshserver_cipherstr -ne 0 ]; then
            return $STS_OK
        else
            sshserver_cipherstr=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "server cipher"`
            if [ $sshserver_cipherstr -ne 0 ]; then
                return $STS_ERR 
            fi
        fi
    fi
    return $STS_OK
}

#check if ssh client cipher is set to !non-cbc
check_sshclient_cipher_str()
{
    STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
    if [ -f $STARTUP_CONFIG_FILE ]; then
        /bin/grep "ssh client cipher non-cbc" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
        if [ $? -eq 0 ]; then
            return $STS_OK
        else
            /bin/grep "ssh client cipher" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
            if [ $? -eq 0 ]; then
                return $STS_ERR
            fi
        fi
    else
        rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
        sshclient_cipherstr=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "client cipher non-cbc"`
        if [ $sshclient_cipherstr -ne 0 ]; then
            return $STS_OK
        else
            sshclient_cipherstr=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "client cipher"`
            if [ $sshclient_cipherstr -ne 0 ]; then
                return $STS_ERR
            fi
        fi
    fi
    return $STS_OK
}

#check if ssh client kex is configured
check_sshclient_kex_set()
{
	kex_str="ssh client key-exchange" 
	kex_rstr="client key-exchange"
	kex_str1="ssh client key-exchange dh-group-14" 
	kex_rstr1="client key-exchange dh-group-14"

	#6.0.1 to 5.0.1b1 is allowed if "ssh client key-exchange dh-group-14" or no kex is configured
	#6.0.1 to 6.0.0/5.0.1/5.0.1a/5.0.1b is allowed only if no kex is configured

	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "$kex_str" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			if [ "$1" == "dh-group-14" ] ; then
				/bin/grep "$kex_str1" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
				if [ $? -ne 0 ]; then
					return $STS_ERR
				fi
			else
				return $STS_ERR
			fi
		fi
	else
		rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
		sshclient_kex=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "$kex_rstr"`
		if [ $sshclient_kex -ne 0 ]; then
			if [ "$1" == "dh-group-14" ] ; then
				sshclient_kex1=`CONFDCMD show running-config rbridge-id $rbridge_id ssh | grep -c "$kex_rstr1"`
				if [ $sshclient_kex1 -eq 0 ]; then
					return $STS_ERR
				fi
			else
				return $STS_ERR
			fi
		fi
	fi
	return $STS_OK
}

#check if the ISLs are online in the breakout mode.
check_if_isl_enabled_on_brk_ports()
{
	if [ -f /proc/fabos/switch/0/tuple_info ]; then
		ISL_ENABLED=`grep -c "ISLs" /proc/fabos/switch/0/tuple_info`
		if [ $ISL_ENABLED -ne 0 ]; then
			return $STS_ERR
		fi
	fi
	return $STS_OK
}
check_dual_partition_in_lc()
{
        ret=$STS_OK

        is_mm_system
        if [ $? -ne 1 ]; then
                return $ret
        fi

        run_cmd /fabos/sbin/hashow -a | grep -e "L.*\/.*:" | while read LINE
        do
                case $LINE in
                        *"Dual Partitions"*)
                                $ECHO Dual Partition $LINE
                        ;;
                        *)
                                $ECHO Error $LINE
                                return $STS_ERR
                        ;;
                esac
        done

        return $?
}

#
# Check sanity of tunnel configurations during upgrade or downgrade
#
check_tunnel_config_not_exists() {
    local ret=$STS_OK
    local gateway_exists=`CONFDCMD show running-config overlay-gateway | grep -c overlay-gateway`
    local nsx_exists=`CONFDCMD show running-config nsx-controller | grep -c nsx-controller`

    if [ $gateway_exists -ne 0 ]; then
        add_err_status "$1 $INCOMPATIBLE_OVERLAY_GATEWAY_CONFIG_ERR_SUFFIX"
        ret=$STS_ERR
    fi

    if [ $nsx_exists -ne 0 ]; then
        add_err_status "$1 $INCOMPATIBLE_NSX_CONTROLLER_CONFIG_ERR_SUFFIX"
        ret=$STS_ERR
    fi

    return $ret
}

check_is_401patcha()
{
	BUILD_STR=$TO_RID
# Downgrade to 4.0.1(eg:4.0.1_bld03) should be blocked
# differentiate 4.0.1 and > 4.0.1a
	if [ -n $BUILD_STR ]; then
		PATCH_VER=`echo $BUILD_STR | cut -c6`
		case ${PATCH_VER} in
			_)
				return $STS_ERR
				;;
			*)
				return $STS_OK
				;;
		esac
	fi
	return $STS_OK
}

check_is_501patcha()
{
    BUILD_STR=$TO_RID
# Downgrade to 5.0.1(eg:5.0.1_bld02) should be blocked
# differentiate 5.0.1 and > 5.0.1a
    if [ -n $BUILD_STR ]; then
        PATCH_VER=`echo $BUILD_STR | cut -c6`
        case ${PATCH_VER} in
            _)
                return $STS_ERR
                ;;
            a)
                return $STS_ERR
                ;;
            *)
                return $STS_OK
                ;;
        esac
    fi
    return $STS_OK
}

check_is_501patchb1()
{
	BUILD_STR=$TO_RID
	PATCH_VER=`echo $BUILD_STR | cut -c6-7`
	if [ "$PATCH_VER" == "b1" ]; then
		return $STS_ERR
	fi	
	return $STS_OK
}

check_is_701patch_aa_ab()
{
    BUILD_STR=$TO_RID
# Downgrade to 7.0.1(eg:7.0.1_bld02),7.0.1aa,7.0.1ab should be blocked
# differentiate 7.0.1 and > 7.0.1a
    if [ -n $BUILD_STR ]; then
        PATCH_VER=`echo $BUILD_STR | cut -c5-7`
       if [ "$PATCH_VER" == "1" -o "$PATCH_VER" == "1aa" -o "$PATCH_VER" == "1ab" ]; then
                return $STS_ERR
       fi
    fi 
    return $STS_OK
}
#check if not in MC mode if switch is Blackbird.
check_for_not_mcmode_if_blackbird()
{
	is_blackbird
	if [ $? == 1 ]; then
		PATH_FWDL_CONF_FILE="/etc/fwdl.conf"
		FWDL_CONF_VCS_MODE=`sed -n 's/vcs-mode : \(\-\?[0-9]\+\)/\1/p' $PATH_FWDL_CONF_FILE`
		MCMODE="0`cat /etc/fabos/Dcmd/cluster.conf 2> /dev/null`"
		if [ $MCMODE -ne 0 ]; then
			add_err_status "$UNSUPPORTED_DOWNGRADE_BLACKBIRD_CURRENT_MCMODE"
			return $STS_ERR
		fi
		if [ $FIRMWARE_RESTORE -ne "1" ]; then
			if [ "$FWDL_CONF_VCS_MODE" -eq 1 ]; then
				add_err_status "$UNSUPPORTED_DOWNGRADE_BLACKBIRD_TO_MCMODE"
				return $STS_ERR
			fi
		fi
	fi
	return $STS_OK
}

#
# Check whether the system contains any interfaces with "qos random-detect" config.
#
does_system_contain_any_interface_with_qos_red_config() {

    interface_qos_red_config=`CONFDCMD show running-config interface | grep -c "qos random-detect"`
        return $interface_qos_red_config
}

#
# Check whether the system contains multiple class-map with the same "access-list".
#
is_acl_used_in_multiple_class_maps() {

    class_map_config=`CONFDCMD show running-config class-map | grep -E "match access-group"`
    num_of_class_maps=`echo "$class_map_config" | wc -l`
    num_of_class_maps_with_unique_acl=`echo "$class_map_config" | sort -u | wc -l`
    if [ $num_of_class_maps -ne $num_of_class_maps_with_unique_acl ]; then
        return 1;
    fi
    return 0;
}

#
#check if leading underscore in username
#
check_leading_underscore_username()
{
    STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config

    check_run_cfg_needed=1
    if [ -f $STARTUP_CONFIG_FILE ]; then
        check_run_cfg_needed=0
        enc_lvl=`/bin/grep "username" $STARTUP_CONFIG_FILE | awk '{print match($2,"^_")}'`
        for flag in $enc_lvl
        do
            if [ $flag -eq 1 ]; then
                add_err_status "$UNSUPPORTED_DOWNGRADE_USERNAME"
                return $STS_ERR
            fi
        done
    fi

    # LC mode does not have startup-cfg so check the running config
    if [ $check_run_cfg_needed -eq 1 ]; then
        username=`CONFDCMD show running-config username | awk '{print match($2,"^_")}'`
        for flag in $username
        do
            if [ $flag -eq 1 ]; then
                add_err_status "$UNSUPPORTED_DOWNGRADE_USERNAME"
                return $STS_ERR
            fi
        done
    fi
}

check_flex_ports()
{
	CONFDCMD show running-config hardware flexport | grep fibre-channel
	
	if [ $? -eq 0 ]; then
		return $STS_ERR
	fi
	
	return $STS_OK
	
}

check_breakout_flex_ports()
{
	CONFDCMD show $TARGET_DB hardware flexport | grep "flexport" | grep ":"

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

	return $STS_OK
}
 #check whether 100G interface exists under hardware portgroup.
check_rigelmor_portgroup_100g()
{   
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    CONFDCMD show running-config hardware port-group > /tmp/pg_out
    pg_num=$(grep -A 2 " $rbridge_id\/" /tmp/pg_out | grep "100"|wc -l)
    if [ $pg_num -ne 0 ]; then
        return $STS_ERR
    fi 
    return $STS_OK
}   

#check whether breakout mode is enabled for the local node
check_rigelmor_breakout()
{
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    CONFDCMD show running-config hardware connector > /tmp/br_out
    br_num=$(grep -A 2 " $rbridge_id\/" /tmp/br_out | grep "sfp" | grep -v "no sfp" | wc -l)
    if [ $br_num -ne 0 ]; then
        return $STS_ERR
    fi
    return $STS_OK
}

#check if non-default duplicate wwn login policy is configured. 
check_duplicateWWN_login_policy_non_default()
{
	CONFDCMD show fabric login-policy | grep "new-login"

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

	return $STS_OK
}

#check if tacacs source ip is configured
check_tacacs_srcaddr_set()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "tacacs-server source-ip chassis-ip" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	else
		tacacs_srcip=`CONFDCMD show running-config tacacs-server| grep -c "source-ip chassis-ip"`
		if [ $tacacs_srcip -ne 0 ]; then
			return $STS_ERR
		fi
	fi
}

#check if password-attribute lockout-duration is configured
check_passwd_attrib_lockout_dur_set()
{
    STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
    if [ -f $STARTUP_CONFIG_FILE ]; then
        /bin/grep "password-attributes max-lockout-duration" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
        if [ $? -eq 0 ]; then
            return $STS_ERR
        fi
    else
        lockout_dur=`CONFDCMD show running-config password-attributes| grep -c "max-lockout-duration"`
        if [ $lockout_dur -ne 0 ]; then
            return $STS_ERR
        fi
    fi
    return $STS_OK
}

#check if NTP source ip is configured
check_ntp_srcaddr_set()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "ntp source-ip chassis-ip" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	else
		ntp_srcip=`CONFDCMD show running-config ntp | grep -c "source-ip chassis-ip"`
		if [ $ntp_srcip -ne 0 ]; then
			return $STS_ERR
		fi
	fi
}

#check if root enable is not configured
check_root_account_enable_set()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "root enable" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 1 ];then
			return $STS_ERR
		fi
	else
		root_account=`CONFDCMD show running-config rbridge-id root | grep -c "root enable"`
		if [ $root_account -eq 0 ]; then
			return $STS_ERR
		fi
	fi
	 return $STS_OK
}

#check if root access console is configured
check_root_access_configured()
{
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "root access" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ];then
			return $STS_ERR
		fi
	else
		root_access=`CONFDCMD show running-config rbridge-id root | grep -c "root access"`
		if [ $root_access -ne 0 ]; then
			return $STS_ERR
		fi
	fi
	return $STS_OK
}

#Prevent firmware downgrade from NOS6.0.0 to any pre-6.0.0 versions,
#if any crypto config is set
check_crypto_config()
{
	crypto_exists=`CONFDCMD show running-config rbridge-id crypto | grep -c crypto`
	keypair_exists=`CONFDCMD show running-config rbridge-id crypto | grep -c keypair`
       
        if [ $crypto_exists -ne 0 ] || [ $keypair_exists -ne 0 ]; then
            return $STS_ERR
        fi

	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
    	if [ -f $STARTUP_CONFIG_FILE ]; then
        	/bin/grep "crypto key\|crypto ca\|keypair" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
        	if [ $? -eq 0 ]; then
            		return $STS_ERR
		fi
	fi

	return $STS_OK	
}

#
#Check if NTP Key configuration has encryption level
#

check_ntp_enc_level_set() {
    ntp_enc_lvl=`CONFDCMD show running-config ntp | grep -c "encryption-level 7"`
    return $ntp_enc_lvl
}

#Check clock timezone has updated timezone configuration
check_tz_entry() {
    STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
    if [ -f $STARTUP_CONFIG_FILE ]; then
        /bin/grep "clock timezone Asia/Srednekolymsk" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
        if [ $? -eq 0 ]; then
            return $STS_ERR
        fi
    else
        tz_entry=`CONFDCMD show clock | grep -c "Asia/Srednekolymsk"`
        if [ $tz_entry -ne 0 ]; then
            return $STS_ERR
        fi
    fi
     return $STS_OK
}

#
#Check NTP has SHA-1 key configuration
#
check_ntp_sha1_key() {
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "ntp authentication-key" $STARTUP_CONFIG_FILE | /bin/grep "sha1" 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	else
		ntp_key=`CONFDCMD show running-config ntp authentication-key | grep -c "sha1"`
		if [ $ntp_key -ne 0 ]; then
			return $STS_ERR
		fi
	fi
	return $STS_OK
}

#
#Check RBAC commands configuration
#

check_rbac_config() {
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "rule" $STARTUP_CONFIG_FILE | awk '{print $(NF-1) " " $NF}' | /bin/grep "command interface"
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
		/bin/grep "rule" $STARTUP_CONFIG_FILE | awk '{print $(NF-1)}' | /bin/grep "management"
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	else		
		rbac_cfg=`CONFDCMD show running-config rule | awk '{print $(NF-1) " " $NF}' | grep -c "command interface"`
		if [ $rbac_cfg -ne 0 ]; then
			return $STS_ERR
		fi
		rbac_cfg=`CONFDCMD show running-config rule | awk '{print $(NF-1)}' | grep -c "management"`
		if [ $rbac_cfg -ne 0 ]; then
			return $STS_ERR
		fi
	fi

	cmds_list=(ve loopback fibrechannel fortygigabitethernet hundredgigabitethernet)

	for cmds in "${cmds_list[@]}"
	do
		if [ -f $STARTUP_CONFIG_FILE ]; then
			/bin/grep -E 'rule.*interface' $STARTUP_CONFIG_FILE | /bin/grep "$cmds" 2>&1 > /dev/null
			if [ $? -eq 0 ]; then
				return $STS_ERR
			fi
		else
			rbac_cfg=`CONFDCMD show running-config rule | grep -c "command interface $cmds"`
			if [ $rbac_cfg -ne 0 ]; then
				return $STS_ERR
			fi
		fi
	done
	return $STS_OK
}

	
#
#If Ospfv3 has duplicate area range in 6.x.x, upgrade to 7.0.0 needs to be blocked
#

check_ospfv3_area_range() {
    RET_VAL=$STS_OK
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    vrfs=`CONFDCMD show running-config rbridge-id $rbridge_id vrf | grep  "vrf" |awk '{print $2}' `
    all_vrfs=(${vrfs//' '/ })
    length=${#all_vrfs[@]}
    all_vrfs[$length]='default-vrf'
    for vrf in ${all_vrfs[@]} ;
        do
             `CONFDCMD show running-config rbridge-id $rbridge_id ipv6 router ospf vrf $vrf| grep  "range" |awk '{print $4}' > /tmp/ospfv3_area_range.txt`
              with_duplicates=`cat /tmp/ospfv3_area_range.txt | wc -l`
              only_uniques=`sort -uf /tmp/ospfv3_area_range.txt | wc -l`
#              echo "vrf=$vrf:with_duplicates=$with_duplicates and only_uniques=$only_uniques"
              if [ $only_uniques -ne $with_duplicates ]; then
                RET_VAL=$STS_ERR
                break
              fi
        done
    rm -f /tmp/ospfv3_area_range.txt
    return $RET_VAL
}
	
#
#check if scpuser configuration is present
#

check_scpuser_cfg() {
	STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config

	if [ -f $STARTUP_CONFIG_FILE ]; then
		/bin/grep "username scpuser" $STARTUP_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			return $STS_ERR
		fi
	else
		usr_chk=`CONFDCMD show running-config username | grep -c "scpuser"`
		if [ $usr_chk -ne 0 ]; then
			return $STS_ERR
		fi
	fi

	return $STS_OK
}

check_rbac_showcmds()
{
    cmds_list=(rbridge-local-running-config rbridge-running-config running-config startup-config startup-db)

    for cmds in "${cmds_list[@]}"
    do
		rbac_showcmds=`CONFDCMD show $TARGET_DB rule | /bin/grep -c "show $cmds"`
	    if [ $rbac_showcmds -ne 0 ]; then
	        return $STS_ERR
	    fi
    done
    return $STS_OK
}

check_rbac_showcmds1()
{
	cmds_list=(legacy-running-config local-running-config cli)

	for cmds in "${cmds_list[@]}"
	do
		rbac_showcmds=`CONFDCMD show $TARGET_DB rule | /bin/grep -c "show $cmds"`
		if [ $rbac_showcmds -ne 0 ]; then
			return $STS_ERR
		fi
	done
	return $STS_OK
}

#
# upgrade to 2.0 case
#

handle_from_any_to_20()
{
	add_err_status "$UNSUPPORTED_DOWNGRADE_TO_20_MSG"
	return $STS_ERR
}

#
# downgrade to 2.1 case
#
handle_from_any_to_21()
{
	add_err_status "$UNSUPPORTED_DOWNGRADE_TO_21_MSG"
    return $STS_ERR
}

#
# downgrade to 3.0 case
#
handle_from_any_to_30()
{
	#check if it is not an embedded platfrom KATANA or HARRIER
	if [ ${SWBD##SWBD} == '112' ] || [ ${SWBD##SWBD} == '123' ] ; then
		allow_disruptive_defconfig_mode_fwdl
		if [ $? -ne $STS_OK ];then
			add_err_status "$DEFCONFIG_DOWNLOAD_TO_30_MSG"
			return $STS_ERR
		fi
		return $STS_OK
	fi
	# for all other platforms
	add_err_status "$UNSUPPORTED_DOWNGRADE_TO_30_MSG"
    return $STS_ERR
}

#
# upgrade to 4.0 case
#
handle_from_any_to_40()
{
	# No direct downgrade support from 7.0 -> 4.0
	add_err_status "$UNSUPPORTED_DOWNGRADE_TO_40_MSG"
	return $STS_ERR

}

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

	# Skip for restore
	$ECHO $FIRMWARE_RESTORE
	if [ $FIRMWARE_RESTORE -eq "1" ]; then
		$ECHO " running firmwarerestore"
		return $STS_OK
	fi

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

    return $STS_OK
}

allow_disruptive_defconfig_mode_fwdl() {

	# Skip for restore
	$ECHO $FIRMWARE_RESTORE
	if [ $FIRMWARE_RESTORE -eq "1" ]; then
		$ECHO " running firmwarerestore"
		return $STS_OK
	fi

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

    return $STS_OK
}

check_vrrp_num_max_all_sess () {
	num_max_vrrp_sess_700=255
	rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
	num_sess=`CONFDCMD show running-config rbridge-id $rbridge_id | grep 'vrrp-group\|vrrp-extended-group' | wc -l`

	if [ $num_sess -gt $num_max_vrrp_sess_700 ]; then
		add_err_status "$UNSUPPORTED_NUM_RIGEL_700_VRRP_SESS"  
		return $STS_ERR
	fi

	return $STS_OK
}

check_sag_num_max_interface_sess () {
	num_max_sag_sess_700=32
	rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    rb_ve_config=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id | grep 'interface Ve ' | awk '{print $3}'`
    for num in $rb_ve_config; do
	num_sess=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id interface ve $num | grep 'anycast-address' | wc -l`
	if [ $num_sess -gt $num_max_sag_sess_700 ]; then
		add_err_status "$UNSUPPORTED_NUM_700_SAG_SESS"  
		return $STS_ERR
	fi
    done

	return $STS_OK
}

allow_disruptive_cold_fwdl() {

	# Skip for restore
	$ECHO $FIRMWARE_RESTORE
	if [ $FIRMWARE_RESTORE -eq "1" ]; then
		$ECHO " running firmwarerestore"
		return $STS_OK
	fi
    is_fwdl_arg "M"
    local defconfig=$?
    if [ $defconfig -ne 0 ]; then
        return $STS_ERR
    fi

    return $STS_OK
	

}

check_bgp_evpn_config () {
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    bgp_address_family_l2evpn_exists=`CONFDCMD show $TARGET_DB rbridge-id   $rbridge_id router bgp | grep -c 'address-family l2vpn evpn'`
    bgp_evpn_instance_exists=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id evpn-instance | grep -c 'evpn-instance '`
    bgp_vrf_rd_exists=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id vrf | grep -c 'rd '`
    bgp_vrf_vni_exists=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id vrf | grep -c 'vni '`
    bgp_vrf_rt_exists=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id vrf | grep -c 'route-target '`

    if [ $bgp_address_family_l2evpn_exists -ne 0 ] || [ $bgp_evpn_instance_exists -ne 0 ] || [ $bgp_vrf_rd_exists -ne 0 ] || [ $bgp_vrf_vni_exists -ne 0 ] || [ $bgp_vrf_rt_exists -ne 0 ]; then
        add_err_status "$UNSUPPORTED_BGP_EVPN"
        return $STS_ERR
    fi

    return $STS_OK
}

check_bgp_dynamic_nbr_config () {
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    bgp_listen_exists=`CONFDCMD show $TARGET_DB rbridge-id   $rbridge_id router bgp | grep -c 'listen'`
	bgp_alt_as_exists=`CONFDCMD show $TARGET_DB rbridge-id   $rbridge_id router bgp | grep -c 'alternate-as'`

    if [ $bgp_listen_exists -ne 0 ] || [ $bgp_alt_as_exists -ne 0 ]; then
        add_err_status "$UNSUPPORTED_BGP_DYN_NBR"
        return $STS_ERR
    fi

    return $STS_OK
}


check_bgp_gshut_nbr_config () {
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    bgp_gshut_exists=`CONFDCMD show $TARGET_DB rbridge-id   $rbridge_id router bgp | grep -c 'graceful-shutdown'`

    if [ $bgp_gshut_exists -ne 0 ]; then
        add_err_status "$UNSUPPORTED_BGP_GSHUT_NBR"
        return $STS_ERR
    fi

    return $STS_OK
}

check_bgp_vrf_filter_config () {
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    bgp_vrf_import_map_exists=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id vrf | grep -c 'import map '`
    bgp_vrf_export_map_exists=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id vrf | grep -c 'export map '`
    ip_extcommunitylist_regexp=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id ip extcommunity-list | grep 'extcommunity-list ' | awk '{print $3}'`

    ip_extcommunitylist_regexp_exists=0
    for num in $ip_extcommunitylist_regexp; do
	if [ $num -gt 99 ]; then
            ip_extcommunitylist_regexp_exists=1
            break
        fi
    done


    if [ $bgp_vrf_import_map_exists -ne 0 ] || [ $bgp_vrf_export_map_exists -ne 0 ] || [ $ip_extcommunitylist_regexp_exists -ne 0 ]; then
        add_err_status "$UNSUPPORTED_BGP_VRF_FILTER"
        return $STS_ERR
    fi

    return $STS_OK
}

check_bgp_ipv6_sitelocal_config () {
    rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
    ipv6_site_local_network_exists=`CONFDCMD show $TARGET_DB rbridge-id   $rbridge_id router bgp | grep -c 'network fe[c|d|e|f]'`
    ipv6_site_local_aggregate_exists=`CONFDCMD show $TARGET_DB rbridge-id $rbridge_id router bgp | grep -c 'aggregate-address fe[c|d|e|f]'`

    if [ $ipv6_site_local_network_exists -ne 0 ] || [ $ipv6_site_local_aggregate_exists -ne 0 ]; then
        add_err_status "$UNSUPPORTED_IPV6_SITELOCAL_ADDR_BGP"
        return $STS_ERR
    fi

    return $STS_OK
}


FIPSCFG_PATH="/fabos/abin/fipscfg"
FIPSCFGFILE="/etc/fabos/fips_selftests.conf"

# Return true (0) if we are in FIPS mode
# cache result in FIPSFLAG so this is cheap to run.
fipsmode(){
	local F
	if [ ! -x ${FIPSCFG_PATH} ]
	then
		echo "fips config does not exist on the system"
		# If file does not exist assume FIPS is not set.
		FIPSFLAG=1
		return 1
	fi

	if [ -z "$FIPSFLAG" ]
	then    if F=$(cat $FIPSCFGFILE 2>/dev/null)
			then    if [ "$F" != "0" ]
					then FIPSFLAG=0
        			else FIPSFLAG=1
					fi
        	else
            	# echo "$0: Needed file $FIPSCFGFILE not readable" >&2
            	FIPSFLAG=1 # If the file is missing then assume not FIPS mode
        	fi
    fi

    return $FIPSFLAG
}


#
# upgrade to 4.1 case
#
handle_from_any_to_41()
{
	allow_disruptive_defconfig_mode_fwdl
	if [ $? -ne $STS_OK ];then
		add_err_status "$UNSUPPORTED_CFG_MSG"
		return $STS_ERR
	fi
	return $STS_OK
}

handle_from_any_to_50()
{
    # kumataka(VDX2746) uses same swbd # as blackbird, but it is not supported in 5.0.x
    is_blackbird
    if [ $? == 1 ]; then
        /fabos/cliexec/chassisshow | grep "HT27460000000" > /dev/null
        if [ $? == 0 ]; then
            add_err_status "$UNSUPPORTED_UPGRADE_TO_50_KUMATAKA_MSG"
            return $STS_ERR
        fi
    fi

	allow_disruptive_defconfig_mode_fwdl
	if [ $? -ne $STS_OK ];then
		add_err_status "$UNSUPPORTED_CFG_MSG"
		return $STS_ERR
	fi

	return $STS_OK;
}

Is_Rigel_10x()
{
	/bin/cat /proc/hv_console | /bin/grep -A 1 "Storage Device Details" | /bin/grep "HyMap"
	if [ $? -eq $STS_OK ]; then
		return $STS_ERR
	fi
	return $STS_OK
}

#
# Check Rigel-Mor using new DRAM: Smart  PN SH1027SR351893SE
#                                 Wintec PN WD3AE808G13IMN-BRD
#
is_rigel_mor_new_dram_v1()
{
    if [ ${SWBD##SWBD} == '164' ]; then
        ln -s /fabos/cliexec/em /fabos/link_sbin/em_get_fru_id
		PN_last2Digit=`/fabos/link_sbin/em_get_fru_id | grep "Part Number" | cut -d '-' -f 3`
        if [ $PN_last2Digit -ge '11' ] && [ $PN_last2Digit -lt '13' ]; then
            return $STS_OK
        fi
    fi
    return $STS_ERR
}

#
# Check Rigel using new DRAM: Wintec PN WD3AE808G13IMP-BRD for Rigel-1U(153)
# Uboot tuning DRAM:          Wintec PN WD3AE808G13IMN-BRD for Rigel-1U(153) and Rigel-Mor (164)
#
is_rigel_new_dram_v2()
{
    if [ ${SWBD##SWBD} == '164' ] ; then
        ln -s /fabos/cliexec/em /fabos/link_sbin/em_get_fru_id
        PN_last2Digit=`/fabos/link_sbin/em_get_fru_id | grep "Part Number" | cut -d '-' -f 3`
        if [ $PN_last2Digit -ge '13' ]; then
            return $STS_OK
        fi
    fi
    if [ ${SWBD##SWBD} == '153' ] ; then
        ln -s /fabos/cliexec/em /fabos/link_sbin/em_get_fru_id
        PN_last2Digit=`/fabos/link_sbin/em_get_fru_id | grep "Part Number" | cut -d '-' -f 3`
        if [ $PN_last2Digit -ge '11' ]; then
            return $STS_OK
        fi
    fi
    return $STS_ERR
}

Is_Cobra2_13()
{
	/fabos/bin/bladevershow | grep -i "Cobra" | grep "1.3" > /dev/null 2>&1 
	if [ $? -eq $STS_OK ]; then
		return $STS_ERR
	fi
	return $STS_OK
}

handle_from_any_to_60()
{
	# Platform scpecific
    Is_Rigel_10x
    if [ $? -ne $STS_OK ]; then
        if [ $TO_PATCH -eq 0 ]; then
            add_err_status "$UNSUPPORTTED_RIGEL_MOR_10X_DOWNGRADE"
            return $STS_ERR
        elif [ $TO_PATCH -eq 1 -a $TO_REVISION -eq 1 ]; then
            add_err_status "$UNSUPPORTTED_RIGEL_MOR_10X_DOWNGRADE"
            return $STS_ERR
        fi
    fi
	
	# Platform Specific
    Is_Cobra2_13
    if [ $? -ne $STS_OK ]; then
        if [ $TO_PATCH -eq 0 ]; then
            add_err_status "$UNSUPPORTED_COBRA2_13"
            return $STS_ERR
        elif [ $TO_PATCH -eq 1 -a $TO_REVISION -eq 1 ]; then
            add_err_status "$UNSUPPORTED_COBRA2_13"
            return $STS_ERR
        fi
    fi

#
# If the version number is equal or greater than 6.0.2h, we allow firmware download.
# Otherwise, need to check what DRAM is using.
# If DRAM is Wintect, do not allow firmware download
# If DRAM is Smart, do not allow firmware download to 6.0.2e or lower version
#
    if [ $TO_MAJOR -eq 6 ] && [ $TO_MINOR -eq 0 ] && [ $TO_PATCH -ge 2 ]; then
        if [ $TO_REVISION -ge 6 ]; then
            $ECHO "6.0.2h onwards, no need to block FWDL"
        else
            is_rigel_new_dram_v2
            if [ $? -eq $STS_OK ]; then
                if [ ${SWBD##SWBD} == '153' ] ; then
                    add_err_status "$UNSUPPORTTED_RIGEL_DRAM_DOWNGRADE"
                fi
                if [ ${SWBD##SWBD} == '164' ] ; then
                    add_err_status "$UNSUPPORTTED_RIGEL_MOR_DRAM_DOWNGRADE"
                fi
                return $STS_ERR
            fi

            is_rigel_mor_new_dram_v1
            if [ $? -eq $STS_OK ] && [ $TO_REVISION -le 3 ]; then
                    add_err_status "$UNSUPPORTTED_RIGEL_MOR_DRAM_DOWNGRADE"
                    return $STS_ERR
            fi
        fi
    fi

	allow_disruptive_defconfig_mode_fwdl
	if [ $? -ne $STS_OK ];then
		add_err_status "$UNSUPPORTED_CFG_MSG"
		return $STS_ERR
	fi

    return $STS_OK
}

handle_from_any_to_70()
{

#
# If the internal version number is equal or greater than 7.0.1d, we allow firmware download..
# Otherwise we need to check what DRAM is using
# If DRAM is Wintect, do not allow firmware download
# If DRAM is Smart, do not allow firmware download to 7.0.1c1 or lower version
#
    if [ $TO_MAJOR -eq 7 ] && [ $TO_MINOR -eq 0 ] && [ $TO_PATCH -ge 1 ]; then
        if [ $TO_REVISION -ge 5 ]; then
            $ECHO "7.0.1d onwards, no need to block FWDL"
        else
            is_rigel_new_dram_v2
            if [ $? -eq $STS_OK ]; then
                if [ ${SWBD##SWBD} == '153' ] ; then
                    add_err_status "$UNSUPPORTTED_RIGEL_DRAM_DOWNGRADE"
                fi
                if [ ${SWBD##SWBD} == '164' ] ; then
                    add_err_status "$UNSUPPORTTED_RIGEL_MOR_DRAM_DOWNGRADE"
                fi
                return $STS_ERR
            fi

            is_rigel_mor_new_dram_v1
            if [ $? -eq $STS_OK ] && [ $TO_REVISION -le 3 ]; then
                    add_err_status "$UNSUPPORTTED_RIGEL_MOR_DRAM_DOWNGRADE"
                    return $STS_ERR
            fi 
        fi
    fi

	allow_disruptive_defconfig_mode_fwdl
	if [ $? -ne $STS_OK ];then
		add_err_status "$UNSUPPORTED_CFG_MSG"
		return $STS_ERR
	fi

	return $STS_OK
}

handle_from_any_to_71()
{
#
# If the internal version number is equal or greater than 7.1.0c, we allow firmware download..
# Otherwise we need to check what DRAM is using
# If DRAM is Wintect, do not allow firmware download
# If DRAM is Smart, do not allow firmware download to 7.1.0a2 or lower version
#
    if [ $TO_MAJOR -eq 7 ] && [ $TO_MINOR -eq 1 ] && [ $TO_PATCH -ge 0 ]; then
        if [ $TO_REVISION -ge 6 ]; then
            $ECHO "7.1.0c onwards, no need to block FWDL"
        else
            is_rigel_new_dram_v2
            if [ $? -eq $STS_OK ]; then
                if [ ${SWBD##SWBD} == '153' ] ; then
                    add_err_status "$UNSUPPORTTED_RIGEL_DRAM_DOWNGRADE"
                fi
                if [ ${SWBD##SWBD} == '164' ] ; then
                    add_err_status "$UNSUPPORTTED_RIGEL_MOR_DRAM_DOWNGRADE"
                fi
                return $STS_ERR
            fi

            is_rigel_mor_new_dram_v1
            if [ $? -eq $STS_OK ] && [ $TO_REVISION -le 3 ]; then
                    add_err_status "$UNSUPPORTTED_RIGEL_MOR_DRAM_DOWNGRADE"
                    return $STS_ERR
            fi 
        fi
    fi

	allow_disruptive_defconfig_mode_fwdl
	if [ $? -ne $STS_OK ];then
	    add_err_status "$UNSUPPORTED_CFG_MSG"
		return $STS_ERR
	fi
    return $STS_OK
}

handle_from_any_to_72()
{
    #return handle_from_any_to_72()

    clusterconfvalue=`cat /etc/fabos/Dcmd/cluster.conf`
    if [ $clusterconfvalue == "0" ]; then
        add_err_status "$UNSUPPORTED_UPGRADE_TO_7X_VCS_MODE"
        return $STS_ERR
    fi

    if [ $FROM_MAJOR -eq 7 -a $FROM_MINOR -eq 4 ];then
           allow_disruptive_defconfig_mode_fwdl
           if [ $? -ne $STS_OK ];then
              add_err_status "$UNSUPPORTED_CFG_MSG"
              return $STS_ERR
           fi
    fi

    return $STS_OK
}

handle_from_any_to_73()
{

	if [ $TO_REVISION -lt 3 ]; then
		check_nos730_fedcert_cli
		if [ $? -ne $STS_OK ]; then
			return $STS_ERR
		fi
	fi

	if [ $TO_REVISION -lt 3 ]; then
		# Downgrade check frm 730fedcert to lower for Crypto configs.
		check_fwdl_downgrade_730fedcert_to_lower
		if [ $? -ne $STS_OK ]; then
			return $STS_ERR
		fi
	fi

    # from 7.4.1 -> 7.3.0 - Default only
    if [ $FROM_MAJOR -eq 7 -a $FROM_MINOR -eq 4 ]; then
        allow_disruptive_defconfig_mode_fwdl
        if [ $? -ne $STS_OK ];then
            add_err_status "$UNSUPPORTED_CFG_MSG"
            return $STS_ERR
        fi
    fi

	# From any to 7.3.0 and 7.3.x
	handle_sha512_userpasswords
	if [ $? -ne $STS_OK ];then
		return $STS_ERR
	fi

	return $STS_OK
}

################################
# General rule in NOS. 
#   N+0 - When upgrade/downgrade between patch releases, 
#		e.g. 7.2.1 and 7.2.2, we recommend ISSU. Of course, coldboot and default-config will work.
#	N+1 - When upgrade/downgrade between two adjacent releases, 
#		e.g. 7.3 and 7.4, we recommend coldboot. Of course, default-config will work.
#	N+2 - When upgrade/downgrade between two disjointed releases, 
#		e.g. 7.2 and 7.4, we recommend default-config. 

# This is how upgrade/download in NOS 7.4.0 works.
#	When upgrading from 7.3, we allow coldboot/default-config
#	When upgrading from 7.2 or below (the lowest is 4.1.0), we only allow default-config

#	When downgrading to 7.3, we allow coldboot/default-config
#	When downgrading to 7.2 or below (the lowest is 4.1.0), we only allow default-config
################################
handle_from_any_to_74()
{
	clusterconfvalue=`cat /etc/fabos/Dcmd/cluster.conf`
	if [ $clusterconfvalue == "0" ]; then
		add_err_status "$UNSUPPORTED_UPGRADE_TO_7X_VCS_MODE"
		return $STS_ERR
	fi

    #block ISSU from 7.4.1 --> below 7.4.1 and 7.4.0/7.4.0x --> 7.4.1 and support 741 --> 741a
    if [ $FROM_MAJOR -eq 7 -a $FROM_MINOR -eq 4 ]; then
		if [ $FROM_PATCH -eq 0 ] || [ $TO_PATCH -eq 0 ]; then
    		check_for_disruptive_options
        	if [ $? -ne $STS_OK ];then
				return $STS_ERR
        	fi
		fi
    fi

	# From any to 7.4.0/7.4.0x and 7.4.1
	if [ $TO_REVISION -lt 5 ]; then
		handle_sha512_userpasswords
		if [ $? -ne $STS_OK ];then
			return $STS_ERR
		fi
	fi

    # from 7.3/7.2/7.1/7.0 -> 7.4.1 - allow default-config 
	if [ $FROM_MAJOR -eq 7 ] && [ $FROM_MINOR -le 3 ] ;then
		allow_disruptive_defconfig_mode_fwdl
        if [ $? -ne $STS_OK ];then
				add_err_status "$UNSUPPORTED_CFG_MSG"
            return $STS_ERR
        fi
    fi

    # from 6.x or below - allow default-config 
    if [ $FROM_MAJOR -le 6 ];then
        allow_disruptive_defconfig_mode_fwdl
        if [ $? -ne $STS_OK ];then
				add_err_status "$UNSUPPORTED_CFG_MSG"
            return $STS_ERR
        fi
    fi
    
	return $STS_OK
}

# LCs 27x40G, 6x100G, and 48x10GT are not supported.
check_M2_linecards_fw_compatibility()
{
    RET_VAL=$STS_OK

    to_fw_supported=0
    if [ ${TO_MAJOR} -gt 4 ]; then
        to_fw_supported=1
    elif [ ${TO_MAJOR} -eq 4 ] && [ ${TO_MINOR} -gt 1 ]; then
        to_fw_supported=1
    elif [ ${TO_MAJOR} -eq 4 ] && [ ${TO_MINOR} -eq 1 ] && [ ${TO_PATCH} -gt 0 ]; then
        to_fw_supported=1
    fi
    
    from_fw_supported=0
    if [ ${FROM_MAJOR} -gt 4 ]; then
        from_fw_supported=1
    elif [ ${FROM_MAJOR} -eq 4 ] && [ ${FROM_MINOR} -gt 1 ]; then
        from_fw_supported=1
    elif [ ${FROM_MAJOR} -eq 4 ] && [ ${FROM_MINOR} -eq 1 ] && [ ${FROM_PATCH} -gt 0 ]; then
        from_fw_supported=1
    fi

    if [ $to_fw_supported -eq 0 ] || [ $from_fw_supported -eq 0 ]; then
        STARTUP_CONFIG_FILE=/var/config/vcs/scripts/startup-config
        lc_cfg_clean=0

        if [ -f $STARTUP_CONFIG_FILE ]; then
            /* handle the FC mode */
            lc_cfg_clean=`/bin/grep -E 'LC27X40G|LC6X100G|LC48X10GT|LC6X100G-POD' $STARTUP_CONFIG_FILE | wc -l`
        else
            /* handle the LC mode */
            rbridge_id=`/fabos/cliexec/config get fabric.domain 2`   
            lc_cfg_clean=`CONFDCMD show running-config rbridge-id $rbridge_id linecard | grep -E 'LC27X40G|LC6X100G|LC48X10GT|LC6X100G-POD' | wc -l`
        fi

	    if [ $lc_cfg_clean -ne 0 ]; then
	        add_err_status "$LC_INCOMPATIBLE_FW_CFG_MSG"
	        RET_VAL=$STS_ERR
	    fi

        if /fabos/bin/slotshow -m|grep -E 'LC27X40G|LC6X100G|LC48X10GT|LC6X100G-POD'>/dev/null; then
            add_err_status "$LC_INCOMPATIBLE_FW_PWR_MSG"
	        RET_VAL=$STS_ERR
        fi
    fi

	return $RET_VAL
}


# Block fwdl if user configured sha512 password
handle_sha512_userpasswords()
{
	is_fwdl_arg "d"
	local defconfig=$?
	# No need to handle for default-config fwdls
	if [ $defconfig -eq 0 ]; then
		return $STS_OK
	fi

	# Block fwdl if non-default users has sha512 passwords
	grep -vwE 'admin|user' /etc/shadow | grep '\$6\$' >> /dev/null
	nondefault_sha512_passwd=$?

	# If shadow file has sha512 default-user password,
	grep -wE "admin|user" /etc/shadow | grep '\$6\$' >> /dev/null
	default_sha512_passwd=$?

	if [ $default_sha512_passwd -eq 0 -a $nondefault_sha512_passwd -eq 0 ]; then 
		add_err_status "$DOWNGRADE_IS_NOT_ALLOWED_IF_SHA512_USERPASSWD_CONFIGURED"
		return $STS_ERR
	elif [ $default_sha512_passwd -eq 0 ]; then
		add_err_status "$DOWNGRADE_IS_NOT_ALLOWED_IF_SHA512_DEFAULT_USERPASSWD_CONFIGURED"
		return $STS_ERR
	elif [ $nondefault_sha512_passwd -eq 0 ]; then
		add_err_status "$DOWNGRADE_IS_NOT_ALLOWED_IF_SHA512_NONDEFAULT_USERPASSWD_CONFIGURED"
		return $STS_ERR
	else
		return $STS_OK
	fi

	return $STS_OK
}

check_if_downgrade()
{
    downgrade=0
    to_revision=${TO_REVISION}

    if [ p"${TO_REVISION}" == "p" ]; then
        to_revision=0
    fi    

    if [ ${TO_MAJOR} -lt ${FROM_MAJOR} ]; then
        downgrade=1
    elif [ ${TO_MAJOR} -eq ${FROM_MAJOR} ] && [ ${TO_MINOR} -lt ${FROM_MINOR} ]; then
        downgrade=1
    elif [ ${TO_MAJOR} -eq ${FROM_MAJOR} ] && [ ${TO_MINOR} -eq ${FROM_MINOR} ] && [ ${TO_PATCH} -lt ${FROM_PATCH} ]; then
        downgrade=1
    elif [ ${TO_MAJOR} -eq ${FROM_MAJOR} ] && [ ${TO_MINOR} -eq ${FROM_MINOR} ] && [ ${TO_PATCH} -eq ${FROM_PATCH} ] && [ ${to_revision} -lt ${FROM_REVISION} ]; then
        downgrade=1
    fi

    return ${downgrade}
}

#Prevent firmware upgrade from NOS6.0.0 to 6.0.1 version,
#if the vlan range for the sflow config under the overlay-gateway 
#overlaps with the vlan range for the stats/span config under 
#the overlay-gateway
check_overlaygateway_sflow_config()
{

sflow_vlan_range_overlapping_config_count=$(/usr/local/postgresql/9.1.3/bin/psql -t -p 9013 -d WaveDatabase -c 'select count(*) from wavecurrent.overlaygatewayconfigmanagedobject gw where exists (select 1 from wavecurrent.overlaygwsflowglobalconfigmanagedobject where ownermanagedobjectidinstanceid = gw.objectidinstanceid and ( (wavecurrent.contains_any(vlan_range, (select vlan_range from wavecurrent.overlaygwspanglobalconfigmanagedobject where ownermanagedobjectidinstanceid = gw.objectidinstanceid))) or (wavecurrent.contains_any(vlan_range,  gw.tunnelvlanstatsrangeadd)) ) )')

	if [$sflow_vlan_range_overlapping_config_count -ge '1' ]; then
	   return $STS_ERR
	fi
	   return $STS_OK
}

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

#
# Synchronize these directories (including Callisto/Carme)
# SWBDxx/ should always exist except in the hot-plug case
# during the hotplug case, the /base directory contains
# the latest info
#
if [ -f /mnt/var/images/${SWBD}/plist ]; then
	$ECHO "Synchronizing the base directory"
	cp /mnt/var/images/${SWBD}/* /mnt/var/images/base/ 2>/dev/null
else
	$ECHO "Synchronizing the platform-specific directory"
	cp /mnt/var/images/base/* /mnt/var/images/${SWBD}/ 2>/dev/null
fi

#
# Synchronize these directories in LCs to workaround
# a compatbility issue between dcmd_int and pit branches
#
is_mm_system
if [ $? == 1 ];then
	ha_role
	if [ $? == 1 ]; then
		$ECHO "synchronizing the /var/images/base directory in LCs" 	
		sync_lc_dir
	fi
fi

check_new_8548_CP_fw_compatibility
if [ $? -ne $STS_OK ]; then
	add_err_status "$CP_INCOMPATIBILE_FW_MSG"
	exit $STS_ERR
fi

# Mercury 2 linecards are not supported in versions prior to 4.1.1 
check_M2_linecards_fw_compatibility
if [ $? -ne $STS_OK ]; then
	exit $STS_ERR
fi

FWDL_LOG="/var/log/fwdl.log"
PATH_LOCAL_CONF_FILE="/etc/fabos/Dcmd/Dcmd.Linux.powerpc.local.conf"

if [ -f $PATH_LOCAL_CONF_FILE ]
then
    grep '<AbmFlag>' $PATH_LOCAL_CONF_FILE 2>>$FWDL_LOG 1>/dev/null
    ret=$?
    if [ $ret -eq 0 ]; then
        grep '<AbmFlag>false</AbmFlag>' $PATH_LOCAL_CONF_FILE 2>>$FWDL_LOG 1>/dev/null
        bm_ret=$?
        if [ $bm_ret -eq 0 ]; then
            echo "Current version $FROM_VER has Bare-Metal mode = false" >> $FWDL_LOG
        else
            echo "Current version $FROM_VER has Bare-Metal mode = true" >> $FWDL_LOG
        fi
    elif [ $ret -eq 1 ]; then
        echo "Current version $FROM_VER doesn't have bmFlag" >> $FWDL_LOG
    else
        echo "Grep error code = $ret" >> $FWDL_LOG
    fi
fi


#
# Handle SANITY check for FIRMWARE DOWNLOAD or FIRMWARE RESTORE to
# a specific firmware version
#

echo "Checking conditions for downloading to ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH}"

if [ $FROM_MAJOR -eq 7 -a $FROM_MINOR -ge 1 -o $FROM_MAJOR -gt 7 ]; then
    if [ $TO_MAJOR -eq 7 -a $TO_MINOR -eq 0 -o $TO_MAJOR -lt 7 ]; then
        vcsconfvalue=`cat /etc/fabos/Dcmd/vcs.conf`
        if [ $vcsconfvalue == "8193" ]; then
            add_err_status "$UNSUPPORTED_DOWNGRADE_FROM_710"
            exit $STS_ERR
        fi
    fi        
fi

case "${TO_MAJOR}.${TO_MINOR}" in
    '2.0')
		handle_from_any_to_20
		RET=$?
		;;
	'2.1')
        handle_from_any_to_21
        RET=$?
    	;;
    '3.0')
        handle_from_any_to_30
        RET=$?
    	;;
    '4.0')
        handle_from_any_to_40
        RET=$?
    	;;
    '4.1')
        handle_from_any_to_41
        RET=$?
    	;;
    '5.0')
        handle_from_any_to_50
        RET=$?
    	;;
    '6.0')
        handle_from_any_to_60
        RET=$?
    	;;
    '7.0')
        handle_from_any_to_70
        RET=$?
    	;;
    '7.1')
        handle_from_any_to_71
        RET=$?
    	;;
    '7.2')
        handle_from_any_to_72
        RET=$?
    	;;
	'7.3')
		handle_from_any_to_73
		RET=$?
		;;
	'7.4')
		handle_from_any_to_74
		RET=$?
		;;
esac

#Failure of pre-installation script during firmwaredownload (or)
#Failure of pre-restore script during firmwarerestore.
if [ $RET != $STS_OK ]; then
	exit $RET
fi

check_if_downgrade

if [ $? -eq 1 ]; then
    is_fwdl_arg "M"
    issu_fwdl_config=$?
    is_fwdl_arg "d"
    defconfig=$?
    if [ $defconfig -eq 0 ]; then
        #    do nothing.
        return $STS_OK

	# Added for the defect NOS-67911
	# Skip the Dcmd performSupportOpsOnSoftwareChange for ISSU downgrade.
    elif [ $issu_fwdl_config -ne 0 ]; then
          echo "Skipping the Dcmd performSupportOpsOnSoftwareChange for ISSU downgrade " >> $FWDL_LOG
    else
        FROM_REVISION_DCM=$FROM_REVISION
        if [ -z "$FROM_REVISION_DCM" ]; then
            FROM_REVISION_DCM=0;
        fi

        TO_REVISION_DCM=$TO_REVISION
        if [ -z "$TO_REVISION_DCM" ]; then
            TO_REVISION_DCM=0;
        fi
        to_ver=${TO_MAJOR}.${TO_MINOR}.${TO_PATCH}.${TO_REVISION_DCM}
   
        error_string=`/fabos/libexec/DcmClient.Linux.powerpc debug performSupportOpsOnSoftwareChange ${FROM_MAJOR}.${FROM_MINOR}.${FROM_PATCH}.${FROM_REVISION_DCM} ${to_ver} 0 no-verbose`

        if [ "p${error_string}" != "pSUCCESS" ]; then
            add_err_status "${error_string}"        
	        exit $STS_ERR
        fi

        if [ $VCS_MODE -eq 0 ];then
            error_string=`/fabos/libexec/DcmClient.Linux.powerpc -serverport 7110 debug performSupportOpsOnSoftwareChange ${FROM_MAJOR}.${FROM_MINOR}.${FROM_PATCH}.${FROM_REVISION_DCM} ${to_ver} 0 no-verbose`
            if [ "p${error_string}" != "pSUCCESS" ]; then
                add_err_status "${error_string}"        
                exit $STS_ERR
            fi
        fi
    fi
fi

#
#Sanity Check for FIRMWARE DOWNLOAD SANITY or FIRMWARE RESTORE SANITY
#has completed successfully.
#EXIT OF FIRMWARE DOWNLOAD.
#
if [ $FIRMWARE_RESTORE -ne "1" ]; then
	#
	# If ISSU is not supported, return auto-leveling
	#
	is_issu_supported
	echo $? > $PREINST_STS_FILE
	exit $RET;
fi

#
#
#CODE FOR FIRMWARE RESTORE OPERATION
#
#
BADDEV=`bootenv BadRootDev 2>/dev/null`
UPGRADE=`bootenv Upgrade 2>/dev/null`
SOFTUPGRADE=`bootenv SoftUpgrade 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'`

prom_restore()
{
	ret=$STS_OK
	if [ -s /mnt/boot/bootrom.bin ]; then
		echo "Restoring Prom Image"
		/usr/sbin/chroot /mnt /sbin/prominst
		ret=$?
	fi
	return $ret	
}

partition_swap()
{
	bootenv OSRootPartition "$DEV_S;$DEV_P"
	bootenv OSLoader "$KERN_S;$KERN_P"
	bootenv Upgrade "/dev/$DEV_S"
	bootenv SoftUpgrade "commit"
}

update_raslog_files()
{
	echo "RASLOG" > /mnt/etc/raslog.int
	echo "RASLOG" > /mnt/etc/raslog.ext
	echo "AUDIT" > /mnt/etc/audit.storage
}

validate_firmware_restore()
{
	ret=$STS_OK

	if [ -n "$BADDEV" ]; then
		add_err_status "$FWDL_RUNNING_MSG"
		ret=$STS_ERR
	elif [ -n "$SOFTUPGRADE" ]; then
		add_err_status "$FWDL_RUNNING_MSG"
		ret=$STS_ERR
	elif [ "$UPGRADE" != /dev/$MOUNT_P ]; then
		add_err_status "$FWRESTORE_NOT_NEEDED_MSG"
		ret=$STS_ERR
	else
		ret=$STS_OK
	fi

	return $ret
}

set_bootcmd() 
{
	# downgrade from 3.0.0 to 2.1.x.
	if [ $TO_MAJOR -eq 2 ] && [ $FROM_MAJOR -gt 2 ]; then
		bootenv bootcmd 'setenv bootargs mem=${mem} ${OSLoadOptions};ataboot;bootm 0x400000'	
	else
		#
		# upgrade from 2.1.x to 3.0.0, or from 3.0.0 to 3.0.0 
		# PROM 1.0.17 has new bootm format for callisto platforms
		#
		PROM_VER=`rpm -q prom-8548 --root /mnt`
		PROM_VER=`echo $PROM_VER | cut -f 3 -d '-'`

		case ${PROM_VER} in
			1.0.*)
				bootenv bootcmd 'setenv bootargs mem=${mem} ${OSLoadOptions};ataboot;makesinrec 0x1000000;bootm 0x400000'	
				;;
			*)
				bootenv bootcmd 'setenv bootargs mem=${mem} ${OSLoadOptions};ataboot 0x2000000;makesinrec 0x3000000;bootm 0x2000000'	
				;;
		esac
	fi
}

#Update the raslog files so that the new raslog messages
#during firmware restore will also be updated
update_raslog_files

#Restore the prom image of the secondary partition
prom_restore
if [ $? -ne $STS_OK ]; then
	echo "Restoration of Prom image of the secondary partition has failed"
	exit $STS_ERR
fi

#Update the bootcmd for callisto
is_callisto
if [ $? == 1 ]; then
	set_bootcmd
fi

exit $STS_OK
