#!/bin/sh
#
#    Copyright (c) 2016 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    Description:
#		This is a different flavor of postinstall checking script.
#		Essentially it is intended to make easier the
#		Compatibility checking of newly introduced features
#		which are introduced in new releases but also
#		back ported to Older maint/patch release versions as well
#
#		The current postinstall operation design is to always run the 
#		postinstall of the higher of the two versions.
#		This does not lend itself to checking whether
#		the new firmware being downloaded supports a given feature,
#		except through a complex specific version checking.
#
#		This scheme requires such new features to be identified by
#		a tag in postinstall script that helps identify if the new release
#		being downloaded supports the given feature or not.
#
#		It is important that each feature compatibility check
#		- Appends the corresponding error message to BOTH  ERROR/STATUS FILES
#		  STATUS_FILE and BNA_STATUS_FILE
#		- Increments the return code count (or alternately set it to non zero)
#		- return STS_ERR (this is not required but recommended for consistency)
#		This will permit a one pass checking of all features
#		And a cumulative message reflecting all corrective actions.
##############################################################################
 
rc=$STS_OK

# Do not use NEW_POSTINST_FILE. This points to latest firmware release postinst
NEW_POSTINST_FILE=$1		# This is the postinst file of the new version being downloaded.
					# It indicates if it supports these new features:
					# - ZENTRON 4 CP, 8548 Rev 31 CPU
					# - nonDFE
					# Optimized BE trunk deskew

MNT_POSTINST="/mnt/sbin/postinst" # This is the new firmware being downloaded
POSTINST="/sbin/postinst"		  # This is the current / running firmware
AUTH_SECRET_CONVERT_SUPPORT="auth_secretconvert" # For checking the AUTH secret conversion support.



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

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

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

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

STS_OK=0
STS_ERR=255

RET_CODE=${STS_OK}
RET=${STS_OK}

export CHASSIS_ROLEID=0
if /fabos/bin/fosconfig --show | grep "Virtual Fabric" | grep enabled > /dev/null 2>&1 ; then
    VF_ENABLED=$STS_ERR;
else
    VF_ENABLED=$STS_OK;
fi

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

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

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

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

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

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

if [ $(ha_role) == "ACTIVE" ]; then
    ACTIVECP=1
	STANDBYCP=0
else
	STANDBYCP=1
fi

ha_state() {
    sync=`/fabos/cliexec/hashow | sed -n -e 's/^.\+\(State sync\).\+$/\1/gp'`
    if [ "$sync" != "State sync" ]; then
	    printf "NOSYNC"
    else
	    printf "SYNC"
    fi
}

HA_STATE=$(ha_state)

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

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

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

CONTEXTS=""

CHASSISCMD=""
cliidx=0
export PATH=/fabos/link_bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/link_abin:/fabos/link_sbin:/fabos/link_rbin:/fabos/factory:/fabos/xtool
export VFROLEMAP=-1:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0

glb_ls_id=-1
glb_vf_id=255
def_vf_id=128

cmd_chassis() {

  context_switch chassis

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

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

swbd=`sin | awk ' {print $2} ' | grep SWBD | sed 's@,@@'`
check_be_trunk_deskew_supported_and_modify()
{
	if [ $STANDBYCP -eq 1 ] ; then
		# Allegiance and Venator Specific
		if [ $swbd == "SWBD165" -o $swbd == "SWBD166" ]; then
			c4_be_trunk_deskew_optimized=`grep -c "C4_BE_TRUNK_DESKEW_OPTIMIZED" $MNT_POSTINST`
			if [ "$c4_be_trunk_deskew_optimized" -eq 0 ]; then
				# The new release does not support this feature. So invoke the BE
				# deskew update API
				correcthost /fabos/rbin/be_trunk_deskew
			fi
		fi
	fi

	return $STS_OK;
}

BSL_supported_and_cleanup()
{
	bsl_supported=`grep -c "BSN_SUPPORT_LINK_SUPPORTED" $MNT_POSTINST`
	if [ "$bsl_supported" -eq 0 ]; then
		# The new release does not support BSL
        # clean up all config entries
        for key in `grep "http\.sl\." /etc/fabos/fabos.0.conf | cut -f 1 -d':'`; do
            correcthost /fabos/cliexec/config remove $key
        done
        correcthost /fabos/cliexec/configcommit
	fi

	return $STS_OK;
}

swbd=`sin | awk ' {print $2} ' | grep SWBD | sed 's@,@@'`
check_vc_mode_update()
{

	# Include all C3 and C4 platform here..
	#SWBDS       += 109      # Stinger
	#SWBDS       += 117      # Pharos
	#SWBDS       += 118      # Tomtoo
	#SWBDS       += 129      # Bulova2
	#SWBDS       += 130      # Superhawk3
	#SWBDS       += 149      # Kestrel3
	#SWBDS       += 150      # Falcon3
	#SWBDS       += 156      # Redbird
	#SWBDS       += 157      # Graphite
	#SWBDS		 += 158      # Carbon

	#SWBDS       += 167      # Shenlong

	#SWBDS       += 148      # Skybolt
	
	#SWBDS       += 62       # Zentron CP
	#SWBDS       += 77       # Zentron on Pluto
	#SWBDS       += 133      # Odin

	#SWBDS       += 141      # Yoda
	#SWBDS       += 142      # Yoda

	#SWBDS       += 161      # Wedge
	#SWBDS       += 162      # Wedge_64
	#SWBDS       += 169      # Chewbacca
	#SWBDS       += 170      # Chewbacca 24 port

	#SWBDS       += 165      # Venator
	#SWBDS       += 166      # Allegiance

	c3_c4_vc_mode_is_weight_based=`grep -c "C3_C4_VC_MODE_IS_WEIGHT_BASED" $MNT_POSTINST`
	if [ "$c3_c4_vc_mode_is_weight_based" -eq 0 ]; then
		case ${SWBD##SWBD} in 
			'62' | '77' | '109' | '117' | '118' | '129' | '130' | '133' | \
			'141' | '142' | '148' | '149' | '150' | '156' | '157' | '158' | '161' | \
			'162' | '165' | '166' | '167' | '169' | '170')
					# The new release does not support vc weight method. So
					# invoke API to clean-up the weight and set back to
					# bandwidth mode
					correcthost /fabos/rbin/update_vc_mode
	    	;;
		*)
	    	;;
		esac
	fi
	return $STS_OK;
}



#Check if active is >= 8.0.1 to verify /fabos/bin/userhashchk exists
#If not, active has already downgraded, required changes already done 
#Check for factory entry, if already found, changes already run from active/standby
#No need to invoke changes again
check_active_security_conversion_support()
{
	if [ $VF_ENABLED -eq $STS_OK ]; then
		# VF disabled
		RSH_CMD="/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CURRENT_AD=0"
	else
		# VF enabled, for_all_context changed glb_ls_id and glb_vf_id to each logical switch's
		RSH_CMD="/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 FABOS_SWITCHNO=$glb_ls_id CURRENT_VF=$glb_vf_id CURRENT_AD=0"
	fi
	proceed1=1
	if [ $ACTIVECP ]; then
		proceed1=0
	else

		# Check/RSH_CMD if active CP has userhashchk
    		userhashchk_present_on_active=`$RSH_CMD /bin/ls /fabos/bin/userhashchk 2> /dev/null`
	    	if [ ! -z "$userhashchk_present_on_active" ]; then
			proceed1=0
		fi
	fi
	proceed2=`cat /etc/shadow | /bin/grep -c "^factory:"`

	if [ $proceed1 -eq 0 ] && [ $proceed2 -eq 0 ]; then
		return $STS_OK
	else
		return $STS_ERR
	fi
}

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

	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
	if [ $new_fw_is_SV -eq 0 ]; then
		new_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	fi	
	if [ $cur_fw_is_SV -eq 0 ]; then
		cur_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $POSTINST) # grep in postinst of Current fw
	fi	
	
	if [ $cur_fw_is_SV -gt 0 ]; then
		#Backward Conversion
		if [ $new_fw_is_SV -eq 0 ]; then
			#Password Conversion - UID Backward Conversion
			correcthost_to_curr_vfid /fabos/libexec/passwd_convert /mnt/etc/passwd FWDL_CONVERSION UID_BACKWARD_CONVERSION > /dev/null 2>&1
			correcthost_to_curr_vfid /bin/cp /mnt/etc/passwd /etc/passwd > /dev/null 2>&1
			correcthost_to_curr_vfid /fabos/cliexec/config save /etc/passwd 
			#Group Conversion - UID Backward Conversion
			correcthost_to_curr_vfid /fabos/libexec/group_convert /mnt/etc/group FWDL_CONVERSION UID_BACKWARD_CONVERSION > /dev/null 2>&1
			correcthost_to_curr_vfid /bin/cp /mnt/etc/group /etc/group > /dev/null 2>&1
			correcthost_to_curr_vfid /fabos/cliexec/config save /etc/group
			#Permission correction for home directories
			pkgname=`/bin/rpm -qf /fabos/users/user --root /mnt`
			/usr/sbin/chroot /mnt /bin/rpm --setugids $pkgname > /dev/null 2>&1
			if [ $? -ne 0 ]; then
				#Permission correction for home directories
				/usr/sbin/chroot /mnt /bin/chown -R root:user /fabos/users/switchadmin
				/usr/sbin/chroot /mnt /bin/chown -R root:user /fabos/users/user
				/bin/grep "^factory" /mnt/etc/passwd > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					if [ -d /mnt/fabos/users/diag ]; then
						/usr/sbin/chroot /mnt /bin/chown -R root:factory /fabos/users/diag
					fi
				fi
			fi
		fi
	fi
}

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

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

	if [ $cur_fw_is_SV -gt 0 ]; then
		#Backward Conversion
		if [ $new_fw_is_SV -eq 0 ]; then
			#Password Conversion - Invalid roles add
			correcthost_to_curr_vfid /fabos/libexec/passwd_convert /mnt/etc/passwd FWDL_CONVERSION INVALID_ROLES_ADDITION > /dev/null 2>&1
			correcthost_to_curr_vfid /bin/cp /mnt/etc/passwd /etc/passwd > /dev/null 2>&1
			correcthost_to_curr_vfid /fabos/cliexec/config save /etc/passwd
			#Group Conversion - Invalid roles add
			correcthost_to_curr_vfid /fabos/libexec/group_convert /mnt/etc/group FWDL_CONVERSION INVALID_ROLES_ADDITION > /dev/null 2>&1
			correcthost_to_curr_vfid /bin/cp /mnt/etc/group /etc/group > /dev/null 2>&1
			correcthost_to_curr_vfid /fabos/cliexec/config save /etc/group 
		fi
	fi
}

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

	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
	if [ $new_fw_is_SV -eq 0 ]; then
		new_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	fi	
	if [ $cur_fw_is_SV -eq 0 ]; then
		cur_fw_is_SV=$(grep -c $TATOOINE_SUPPORT $POSTINST) # grep in postinst of Current fw
	fi	
	
	if [ $cur_fw_is_SV -gt 0 ]; then
		#Backward Conversion
		if [ $new_fw_is_SV -eq 0 ]; then
			#DefAcct Passwd add
			check_active_security_conversion_support
			if [ "$?" -eq $STS_OK ]; then	
				#Add back passwords of default accts to /passwd
				type=8
				correcthost_to_curr_vfid /fabos/bin/userhashchk $type 
				stat=$?
				if [ $stat -ne 0 ]; then
					echo "Default Acct Passwd Update failed."
				fi
			fi
		fi
	fi
}

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

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

	if [ $cur_fw_is_SV -gt 0 ]; then
		#Backward Conversion
		if [ $new_fw_is_SV -eq 0 ]; then
			#Factory addition to passwd,shadow,userdb
			check_active_security_conversion_support
			if [ "$?" -eq $STS_OK ]; then	
				if [ $VF_ENABLED -eq $STS_OK ]; then
					# VF disabled
					RSH_CMD="/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CURRENT_AD=0"
				else
					# VF enabled, for_all_context changed glb_ls_id and glb_vf_id to each logical switch's
					RSH_CMD="/usr/bin/rsh -n $(otherhost) ROLE_ID=root LOGIN_ID=root CHASSIS_ROLEID=0 FABOS_SWITCHNO=$glb_ls_id CURRENT_VF=$glb_vf_id CURRENT_AD=0"
				fi

				#Add back "factory" account entry to /etc/passwd, /etc/shadow
				rand_pass=`/usr/bin/openssl rand 16 -base64 2> /dev/null`
				if [ $ACTIVECP ]; then
					correcthost_to_curr_vfid /bin/grep "^factory:" /etc/passwd | /bin/grep "^factory:" > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
					then 
						correcthost_to_curr_vfid echo "factory:$rand_pass:0:601:Diagnostics:/fabos/users/diag:/bin/rbash" >> /etc/passwd
					fi
					correcthost_to_curr_vfid /bin/grep "^factory:" /etc/shadow | /bin/grep "^factory:" > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
					then 
						correcthost_to_curr_vfid echo "factory:$rand_pass:::::::" >> /etc/shadow
					fi
					correcthost_to_curr_vfid /fabos/cliexec/config save /etc/shadow
					correcthost_to_curr_vfid /fabos/cliexec/config save /etc/passwd			
				else
					$RSH_CMD "/bin/grep \"^factory:\" /etc/passwd" | /bin/grep "^factory:" > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
					then 
						$RSH_CMD "echo \"factory:$rand_pass:0:601:Diagnostics:/fabos/users/diag:/bin/rbash\" >> /etc/passwd"
					fi
					$RSH_CMD "/bin/grep \"^factory:\" /etc/shadow" | /bin/grep "^factory:" > /dev/null 2>&1; ret=$?; if [ $ret -ne 0 ]; 
					then 
						$RSH_CMD "echo \"factory:$rand_pass:::::::\" >> /etc/shadow"
					fi	
					$RSH_CMD /fabos/cliexec/config save /etc/shadow
					$RSH_CMD /fabos/cliexec/config save /etc/passwd
				fi

				#Add back "factory" account entry to user.db	
				if [ $VF_ENABLED -ne $STS_OK ]; then
					#VF enabled
					part1="INSERT INTO user VALUES('factory',128,-1"
					i=1
					val=601
					ads=""
					while [ $i -le 255 ]; do
						ads=$ads",$val"
						i=`expr $i + 1`
					done
					part3=",0,'',0,0,'',0,0);"
					sqlbuf=$part1$ads$part3	
				else
					#VF disabled
					part1="INSERT INTO user VALUES('factory',0,1"
					i=1
					val=1
					ads=""
					while [ $i -le 255 ]; do
						ads=$ads",$val"
						i=`expr $i + 1`
					done
					part3=",0,'',0,0,'',0,0);"
					sqlbuf=$part1$ads$part3	
				fi
				type=5
				if [ $ACTIVECP ]; then
					correcthost_to_curr_vfid /fabos/bin/userhashchk $type "$sqlbuf"
	   				# if the platform is chassis execute below on standby
					chassis=`/fabos/cliexec/hashow | grep -c "Not supported"`
	    				if [ $chassis -eq 0 ]; then
						$RSH_CMD /bin/cp /mnt/etc/fabos/user.db /etc/fabos/user.db
					fi
				else
					correcthost_to_curr_vfid /fabos/bin/userhashchk $type \"$sqlbuf\"
					/bin/cp /mnt/etc/fabos/user.db /etc/fabos/user.db
				fi
				stat=$?
				if [ $stat -ne 0 ]; then
					echo "Adding factory account to user db failed"
				fi

				#Group Conversion - Factory add
				correcthost_to_curr_vfid /fabos/libexec/group_convert /mnt/etc/group FWDL_CONVERSION FACTORY_ADDITION > /dev/null 2>&1
				correcthost_to_curr_vfid /bin/cp /mnt/etc/group /etc/group > /dev/null 2>&1
				correcthost_to_curr_vfid /fabos/cliexec/config save /etc/group
			fi
		fi
	fi
}

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

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

	if [ $cur_fw_is_SV -gt 0 ]; then
		#Backward Conversion
		if [ $new_fw_is_SV -eq 0 ]; then
			#Passwd history hash check
			check_active_security_conversion_support
			if [ "$?" -eq $STS_OK ]; then	
				#Clear passwd history if it contains non-md5 hashes
				type=7
				correcthost_to_curr_vfid /fabos/bin/userhashchk $type 
				stat=$?
				if [ $stat -ne 0 ]; then
					echo "Clearing Password history failed."
				fi
			fi
		fi
	fi
}

#ACCESS_TIME_SUPPORTED="Version Supports Access Time feature"
access_time_conversion()
{
	#******Accesstime conversion	
	new_fw_is_SV=$(grep -c "ACCESS_TIME_SUPPORTED" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "ACCESS_TIME_SUPPORTED" $POSTINST)    # grep in postinst of Current fw

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

	#Backward Conversion
	if [ $cur_fw_is_SV -gt 0 ]; then
		if [ $new_fw_is_SV -eq 0 ]; then	
			#Time.conf removal
			if [ -e /etc/time.conf ]; then
				size=`/bin/ls -la /etc/time.conf | /bin/awk ' { print $5 } '`
				/bin/dd if=/dev/zero of=/etc/time.conf bs=1 count=$size 2> /dev/null
				/bin/rm /etc/time.conf
			fi
			if [ -e /mnt/etc/time.conf ]; then
				size=`/bin/ls -la /mnt/etc/time.conf | /bin/awk ' { print $5 } '`
				/bin/dd if=/dev/zero of=/mnt/etc/time.conf bs=1 count=$size 2> /dev/null
				/bin/rm /mnt/etc/time.conf
			fi
		fi
	fi
}

handle_pam_conf_v2() {

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

CHASSISCMD="cmd_chassis"
AUTHSPECMODE=`$CHASSISCMD /fabos/bin/configshow -all | grep authspec.mode | sed -e "s/authspec.mode://g"`

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

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

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

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

#AUTHSECRET_CONVERSION_SUPPORTED="Version Supports Auth Secret Update"
authsecret_conversion()
{
	#******Authsecret Conversion
	new_fw_is_SV=$(grep -c $AUTH_SECRET_CONVERT_SUPPORT $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c $AUTH_SECRET_CONVERT_SUPPORT $POSTINST)    # grep in postinst of Current fw
	
	# 8.0.1 supports above feature but not feature tag
	# Look for special string in postinstall 
	# to detect feature support
		
	if [ $cur_fw_is_SV -gt 0 ]; then
		#Backward Conversion
		 
		
		if [ $new_fw_is_SV -eq 0 ]; then
			if [ $ACTIVECP ]; then
			/fabos/libexec/auth_secretconvert 8.0 7.4 > /dev/null 2>&1
			elif [ $STANDBYCP -eq 1 ]; then
			correcthost_to_curr_vfid /fabos/libexec/auth_secretconvert 8.0 7.4 > /dev/null 2>&1
			/fabos/libexec/auth_secretconvert 8.0 7.4 > /dev/null 2>&1
			fi

			for f in /etc/fabos/auth.[0-7].conf
			do
				if [ -e $f ]; then
					correcthost_to_curr_vfid /bin/cp /mnt$f $f > /dev/null 2>&1
					/bin/cp /mnt$f $f > /dev/null 2>&1
				fi
			done
		fi
	fi
}

#RBAC_UPDATE_SUPPORTED="Version Supports RBAC Update"
rbac_conversion()
{
	#******Rbac and Userdb Update
	new_fw_is_SV=$(grep -c "RBAC_UPDATE_SUPPORTED" $MNT_POSTINST) # grep in postinst of New fw
	cur_fw_is_SV=$( grep -c "RBAC_UPDATE_SUPPORTED" $POSTINST)    # grep in postinst of Current fw

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

	if [ $cur_fw_is_SV -gt 0 ]; then
		#Backward Conversion
		if [ $new_fw_is_SV -eq 0 ]; then
			#Rbac and Userdb Update
			correcthost_to_curr_vfid /bin/mv /etc/fabos/rbac/dynamic.default /etc/fabos/rbac/org_dynamic.default
			correcthost_to_curr_vfid /bin/cp /mnt/etc/fabos/rbac/dynamic.default /etc/fabos/rbac/dynamic.default
			correcthost_to_curr_vfid /fabos/libexec/trig_userdb_merge /mnt/etc/fabos/rbac/dynamic 8.0.1 7.4.0
			correcthost_to_curr_vfid /bin/cp /mnt/etc/fabos/rbac/dynamic /etc/fabos/rbac/dynamic
			correcthost_to_curr_vfid /bin/mv /etc/fabos/rbac/org_dynamic.default /etc/fabos/rbac/dynamic.default
		fi
	fi
}

# Sync passwd file if / and /mnt have different files
# To resolve /passwd file overwrite during RPM installation
passwd_file_sync()
{
	#Passwd file sync
	primsum=`/usr/bin/md5sum /etc/passwd | /usr/bin/cut -d ' ' -f 1`
	secsum=`/usr/bin/md5sum /mnt/etc/passwd | /usr/bin/cut -d ' ' -f 1`
	if [ "$primsum" != "$secsum" ]; then
		/bin/cp /etc/passwd /mnt/etc/passwd
	fi
}
#Modify File Permissions as required
file_permission_modifications()
{
	#File Permission Updates
	#Change file ppermisson to security config files after upgrade to 8.0.1 or above.
	
	filelist_perm_400="/etc/fabos/certs/sw0/pvt_key"

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

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


}

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

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

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



# saveNoFuseModelpsnewfwver()
# Parse .bin (binary executable) filenames for
# the PSU's firmware versions
# And Save the psu's new firmware versions in /etc/fabos/psnewfwver
# in the following format:	
# Mm
#	where	M = Major Version#, m = minor version# for the PSU's new firmware image
#	Example:
#	If the new dist has these PSU new firmware version files:
#		VKA_00104_0F1_02_01_20150608_1118.elf.S - Primary Intake
#		VKA_00104_0F2_02_03_20150608_1128.elf.S - Secondary Intake
#		
#	Then this function will save the parsed version number
# 	in file /mnt/etc/fabos/psnewfwver as
#	21
#
saveNoFuseModelpsnewfwver()
{
	cd /mnt/fabos/factory
	PriMajIn=$(ls VKA_00104_0F1*.elf.S 2>&1 | awk -F'_' '{printf "%1d", $4}')
	PriMinIn=$(ls VKA_00104_0F1*.elf.S 2>&1 | awk -F'_' '{printf "%1d", $5}')
	SecMajIn=$(ls VKA_00104_0F2*.elf.S 2>&1 | awk -F'_' '{printf "%1d", $4}')
	SecMinIn=$(ls VKA_00104_0F2*.elf.S 2>&1 | awk -F'_' '{printf "%1d", $5}')
	PriMajEx=$(ls VKA_00105_0F1*.elf.S 2>&1 | awk -F'_' '{printf "%1d", $4}')
	PriMinEx=$(ls VKA_00105_0F1*.elf.S 2>&1 | awk -F'_' '{printf "%1d", $5}')
	SecMajEx=$(ls VKA_00105_0F2*.elf.S 2>&1 | awk -F'_' '{printf "%1d", $4}')
	SecMinEx=$(ls VKA_00105_0F2*.elf.S 2>&1 | awk -F'_' '{printf "%1d", $5}')
	cd -

	if [ -z $PriMajIn ]; then PriMajIn=0; fi
	if [ -z $PriMinIn ]; then PriMinIn=0; fi
	if [ -z $PriMajIn ]; then PriMajIn=0; fi
	if [ -z $PriMinIn ]; then PriMinIn=0; fi
	if [ -z $PriMajEx ]; then PriMajEx=0; fi
	if [ -z $PriMinEx ]; then PriMinEx=0; fi
	if [ -z $PriMajEx ]; then PriMajEx=0; fi
	if [ -z $PriMinEx ]; then PriMinEx=0; fi

	echo $PriMajIn$PriMinIn$SecMajIn$SecMinIn$PriMajEx$PriMinEx$SecMajEx$SecMinEx > /mnt/etc/fabos/psnewfwver
}

#
# main()
#
echo > $STATUS_FILE      # Clear the error file
echo > $BNA_STATUS_FILE  # Clear the BNA error file
echo "Please address the following before downloading the specified firmware:" >> $STATUS_FILE

# Taggged features Post install updates begin here:

check_be_trunk_deskew_supported_and_modify
check_vc_mode_update


TATOOINE_SUPPORT="passwdcfg.hash"
#*****Passwd File Sync
passwd_file_sync

#******UID Conversion
uid_conversion

#******Invalid Accts Conversion
invalid_accounts_conversion

#******DefAcct Passwd Conversion
default_account_passwd_update

#******Factory Conversion
factory_conversion

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

#******Accesstime conversion	
access_time_conversion

#******Handle Pam conf
pam_conf_conversion

#******Authsecret Conversion
authsecret_conversion

#******Rbac db Update
rbac_conversion

#******File Permission Updates
file_permission_modifications

# Save PSU's New firmware version in  /etc/fabos/psnewfwver
if [ $swbd == "SWBD165" -o $swbd == "SWBD166" ]; then
	savepsnewfwver
fi
if [ $swbd == "SWBD133" -o $swbd == "SWBD148" -o  $swbd == "SWBD171" ]; then
	saveNoFuseModelpsnewfwver
fi

BSL_supported_and_cleanup

exit $rc
