#!/bin/bash
#
#    Copyright (c) 2005-2016 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    Description:
#
#   The postinst script will be run after the firmware has been
#   downloaded to the "/mnt" partition but before the reboot takes
#   place. In a chassis, this script will be run on both of the
#   MMs.
#
#   Firmwaredownload will choose the newer postinst script to run
#   by comparing the major, minor, and patch numbers of the running
#   firmware on the "/" partition, and just-downloaded firmware on
#   the "/mnt" partition. If the running firmware is newer, it will
#   run the postinst script from the "/" partition. If the running
#   firmware is older or the same as the just-downloaded firmware,
#   it will run the postinst script from the "/mnt" partition.
#
#   Any post-processing to complete firmwaredownload can be done here.
#
PATH=/bin:/usr/bin:/sbin:/usr/sbin
export TZ="UTC"
FIPS_CONF_FILE=/etc/fabos/fips_selftests.conf

SHADOW_FILE=/etc/shadow
SHADOW_FILE_MNT=/mnt/etc/shadow

STS_OK=0
STS_ERR=255

CAT=/bin/cat
MV=/bin/mv

PAM_TIME_CONF=/etc/time.conf
INETD_DEBUG_LOG=/var/log/loginDebug.log
size=0

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

if [ "$DEBUG_PAM_TIME" == 1 ]; then
	if [ -f "$INETD_DEBUG_LOG" ]; then
    	size=`/usr/bin/wc -c < $INETD_DEBUG_LOG`
	fi
    if [ "$size" -ge 50000 ]; then
        $ECHO "Flushing file into its backup" >> $INETD_DEBUG_LOG
        $MV $INETD_DEBUG_LOG /var/log/loginDebug.log.1
    fi
    $ECHO   >> $INETD_DEBUG_LOG
    $ECHO "Start date : `date`" >> $INETD_DEBUG_LOG
	if [ -f "$PAM_TIME_CONF" ]; then
    	$CAT $PAM_TIME_CONF >> $INETD_DEBUG_LOG 2>/dev/null
	fi
fi

#
# copied from /fabos/src/setup/profile
#
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
}


setcontext()
{
    if [ "$1" != "chassis" ]
    then
		export FABOS_SWITCHNO=$2
		export CURRENT_VF=$1
		export CHASSIS_ROLEID=0
    else
		export FABOS_SWITCHNO=-1
		export CURRENT_VF=255
		export CHASSIS_ROLEID=0
    fi
	export ROLE_ID=root
}

p2_install()
{
	/bin/mknod /dev/sdb3 b 8 3
	/bin/mknod /dev/sdb4 b 8 4

	/bin/mkdir -p /mnt2
	for dev in /dev/sdb3 /dev/sdb4; do
		/sbin/mke2fs -t ext4 -g32768 -b4096 -j $dev
		/bin/mount -t ext4 $dev /mnt2
		/bin/rsync -rlpgoDxt --rsh=/usr/bin/rsh --delete --ignore-errors --timeout=60 /mnt/ /mnt2
		umount /mnt2
	done
	/bin/rmdir /mnt2
	/bin/mknod /dev/nvram1 c 10 145
	cat /dev/nvram0 > /dev/nvram1
}

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

ha_insync()
{
    /fabos/cliexec/hashow | while read ha; do
        case $ha in
            *State*synchronized*)
                return 1;
            ;;
            *)
                return 0;
            ;;
        esac
    done
    return $?
}


#
# Passed in version numbers
#
TO_MAJOR=$1
TO_MINOR=$2
TO_PATCH=$3
TO_RID=$4
OUTPUT=$5       # output tty
TO_REVISION=$6
FLAG=$7

#load addresses
Linux_Load_Addr="0x78000000"
fslHV_Load_Addr="0x2000000"
HVdtb_Load_Addr="0x3000000"
HWdtb_Load_Addr="0x4000000"

# Retrieve the current system platform identifier.
sw_platform=`/sbin/sin 2>/dev/null | sed -n 's/^.*SWBD\([^,]*\),.*/\1/p'`

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%%[a-z_]*}
FROM_REVISION=`cat /etc/version.conf | grep IntNum | awk '{print $2}'`

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



#
# Default the output tty to console if
# it is not passed in
#
if [ -z $OUTPUT ]; then
    OUTPUT=/dev/ttyS0
fi

$ECHO Requested version is ${TO_MAJOR}.${TO_MINOR}.${TO_PATCH}
$ECHO Requested version string is ${TO_RID}
$ECHO Standard output is ${OUTPUT}
$ECHO Current version is ${FROM_MAJOR}.${FROM_MINOR}.${FROM_PATCH}

# untar ras man pages
if [[ -e /mnt/fabos/man/cat7/rasman.tar ]]; then
 tar -xf /mnt/fabos/man/cat7/rasman.tar -C /mnt/fabos/man/cat7/ 2>/dev/null
 > /mnt/fabos/man/cat7/rasman.tar
 gunzip /mnt/fabos/man/cat7/*.gz 2>/dev/null
 rm -f /mnt/fabos/man/cat7/*.gz 2>/dev/null
else
  echo "rasman.tar does not exist."
fi

# Update /mnt/etc/hosts if it doesn't contain 127.2 addresses
grep "127.2" /mnt/etc/hosts > /dev/null
if [ $? == 1 ]; then
	sed  '/127.1/d' /mnt/etc/hosts > /tmp/hosts
	cat /mnt/etc/hosts.nos >> /tmp/hosts
	mv /tmp/hosts /mnt/etc/hosts
fi

# This function compares the version of both primary and secondary partition
# and returns the following values
# -1 : if primary partition is of higher version
#  0 : if both the partions have same version
#  1 : if secondary partion is of higher version
check_new_version()
{
      ret=0
      if [ $FROM_MAJOR -gt $TO_MAJOR ] ; then
              ret=-1
      elif [ $FROM_MAJOR -lt $TO_MAJOR ] ; then
              ret=1
      elif [ $FROM_MINOR -gt $TO_MINOR ] ; then
              ret=-1
      elif [ $FROM_MINOR -lt $TO_MINOR ] ; then
              ret=1
      elif [ $FROM_PATCH -gt $TO_PATCH ] ; then
              ret=-1
      elif [ $FROM_PATCH -lt $TO_PATCH ] ; then
              ret=1
      else
              ret=0
      fi

      $ECHO check_new_version. Ret ${ret}
      return $ret
}


check_OpenSSH_75()
{
    ret=0
    if ([ $TO_MAJOR -ge 7 ] && [ $TO_MINOR -ge 3 ] && [ $TO_PATCH -ge 0 ] && [ $TO_REVISION -ge 3 ]); then
	ret=1
    elif ([ $TO_MAJOR -ge 7 ] && [ $TO_MINOR -gt 3 ]); then
	ret=1
    elif [ $TO_MAJOR -gt 7 ]; then
	ret=1
    else
	ret=0 
    fi
    $ECHO check_OpenSSH_75. Ret ${ret}
    return $ret
}

check_OpenSSH_62()
{
   ret=0
    
   if ([ $TO_MAJOR -le 7 ] && [ $TO_MINOR -lt 3 ] || [ $TO_MAJOR -lt 7 ]); then
        ret=1
   elif ([ $TO_MAJOR -eq 7 ] && [ $TO_MINOR -eq 3 ] && [ $TO_PATCH -eq 0 ] && [ $TO_REVISION -lt 3 ]); then
        ret=1
   else
        ret=0
   fi
   $ECHO check_OpenSSH_62. Ret ${ret}
   return $ret   
}

Write_SSH_75_Config()
{
   file=$1
   
   /bin/grep "^LoginGraceTime 120" $file > /dev/null 2>&1
   if [ $? -ne 0 ]; then
        /bin/grep -v "LoginGraceTime" $ > temp && mv temp $file
        echo "LoginGraceTime 120" >> $file
   fi
   /bin/grep "^ClientAliveCountMax 0" $file > /dev/null 2>&1
   if [ $? -ne 0 ]; then
       /bin/grep -v "ClientAliveCountMax" $file > temp && mv temp $file
       echo "ClientAliveCountMax 0" >> $file
   fi
   /bin/grep "^ClientAliveInterval 0" $file > /dev/null 2>&1
   if [ $? -ne 0 ]; then
      /bin/grep -v "ClientAliveInterval" $file > temp && mv temp $file
      echo "ClientAliveInterval 0" >> $file
   fi
   /bin/grep "^MaxAuthTries 6" $file > /dev/null 2>&1
   if [ $? -ne 0 ]; then
     /bin/grep -v "MaxAuthTries" $file > temp && mv temp $file
     echo "MaxAuthTries 6" >> $file
   fi
   /bin/grep "^RekeyLimit 1023M" $file > /dev/null 2>&1
   if [ $? -ne 0 ]; then
       /bin/grep -v "RekeyLimit" $file > temp && mv temp $file
       echo "RekeyLimit 1023M" >> $file
   fi
   /bin/grep "^PermitRootLogin yes" $file 2>&1 > /dev/null
   if [ $? -ne 0 ]; then
      /bin/grep -v "PermitRootLogin" $file > temp && mv temp $file
      echo "PermitRootLogin yes" >> $file
   fi
   /bin/grep -v "PrintLastLog" $file > temp && mv temp $file
   /bin/grep -v "UsePrivilegeSeparation" $file > temp && mv temp $file
   /bin/grep -i "CACertificateFile" $file 2>&1 > /dev/null
   if [ $? -ne 0 ]; then
        /bin/grep -v "CACertificateFile" $file > temp && mv temp $file
       echo "#CACertificateFile /etc/fabos/certs/commoncert/ca.cert.pem" >> $file
   fi
 
}

Write_SSH_62_Config()
{
   file=$1

   /bin/grep -v "LoginGraceTime" $file > temp && mv temp $file
   /bin/grep -v "RekeyLimit" $file > temp && mv temp $file
   /bin/grep -v "PermitRootLogin" $file > temp && mv temp $file
   /bin/grep -i "^PrintLastLog" $file
   if [ $? -ne 0 ]; then
        /bin/grep -v "PrintLastLog" $file > temp && mv temp $file
        echo "PrintLastLog no" >> $file
   fi
   /bin/grep -i "^UsePrivilegeSeparation" $file
   if [ $? -ne 0 ]; then
       /bin/grep -v "UsePrivilegeSeparation" $file > temp && mv temp $file
       echo "UsePrivilegeSeparation no" >> $file
   fi
   /bin/grep -i "^X509KeyAlgorithm" $file
   if [ $? -ne 0 ]; then
       /bin/grep -v "X509KeyAlgorithm" $file > temp && mv temp $file
   fi
   /bin/grep -v "^HostKey /etc/ssh_host_x509_rsa_key" $file > temp && mv temp $file
   /bin/grep -v "CACertificateFile" $file > temp && mv temp $file
}

check_new_version
if [ $? -lt 0 ] ; then
	/mnt/bin/bash /sbin/fwclean -o -s
else
	/mnt/bin/bash /mnt/sbin/fwclean -o -s
fi

#############################################################################################################################
#                                                                                                                           #
# Creation of new files or conditional check needs to be added after this.                                                  #
#                                                                                                                           #
# The cleaup script should run before the creation of new files(If any) by this script.                                     #
#                                                                                                                           #
#############################################################################################################################

if [ -f "/fabos/cliexec/config" ] ; then
    /fabos/cliexec/config set ipfilter.0.rule.11 5 0,0x63,0,0,6,600,65535
    /fabos/cliexec/config set ipfilter.0.rule.12 5 0,0x63,0,0,17,600,65535
    /fabos/cliexec/config set ipfilter.1.rule.11 5 0,0x63,0,0,6,600,65535
    /fabos/cliexec/config set ipfilter.1.rule.12 5 0,0x63,0,0,17,600,65535
    /fabos/cliexec/config update 
fi

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

# Recreate the trace dump file for the appropriate platforms.  These values must
# match those in the trace .c files.
# simply cannot run a binary in secondary partition due to a toolchain and libc
# change. FIXME!
trace_create_dump_file()
{
if [ -f '/fabos/cliexec/traceCreateDb' ] ;then
    /fabos/cliexec/traceCreateDb ${SWBD##SWBD}
fi
}

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

#
# AAA will be loaded from DCMd. Remove aaa_init.xml file if exists.
#
/bin/rm -f /mnt/var/confd/cdb/aaa_init.xml

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

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

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

$ECHO "Handling PAM login configuration files"

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

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

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

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

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

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

sync
}

handle_pam_conf_v2() {
CONF_DIR=/mnt/etc/pam.d
CONSOLE_CONF=ttylogin
NET_CONF=netlogin
SSH_CONF=sshd

AUTHSPECMODE=`cat /etc/fabos/fabos.chassis.conf | grep authspec.mode | sed -e "s/authspec.mode://g"`

echo "handle_pam_conf_v2 : AUTHSPECMODE = $AUTHSPECMODE" >> /var/log/inetdDebug.log
#Local only
if [ $AUTHSPECMODE -eq 0 ]; then
    /bin/cp $CONF_DIR/login.noradius $CONF_DIR/$NET_CONF
    /bin/cp $CONF_DIR/login.noradius /etc/pam.d/$NET_CONF
    /bin/cp $CONF_DIR/login.noradius $CONF_DIR/$CONSOLE_CONF
    /bin/cp $CONF_DIR/login.noradius /etc/pam.d/$CONSOLE_CONF
    /bin/cp $CONF_DIR/sshd.noradius $CONF_DIR/$SSH_CONF
    /bin/cp $CONF_DIR/sshd.noradius /etc/pam.d/$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 /etc/pam.d/$NET_CONF
    /bin/cp $CONF_DIR/login.radius $CONF_DIR/$CONSOLE_CONF
    /bin/cp $CONF_DIR/login.radius /etc/pam.d/$CONSOLE_CONF
    /bin/cp $CONF_DIR/sshd.radius $CONF_DIR/$SSH_CONF
    /bin/cp $CONF_DIR/sshd.radius /etc/pam.d/$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 /etc/pam.d/$NET_CONF
    /bin/cp $CONF_DIR/login.radius-local $CONF_DIR/$CONSOLE_CONF
    /bin/cp $CONF_DIR/login.radius-local /etc/pam.d/$CONSOLE_CONF
    /bin/cp $CONF_DIR/sshd.radius-local $CONF_DIR/$SSH_CONF
    /bin/cp $CONF_DIR/sshd.radius-local /etc/pam.d/$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 /etc/pam.d/$NET_CONF
    /bin/cp $CONF_DIR/login.radius-local2 $CONF_DIR/$CONSOLE_CONF
    /bin/cp $CONF_DIR/login.radius-local2 /etc/pam.d/$CONSOLE_CONF
    /bin/cp $CONF_DIR/sshd.radius-local2 $CONF_DIR/$SSH_CONF
    /bin/cp $CONF_DIR/sshd.radius-local2 /etc/pam.d/$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 /etc/pam.d/$NET_CONF
    /bin/cp $CONF_DIR/login.adldap $CONF_DIR/$CONSOLE_CONF
    /bin/cp $CONF_DIR/login.adldap /etc/pam.d/$CONSOLE_CONF
    /bin/cp $CONF_DIR/sshd.adldap $CONF_DIR/$SSH_CONF
    /bin/cp $CONF_DIR/sshd.adldap /etc/pam.d/$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 /etc/pam.d/$NET_CONF
    /bin/cp $CONF_DIR/login.adldap-local2 $CONF_DIR/$CONSOLE_CONF
    /bin/cp $CONF_DIR/login.adldap-local2 /etc/pam.d/$CONSOLE_CONF
    /bin/cp $CONF_DIR/sshd.adldap-local2 $CONF_DIR/$SSH_CONF
    /bin/cp $CONF_DIR/sshd.adldap-local2 /etc/pam.d/$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 /etc/pam.d/$NET_CONF
    /bin/cp $CONF_DIR/login.adldap-local $CONF_DIR/$CONSOLE_CONF
    /bin/cp $CONF_DIR/login.adldap-local /etc/pam.d/$CONSOLE_CONF
    /bin/cp $CONF_DIR/sshd.adldap-local $CONF_DIR/$SSH_CONF
    /bin/cp $CONF_DIR/sshd.adldap-local /etc/pam.d/$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 /etc/pam.d/$NET_CONF
    /bin/cp $CONF_DIR/login.tacplus $CONF_DIR/$CONSOLE_CONF
    /bin/cp $CONF_DIR/login.tacplus /etc/pam.d/$CONSOLE_CONF
    /bin/cp $CONF_DIR/sshd.tacplus $CONF_DIR/$SSH_CONF
    /bin/cp $CONF_DIR/sshd.tacplus /etc/pam.d/$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 /etc/pam.d/$NET_CONF
    /bin/cp $CONF_DIR/login.tacplus-local2 $CONF_DIR/$CONSOLE_CONF
    /bin/cp $CONF_DIR/login.tacplus-local2 /etc/pam.d/$CONSOLE_CONF
    /bin/cp $CONF_DIR/sshd.tacplus-local2 $CONF_DIR/$SSH_CONF
    /bin/cp $CONF_DIR/sshd.tacplus-local2 /etc/pam.d/$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 /etc/pam.d/$NET_CONF
    /bin/cp $CONF_DIR/login.tacplus-local $CONF_DIR/$CONSOLE_CONF
    /bin/cp $CONF_DIR/login.tacplus-local /etc/pam.d/$CONSOLE_CONF
    /bin/cp $CONF_DIR/sshd.tacplus-local $CONF_DIR/$SSH_CONF
    /bin/cp $CONF_DIR/sshd.tacplus-local /etc/pam.d/$SSH_CONF
else
    /bin/cp $CONF_DIR/login.noradius $CONF_DIR/$NET_CONF
    /bin/cp $CONF_DIR/login.noradius /etc/pam.d/$NET_CONF
    /bin/cp $CONF_DIR/login.noradius $CONF_DIR/$CONSOLE_CONF
    /bin/cp $CONF_DIR/login.noradius /etc/pam.d/$CONSOLE_CONF
    /bin/cp $CONF_DIR/sshd.noradius $CONF_DIR/$SSH_CONF
    /bin/cp $CONF_DIR/sshd.noradius /etc/pam.d/$SSH_CONF
fi
}


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

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

#
# Check whether dual-partition is supported or not 
#
is_2part_supported()
{
    case ${SWBD##SWBD} in
        '1004' | '1005' | '1006' | '1007' | '1008' | '1009' | '1010' | '1011')
            return 1;;
        *)
            return 0;;
    esac
}

#
# Check whether Dcmd is supported or not 
#
is_dcmd_supported()
{   
    case ${SWBD##SWBD} in
        '62' | '77' | '1000' | '1001' | '95' | '96' | \
        '97' | '105' | '112' | '113' | '116' | '107' | \
        '131'| '137' | '138' | '151' | '153' | '154' | '155' | '164' )
            return 1;;
        *)
            return 0;;
    esac
}

dcm_handle_local_conf_file () {

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

    # copy local.conf to /mnt
    rm /mnt$PATH_LOCAL_CONF_FILE 2>>  $FWDL_LOG
    if [ -f $PATH_LOCAL_CONF_FILE ]
    then
        echo "Copy Dcmd Local Config File .. " >> $FWDL_LOG
        cp $PATH_LOCAL_CONF_FILE /mnt$PATH_LOCAL_CONF_FILE  2>>  $FWDL_LOG
    fi

    # manipulate local.conf in /mnt
    local insertBM=1
    if [ -f /mnt$PATH_LOCAL_CONF_FILE ]
    then
        grep '<AbmFlag>' /mnt$PATH_LOCAL_CONF_FILE 2>>$FWDL_LOG 1>/dev/null
        ret=$?
        if [ $ret -eq 0 ]; then
            grep '<AbmFlag>false</AbmFlag>' /mnt$PATH_LOCAL_CONF_FILE 2>>$FWDL_LOG 1>/dev/null
            bm_ret=$?
            if [ $bm_ret -eq 0 ]; then
                echo "Keep Current Bare-Metal mode = false" >> $FWDL_LOG
            else
                echo "Keep Current Bare-Metal mode = true" >> $FWDL_LOG 
            fi
            insertBM=0
        elif [ $ret -eq 1 ]; then
            echo "Bare-Metal mode is not found" >> $FWDL_LOG 
        else
            echo "Grep error code = $ret" >> $FWDL_LOG
        fi
    fi

    if [ $insertBM -eq 1 ]
    then
        local current_rbridge_id=`/fabos/cliexec/config get fabric.domain 2`
        local bmentry="<AconfigName>VcsNodeLocalManagedObject*${current_rbridge_id}</AconfigName><AconfigValue><AVcsNodeLocalManagedObject><AbulkingId>0</AbulkingId><AbmFlag>false</AbmFlag></AVcsNodeLocalManagedObject></AconfigValue><AmanagedObjectName>VcsNodeLocalManagedObject</AmanagedObjectName><AownerNodeObjectId>0*0</AownerNodeObjectId>"
        local bmentry_size=${#bmentry}
        echo -n "$bmentry_size#$bmentry" >> /mnt$PATH_LOCAL_CONF_FILE
        echo "Deactivate Bare-Metal mode on new firmware" >> $FWDL_LOG
    fi
}


#
#Firmware upgrade case      : 1
#Firmware downgrade case    : -1
#same firmware              : 0
#
firmwaredownload_case()
{
    check_new_version
    status=$?
    case=0
    if [ ${status} -eq 0 ] ; then
	    FROM_DATE=$(/bin/rpm -q --queryformat "%{BUILDTIME}" dcm);
	    TO_DATE=$(/bin/rpm --root /mnt -q --queryformat "%{BUILDTIME}" dcm);
	    if [ $FROM_DATE -gt $TO_DATE ]; then
		    #downgrade
            case=-1
	    else
		    #upgrade
            case=1
        fi
    else
        case=${status}
	fi

    return ${case}
}
#
# Check whether Dcmd is supported or not 
#
is_callisto()
{   
    case ${SWBD##SWBD} in
        '95' | '96' | '97' | '107' | '112' | '116' | '123') 
            return 1;;
        *)
            return 0;;
    esac
}

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

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

#
# Check if Access Gateway is default on platform
#
is_accessgateway_def()
{
    case ${SWBD##SWBD} in
        '131' | '137' | '138' | '151') 
            return 1;;
        *)
            return 0;;
    esac
}

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' 2>&1 >/dev/null    
    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.*)
                # echo --- Setting old bootcmd
                bootenv bootcmd 'setenv bootargs mem=${mem} ${OSLoadOptions};ataboot;makesinrec 0x1000000;bootm 0x400000' 2>&1 >/dev/null    
                ;;
            *)
                # echo --- Setting new bootcmd
                bootenv bootcmd 'setenv bootargs mem=${mem} ${OSLoadOptions};ataboot 0x2000000;makesinrec 0x3000000;bootm 0x2000000' 2>&1 >/dev/null     
                ;;
        esac
    fi
}

set_bbd_bootcmd() 
{
	bootenv bootcmd 'execute_internal_bootcmd'   
}

# Helper function. update the metadata for fast load able images
update_fastload_mdt() {
    sync

    #install root
    ROOT=/mnt
    #create the meta data now
    $ROOT/usr/bin/mkfastmdt "$ROOT/boot/uImage"                    $Linux_Load_Addr
    $ROOT/usr/bin/mkfastmdt "$ROOT/boot/hv.uImage"                 $fslHV_Load_Addr
    $ROOT/usr/bin/mkfastmdt "$ROOT/boot/silkworm.dtb"              $HWdtb_Load_Addr
    $ROOT/usr/bin/mkfastmdt "$ROOT/boot/silkworm_hct.dtb"          $HVdtb_Load_Addr
    is_2part_supported
    if [ $? == 1 ]; then
        $ROOT/usr/bin/mkfastmdt "$ROOT/boot/silkworm_hct_2part.dtb" $HVdtb_Load_Addr
    fi

    #create metadata for fast loading (.mdt is added by mkfastmdt)
    cat $ROOT/boot/uImage.mdt       >  $ROOT/boot/fastloading.mdt
    cat $ROOT/boot/hv.uImage.mdt    >> $ROOT/boot/fastloading.mdt
    cat $ROOT/boot/silkworm.dtb.mdt >> $ROOT/boot/fastloading.mdt
    is_2part_supported
    if [ $? == 1 ]; then
        cp $ROOT/boot/fastloading.mdt $ROOT/boot/fastloading_2p.mdt
    fi

    #hv config device tree differs
    cat $ROOT/boot/silkworm_hct.dtb.mdt >> $ROOT/boot/fastloading.mdt
    is_2part_supported
    if [ $? == 1 ]; then
        cat $ROOT/boot/silkworm_hct_2part.dtb.mdt >> $ROOT/boot/fastloading_2p.mdt
    fi
    #end of data indicator
    echo "[]" >> $ROOT/boot/fastloading.mdt
    echo "[]" >> $ROOT/boot/fastloading_2p.mdt
    #clean up
    rm -f $ROOT/boot/uImage.mdt
    rm -f $ROOT/boot/hv.uImage.mdt
    rm -f $ROOT/boot/silkworm.dtb.mdt
    rm -f $ROOT/boot/silkworm_hct.dtb.mdt
    is_2part_supported
    if [ $? == 1 ]; then
        rm -f $ROOT/boot/silkworm_hct_2part.dtb.mdt
    fi

    sync

    #check if fast loading env is available in uboot.
    result=`bootenv | grep -i "hvcmd_fast"`
    if [  $? -ne 0 ]; then
        echo "updating env for fast USB loading"

        #get hvcmd from the env
        hvcmd_env=`bootenv | grep -i "hvcmd"`
        #update the hvcmd_env  as per hvcmd_fast
        result=`echo $hvcmd_env | grep "silkworm_hct.dtb"`
        if [ $? -eq 0 ]; then
            bootenv -v hvcmd_fast "makesinrec 0x79fff000;ext2load usb 0:\$prt 1000 /boot/fastloading.mdt;usb fastload 1000 ;bootm $fslHV_Load_Addr - $HWdtb_Load_Addr"
            bootenv -v fastboot 'true'
        fi
        
        result=`echo  $hvcmd_env | grep "silkworm_hct_2part.dtb"`
        if [ $? -eq 0 ]; then
            bootenv -v hvcmd_fast "makesinrec 0x79fff000;ext2load usb 0:\$prt 1000 /boot/fastloading_2p.mdt ; usb fastload 1000 ;bootm $fslHV_Load_Addr - $HWdtb_Load_Addr"
            bootenv -v fastboot 'true'
        fi
    fi
}

comp_file()
{
    f1="$1"
    f2="$2"
    result=1
    if [ -f $f1 ] && [ -f $f2 ]; then
        sum1=`md5sum $f1 |cut -f 1 -d ' '`
        sum2=`md5sum $f2 |cut -f 1 -d ' '`
        $ECHO "$f1: $sum1, $f2: $sum2"
        if [ $sum1 = $sum2 ]; then
            result=0
        fi
    fi
    return $result
}

get_num_of_daemon() {

    local vcsconfvalue="0000"
    local clusterconfvalue="0"
    local num_daemons=1

    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
       num_daemons=2
    fi

    echo "$num_daemons"

}

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

    return $STS_OK
}

is_fwdl_arg() {

    #
    # Reads command line args passed to firmwaredownload
    # and checks if the required argument is specified
    #
    parent_pid=`ps -ef|grep 'fabos\/sbin\/firmwaredownload' | awk '{print $2}'`
    echo "parent_pid=$parent_pid" >> /var/log/fwdl.log
    for arg in $(/usr/bin/tr '\0' ' ' < /proc/$parent_pid/cmdline)
    do
            case $arg in
            (-*$1*)
        return $STS_OK
        ;;
            esac
        done
        return $STS_ERR
}

# Add sendmail user id to passwd
grep smmsp /etc/passwd > /dev/null
if [ $? -eq 1 ] ; then
        sed '/ftp/a\
smmsp:x:25:25:Sendmail:\/home\/smmsp:\/bin\/false' /etc/passwd > /etc/passwd.tmp
        mv /etc/passwd.tmp /etc/passwd
fi

# Add sendmail user id to group
grep smmsp /etc/group > /dev/null
if [ $? -eq 1 ] ; then
        sed '/man/a\
smmsp:x:25:smmsp' /etc/group > /etc/group.tmp
        mv /etc/group.tmp /etc/group
fi

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

#for harrier platform, switch-conf is changed between builds, so remove any potential old switch-conf.SWBD file
if [ $sw_platform == 123 ]; then 
	/bin/rm -f /mnt/etc/fabos/config/switch-conf.${SWBD##SWBD} 2>&1
	/bin/rm -f /mnt/fabos/config/switch-conf.${SWBD##SWBD} 2>&1
	/bin/rm -f /fabos/config/switch-conf.${SWBD##SWBD} 2>&1
	/bin/rm -f /etc/fabos/config/switch-conf.${SWBD##SWBD} 2>&1
fi

#copy vcs.conf and cluster.conf to persist VCS mode and cluster mode after firmwaredownload

if ([ $FROM_MAJOR -eq 4 ] && [ $FROM_MINOR -eq 0 ]); then
# From 4.0.x <-> 5.0.0_pit we only support default-config mode. Use this flag to make the DCMD DB to default while moving from 4.0.x -> 5.0.0_pit.
	FLAG=1
	echo "default fwdl flag=$FLAG" >> /var/log/fwdl.log;
	echo "Making the DCM DB to default";
fi

if ([ $FROM_MAJOR -eq 5 ] && [ $FROM_MINOR -eq 0 ] && [ $TO_MAJOR -eq 6 ] && [ $TO_MINOR -eq 0 ] && [ $TO_PATCH -eq 2 ]); then
# From 5.0 <-> 6.0.2 we only support default-config mode. Use this flag to make the DCMD DB to default while moving from 5.0. -> 6.0.2.
        fipsmode
        if [ $? -eq 0 ]; then

		echo "default configuration "
		FLAG=1
		echo "default fwdl flag=$FLAG" >> /var/log/fwdl.log;
		echo "Making the DCM DB to default";
	fi
fi


#
# For Blackbird - default config for downgrade to nos4.0.x_bbd
# For more info refer defect TR000528208
#
is_blackbird
if [ $? == 1 ]; then
	if [ $TO_MAJOR -eq 4 -a $TO_MINOR -eq 0 ]; then
		FLAG=1
		echo "Making the DCM DB to default";
	fi
fi

echo "default fwdl flag=$FLAG" >> /var/log/fwdl.log;

is_dcmd_supported
if [ $? == 1 ]; then

    PATH_FWDL_LOG="/var/log/fwdl.log"
    PATH_FWDL_CONF_FILE="/etc/fwdl.conf"

    # Special handling for 4.1.2->5.x.x upgrade where Castor switch will sync files on secondary partition to the new Standby GOS (via p2_install)
    # Before sync start, Active should copy current VCSID/VCSMODE to secondary partition so that VCS parameters are synced to standby to avoid the VCS parameter mismatch
    # For default firmwaredownload, vcs files are also copied to secondary partition but it will be modified by cfgdefault script.

    if [ $FROM_MAJOR -eq 4 ] || [ "$SWBD" == "SWBD155" ] || [ "$SWBD" == "SWBD138" ]; then
        cp /etc/fabos/Dcmd/vcs.conf /mnt/etc/fabos/Dcmd/vcs.conf >> $PATH_FWDL_LOG 2>&1
        cp /etc/fabos/Dcmd/cluster.conf /mnt/etc/fabos/Dcmd/cluster.conf >> $PATH_FWDL_LOG 2>&1
    fi

	if [ -n "$FLAG" ] && [ $FLAG -eq 1 -o $FLAG -eq 2 ]; then

        # this is a default firmwaredownload case or default factory

	    setcontext 128 0

        # Get firmwaredownload parameters

        fwdl_conf_rbridge_id=""
        fwdl_conf_vcs_id=""
        fwdl_conf_vcs_mode=""
        fwdl_conf_keep_baremetal=1

        if [ -f $PATH_FWDL_CONF_FILE ]; then
            fwdl_conf_rbridge_id=`sed -n 's/rbridge-id : \([0-9]\+\)/\1/p' $PATH_FWDL_CONF_FILE`
            fwdl_conf_vcs_id=`sed -n 's/vcs-id : \([0-9]\+\)/\1/p' $PATH_FWDL_CONF_FILE`
            fwdl_conf_vcs_mode=`sed -n 's/vcs-mode : \(\-\?[0-9]\+\)/\1/p' $PATH_FWDL_CONF_FILE`
            fwdl_conf_keep_baremetal=`sed -n 's/keep-baseconfig : \(\-\?[0-9]\+\)/\1/p' $PATH_FWDL_CONF_FILE`
        fi
        
        # For default firmwaredownload, always keep baremetal flag (disabled)
        if [ $FLAG -eq 1 ]; then
            fwdl_conf_keep_baremetal=1
        fi

        echo "parameter [vcs-id:$fwdl_conf_vcs_id] " >> $PATH_FWDL_LOG;
        echo "parameter [rbridge-id:$fwdl_conf_rbridge_id] " >> $PATH_FWDL_LOG;
        echo "parameter [vcs-mode:$fwdl_conf_vcs_mode] " >> $PATH_FWDL_LOG;
        echo "parameter [keep-baremetal:$fwdl_conf_keep_baremetal] " >> $PATH_FWDL_LOG;

        # Invoke cfgdefault script to clean dcmd configuration

        OPTS=""
        if [ -n "$fwdl_conf_vcs_id" ]; then
            OPTS="-v $fwdl_conf_vcs_id"
        fi
        if [ -n "$fwdl_conf_rbridge_id" ]; then
            OPTS="$OPTS -r $fwdl_conf_rbridge_id "
        fi
                if [ -n "$fwdl_conf_vcs_mode" ]; then
            OPTS="$OPTS -m $fwdl_conf_vcs_mode"
        fi
        if [ -n "$fwdl_conf_keep_baremetal" ]; then
            OPTS="$OPTS -b $fwdl_conf_keep_baremetal"
        fi

        check_new_version
        if [ $? -lt 0 ] ; then
            /sbin/cfgdefault -p 1 -l "$PATH_FWDL_LOG" -u 0 $OPTS 
        else
            /mnt/sbin/cfgdefault -p 1 -l "$PATH_FWDL_LOG" -u 0 $OPTS 
        fi

        sync;

    else
        # this is a regular firmwaredownload case

    # All DCMd related conf file should be handled here instead of in fabos/dcmd.sh script after reboot 
    # The main reason is that postinst script is running on behalf of new firmware version, that allows config file to be manipulated even in a downgrade case 
    dcm_handle_local_conf_file 

    if ([ $FROM_MAJOR -le 2 ] && [ $TO_MAJOR -ge 3 ]) || ([ $FROM_MAJOR -ge 3 ] && [ $TO_MAJOR -le 2 ]); then
        echo "Simply cleaning up Configuration Store." > ${OUTPUT};
        rm -rf /mnt/etc/fabos/Dcmd/WaveDatabase/*; 
        rm -rf /mnt/etc/fabos/Dcmd/WaveDatabase/.* > /dev/null 2>&1;    #remove all hidden files as well 
        rm -rf /mnt/etc/fabos/Dcmd/Dcmd.Linux.powerpc.cfg;
        rm -rf /mnt/etc/fabos/Ccmd/WaveDatabase/*; 
        rm -rf /mnt/etc/fabos/Ccmd/WaveDatabase/.* > /dev/null 2>&1;    #removes all hidden files as well  
        rm -rf /mnt/etc/fabos/Ccmd/Ccmd.Linux.powerpc.cfg;
    else
            noofdaemon=$(get_num_of_daemon) 
            from_version_need_ccmd=1
            to_version_need_ccmd=1

            if [ $FROM_MAJOR -ge 5 ] || ([ $FROM_MAJOR -eq 4 ] && [ $FROM_MINOR -eq 1 ])
            then
                from_version_need_ccmd=0
            else
                from_version_need_ccmd=1
            fi

            if [ $TO_MAJOR -ge 5 ] || ([ $TO_MAJOR -eq 4 ] && [ $TO_MINOR -eq 1 ])
            then
                to_version_need_ccmd=0
            else
                to_version_need_ccmd=1
            fi

            # In Taurus/Capricorn, MC/SA mode won't create CCMD database. This will cause an issue if we downgrade to Leo (or pre-Leo) where CCMD database is expected.
            if ([ $from_version_need_ccmd -eq 0 ] && [ $to_version_need_ccmd -eq 1 ]) && [ $noofdaemon -eq 1 ]
            then
                echo -e "`date` - Initializing the Ccmd database (current partition). "
                /fabos/bin/initializeccmdb   
            fi

            # In FC or Capricon/Taurus->Leo/pre_Leo downgrade case, we always initilize both databases.
            if ([ $from_version_need_ccmd -eq 0 ] && [ $to_version_need_ccmd -eq 1 ]) || [ $noofdaemon -eq 2 ]
            then
        echo -e "`date` - Initializing the Dcmd and Ccmd database..."

        if [ "$sw_platform" == "1000" ]; then
            /usr/sbin/chroot /mnt /fabos/bin/initializedcmdb & /usr/sbin/chroot /mnt /fabos/bin/initializeccmdb; wait
            /usr/sbin/chroot /mnt sync
        else
            /usr/sbin/chroot /mnt /fabos/bin/initializedcmdb
            /usr/sbin/chroot /mnt /fabos/bin/initializeccmdb
        fi

        echo -e "`date` - Completed intializing the Dcmd and Ccmd database."
            else
                echo -e "`date` - Initializing the Dcmd database..."
                /usr/sbin/chroot /mnt /fabos/bin/initializedcmdb
                echo -e "`date` - Completed intializing the Dcmd database."
            fi
        fi

	# just remove this config to avoid backward compatibility
	#
	/bin/rm -f /mnt/etc/fabos/config/switch-conf.${SWBD##SWBD} 2>&1
	/bin/rm -f /mnt/fabos/config/switch-conf.${SWBD##SWBD} 2>&1

    # copy the conf files always to persist mode. 
    # Previous conf Files removal logic should be handled in fabos script
    cp /etc/fabos/Dcmd/vcs.conf /mnt/etc/fabos/Dcmd/vcs.conf.fwdl
    cp /etc/fabos/Dcmd/cluster.conf /mnt/etc/fabos/Dcmd/cluster.conf.fwdl
    echo "POSTINSTALL : cluster.conf = "`cat /etc/fabos/Dcmd/cluster.conf` >> /etc/fabos/Dcmd/fwdl_db_copy_log
    echo "POSTINSTALL : cluster.conf.fwdl = "`cat /mnt/etc/fabos/Dcmd/cluster.conf.fwdl` >> /etc/fabos/Dcmd/fwdl_db_copy_log
   
    if [ -d /mnt/etc/fabos/Dcmd/yang ]
    then
        rm -rf /mnt/etc/fabos/Dcmd/yang
    fi

    if [ -L /mnt/etc/fabos/NosSmd/yang ]
    then
        rm -f /mnt/etc/fabos/NosSmd/yang
    fi
 
    # Enabling DB conversion by default, remove the file disableschemaconversion.
    rm -f /mnt/etc/fabos/Dcmd/disableschemaconversion;
    rm -f /mnt/etc/fabos/Ccmd/disableschemaconversion;
    
    # using the vcs.conf.fwdl file to save the information about the fwdl case.
    firmwaredownload_case
    case=$?
	#echo "Firmware download case:" ${case}

    # content of file /mnt/etc/fabos/Dcmd/vcs.conf.fwdl is not being used for vcs.conf file.
    # but only the existence of this file decides the fwdl. Hence, reusing the file for 
    # passing the fwdl case (0:same/nightly firmware, 1:fwdl upgrade, -1 : fw downgrade) in the same file.
    echo ${case} > /mnt/etc/fabos/Dcmd/vcs.conf.fwdl
    /usr/sbin/chroot /mnt tar -C /etc/confd -xzvf /etc/confd/docroot.tgz > /dev/null 2>&1 
    /usr/sbin/chroot /mnt tar -C /etc/confd -xvf /etc/confd/YangFiles.tar > /dev/null 2>&1 
    sync;
    sync;
fi
    # Store from and to firmware versions in a file to be used later while booting Dcmd
    firmwareVersionFile="/etc/fabos/Dcmd/FirmwareVersions"

    FROM_REVISION_DCM=$FROM_REVISION
    if [ -z "$FROM_REVISION_DCM" ]; then
        FROM_REVISION_DCM=0;
    fi

    echo "${FROM_MAJOR}.${FROM_MINOR}.${FROM_PATCH}.${FROM_REVISION_DCM}" > /mnt${firmwareVersionFile}
    echo "${TO_MAJOR}.${TO_MINOR}.${TO_PATCH}.${TO_REVISION}" >> /mnt${firmwareVersionFile}
fi

#replace the 8th parameter of prority-table to be 15.0 for a consistency firmwareupgrade
if [ -f /var/config/vcs/scripts/startup-config ]; then
    awk '{if ($1 == "priority-table") { strict = match($9, /15.0/); if (strict) print; else print "",$1,$2,$3,$4,$5,$6,$7,$8,"15.0";} else  print }' /var/config/vcs/scripts/startup-config > /root/tempStartupFile
    mv /root/tempStartupFile /var/config/vcs/scripts/startup-config
fi

#Starting the snmp-server configuration keys manipulation before reboot
if [ -f /var/config/vcs/scripts/startup-config ]; then
#snmp-server config line manipulation form two line display to one line
    do_snmp_config_manipulation(){
        read line
        temp1=$line
        one=$(echo $line | cut -d " " -f 3)
        if [ "$one" == "rw" ];then
            rw=" rw"
            temp=$temp$rw
            echo "$temp">>$OUTPUT_FILE;
        elif [ "$one" == "snmp-server" ]; then
              echo "$temp">>$OUTPUT_FILE
              temp=$temp1
              do_snmp_config_manipulation
        else
              echo "$temp">>$OUTPUT_FILE
              echo "$temp1">>$OUTPUT_FILE
        fi
    }
#File Details and Inital Settings
cp /var/config/vcs/scripts/startup-config /var/config/vcs/scripts/startup-config-copy
INPUT1_FILE=/var/config/vcs/scripts/startup-config
INPUT_FILE=/var/config/vcs/scripts/startup-config-temp
OUTPUT_FILE=/var/config/vcs/scripts/startup-config-edited
rm -f ${OUTPUT_FILE}
sed -e 's/\\/\\\\/g' $INPUT1_FILE>$INPUT_FILE
BAKIFS=$IFS
IFS=$(echo -en "\r")
exec 3<&0
exec 0<$INPUT_FILE
while read line
do
    temp=$line;
    one=$(echo $line | cut -d " " -f 1)
    if [ "$one" == "snmp-server" ] ;then
        do_snmp_config_manipulation
    else
    LEN=$(echo ${#line})
        if [ $LEN -gt 0 ]; then
            echo "$line">>$OUTPUT_FILE
        fi
    fi
done
exec 0<&3
IFS=$BAKIFS
rm -f ${INPUT_FILE}
mv /var/config/vcs/scripts/startup-config-edited /var/config/vcs/scripts/startup-config
fi

#NTP-key config list
STARTUP_FILE="/var/config/vcs/scripts/startup-config"

# Removing "encryption-level 0" line from NTP-key config list in 4.1.x [x < 3]
if [ $TO_MAJOR -eq 4 -a $TO_MINOR -eq 1 -a $TO_PATCH -lt 3 ] && [ -f STARTUP_FILE ]; then
	#remove "encryption-level 0" from ntp authentication-key list
	sed -e 's/encryption-level 0//g' $STARTUP_FILE > ntp_no_encr.tmp
	mv ntp_no_encr.tmp $STARTUP_FILE

fi

# Removing "encryption-level 0" line from NTP-key config list in 5.0.0
if [ $TO_MAJOR -eq 5 -a $TO_MINOR -eq 0 -a $TO_PATCH -eq 0 ] && [ -f STARTUP_FILE ]; then
	#remove "encryption-level 0" from ntp authentication-key list
	sed -e 's/encryption-level 0//g' $STARTUP_FILE > ntp_no_encr.tmp
	mv ntp_no_encr.tmp $STARTUP_FILE
fi

#Completing the snmp-server configuration keys manipulation before reboot

if [ $FROM_MAJOR -ge 4 ] && [ $TO_MAJOR -le 3 ] && [ -f /var/config/vcs/scripts/startup-config ]; then
	STARTUP_FILE="/var/config/vcs/scripts/startup-config"

#remove the "encryption-level 0" line from radisu/tacacs list
	awk 'match($1,"encryption-level") == 0 {print $0}' $STARTUP_FILE > rad_tac_no_encr.tmp
	cp rad_tac_no_encr.tmp $STARTUP_FILE
	rm rad_tac_no_encr.tmp

#move fcsp from rbridge-id ! to end of the file
	fcsp_cnt=$(cat $STARTUP_FILE | grep "fcsp" | wc -l)
	if [ "$fcsp_cnt" -ne 0 ]; then
		awk '/fcsp/' $STARTUP_FILE >> fcsp.tmp
		sed -e 's/^[ \t]*//' fcsp.tmp >> fcspnosp.tmp
		sed '/fcsp/d' $STARTUP_FILE >> startup-config-no-fcsp.tmp
		cat fcspnosp.tmp >> startup-config-no-fcsp.tmp
		cp startup-config-no-fcsp.tmp $STARTUP_FILE
		rm -rf *.tmp
	fi
#move secpolicy, member-entry, ! from rbridge-id ! to end of the file
	SECPOL_FILE=startup-secpol.tmp
	SECPOLNOSP_FILE=startup-secpolnosp.tmp

#find the number of secpolicy+member-entry+!(yang list) line
	secpol_cnt=$(cat $STARTUP_FILE | grep "secpolicy" | wc -l)
	mem_cnt1=$(cat $STARTUP_FILE |  sed -n '/secpolicy defined-policy*/,/\!/p' | grep "member-entry"| wc -l)
	mem_cnt2=$(cat $STARTUP_FILE |  sed -n '/secpolicy active-policy*/,/\!/p' | grep "member-entry"| wc -l)
	mem_cnt=`expr $mem_cnt1 + $mem_cnt2`
	final_cnt=0

	if [ "$secpol_cnt" -eq 2 ]; then
		final_cnt=$(($secpol_cnt+$mem_cnt+1))
	else
		final_cnt=$(($secpol_cnt+$mem_cnt))
	fi

	if [ "$final_cnt" -ne 0 ]; then
# get the line no of 1st occurance of secpolicy, and find the end index
		secpol_start=$(awk '/secpolicy/{print NR}' $STARTUP_FILE| head -1)
		if [ ! -z $secpol_start ]; then
			secpol_end=$(($secpol_start+$final_cnt))
#remove 1st space in all the lines of secpolicy list
			sed -n "$secpol_start,$secpol_end p" $STARTUP_FILE > $SECPOL_FILE
			sed 's,^.,,g' $SECPOL_FILE >> $SECPOLNOSP_FILE
#append secpolicy+member-entry+1 yang list at the bottom
			sed "$secpol_start,$secpol_end d" $STARTUP_FILE >> startup-no-secpol.tmp
			cp startup-no-secpol.tmp $STARTUP_FILE
			cat $SECPOLNOSP_FILE >> $STARTUP_FILE
		fi
	fi
	

	awk '/system-monitor/' $STARTUP_FILE >> sysmon.tmp
	sed -e 's/^[ \t]*//' sysmon.tmp >> sysmonnosp.tmp
	sed '/system-monitor/d' $STARTUP_FILE >> startup-config-no-sysmon.tmp
	cat sysmonnosp.tmp >> startup-config-no-sysmon.tmp
	INPUT_TEMP_FILE=startup-config-no-sysmon.tmp
	INPUT_TEMP_FILE1=startup-config-no-sysmon1.tmp
	OUTPUT_FILE=startup-final.tmp
	cp $INPUT_TEMP_FILE $INPUT_TEMP_FILE1
	sed -e 's/\\/\\\\/g' $INPUT_TEMP_FILE1>$INPUT_TEMP_FILE
	BAKIFS=$IFS
	IFS=$(echo -en "\r")
	exec 3<&0
	exec 0<$INPUT_TEMP_FILE

# Because of above operation, rbridge-id-! block will be left
# Hence passing the file to remove the empty block

	while read line
	do
		temp=$line;
		one=$(echo $line | cut -d " " -f 1)
		
		if [ "$one" == "rbridge-id" ];then
			read line;
			temp1=$line;
			exc=$(echo $line | cut -d " " -f 1)
			if [ "$exc" != "!" ]; then
				echo "$temp" >> $OUTPUT_FILE;
				echo "$temp1" >> $OUTPUT_FILE;
			fi
		else
			echo "$temp" >> $OUTPUT_FILE;
		fi
	done
		echo "" >> $OUTPUT_FILE;
	exec 0<&3
	IFS=$BAKIFS
	cp $OUTPUT_FILE $STARTUP_FILE
	rm -rf *.tmp
fi


#
# MAC,IP ACL config Update from 1.x.x or 2.x.x to 3.x.x or higher
#
if [ $FROM_MAJOR -le 2 ] && [ $TO_MAJOR -ge 3 ] && [ -f /var/config/vcs/scripts/startup-config ]; then
    STARTUP_FILE=/var/config/vcs/scripts/startup-config
    TEMP_STARTUP_FILE=startup-config.tmp
    #MAC ACL Name conversions
    ORIG_ACL_NAMES=$(grep "mac access-list" $STARTUP_FILE | awk '{print $4}')
    acl_num=0
    for acl_name in $ORIG_ACL_NAMES
    do
        changed_acl_name=$(echo $acl_name|sed 's![]\.@#+*()={}[~<>$|&/:;,]!!g'|sed 's!\(.\{58,63\}\).....!\1!g')-m$acl_num
        search_acl_name=$(echo $acl_name|sed 's!\([]\*\$\/&[]\)!\\\1!g')
        sed "/mac/s/\<$search_acl_name\>/$changed_acl_name/g" $STARTUP_FILE > $TEMP_STARTUP_FILE
        rm $STARTUP_FILE
        mv $TEMP_STARTUP_FILE $STARTUP_FILE
        ((acl_num++))
    done

    #IP ACL Name conversions
    ORIG_ACL_NAMES=$(grep "ip access-list" $STARTUP_FILE | awk '{print $4}')
    acl_num=0
    for acl_name in $ORIG_ACL_NAMES
    do
        changed_acl_name=$(echo $acl_name|sed 's![]\.@#+*()={}[~<>$|&/:;,]!!g'|sed 's!\(.\{58,63\}\).....!\1!g')-i$acl_num
        search_acl_name=$(echo $acl_name|sed 's!\([]\*\$\/&[]\)!\\\1!g')
        sed "/ip/s/\<$search_acl_name\>/$changed_acl_name/g" $STARTUP_FILE > $TEMP_STARTUP_FILE
        rm $STARTUP_FILE
        mv $TEMP_STARTUP_FILE $STARTUP_FILE
        ((acl_num++))
    done

    #Extract MAC acl config into a different file
    awk '/^mac access-list/,/^!/' $STARTUP_FILE > startup-config-acl.tmp
    #remove all the host keywords and put them before MAC address in ACL rule
    sed '/seq/s/ host//g' startup-config-acl.tmp > startup-config-acl_nohost.tmp
    #add Host words before MAC address
    sed '/seq/s/[0-9a-fA-F]\{4\}\(.[0-9a-fA-F]\{4\}\)\{2\}/host &/g' startup-config-acl_nohost.tmp > startup-config-acl.tmp
    #Extract IP ACL to the MAC ACL config file
    awk '/^ip access-list/,/^!/' $STARTUP_FILE >> startup-config-acl.tmp
    #Remove MAC and IP ACL config and place it above VLAN config
    sed '/^mac access-list/,/^!/d' $STARTUP_FILE >> $TEMP_STARTUP_FILE
    sed '/^ip access-list/,/^!/d' $TEMP_STARTUP_FILE >> startup-config-no-acl.tmp
    IF_VLAN_START=`grep -n "interface Vlan" startup-config-no-acl.tmp | head -1 | cut -f 1 -d :`
    TOTAL_LINES=`cat startup-config-no-acl.tmp | wc -l`
    cat startup-config-no-acl.tmp | head -$[$IF_VLAN_START - 1] > startup-config-final.tmp
    cat startup-config-acl.tmp >> startup-config-final.tmp
    cat startup-config-no-acl.tmp | tail -$[$TOTAL_LINES - $IF_VLAN_START + 1] >> startup-config-final.tmp
    rm $STARTUP_FILE
    mv startup-config-final.tmp $STARTUP_FILE
    rm -f *.tmp
fi
#Done with MAC,IP ACL config upgrade


VCS_SET_MODE_LOG_FILE=/mnt/var/log/vcs_set_mode.log
#If VCS mode is enabled prepare the VCS-ONLY-CLIs for rendering. 
if [ -f '/mnt/etc/fabos/Dcmd/vcs_set_mode.sh' ] ; then
    # Overwrite the logfile with every FWDL.
    date > $VCS_SET_MODE_LOG_FILE    
    VCS_MODE=`cat /etc/fabos/Dcmd/vcs.conf | head -n 1`
    if [ $VCS_MODE != "0000" ]; then
        #Run the script from the new firmware.    
        /mnt/etc/fabos/Dcmd/vcs_set_mode.sh  enable  /mnt
    else 
        echo "VCS Mode not enabled. VCS_MODE=$VCS_MODE" >> $VCS_SET_MODE_LOG_FILE
    fi
else
    echo "VCS set mode script not found." >> $VCS_SET_MODE_LOG_FILE
fi


#
# To DCMD, whether it is a firmware upgrade or downgrade is not only
# based on the major, minor or patch numbers, but also based on the
# build dates. If the new firmware has a later date than the old firmware,
# it is an upgrade, else it is a downgrade. The build date is embedded
# in the name of the kernel RPM package.
#
if ([ $FROM_MAJOR -eq 3 ] && [ $TO_MAJOR -eq 3 ]); then
    FROM_DATE=$(/bin/rpm -q kernel | cut -d "-" -f 3 | cut -c -6);
    TO_DATE=$(/bin/rpm --root /mnt -q kernel | cut -d "-" -f 3 | cut -c -6);
    if [ $FROM_DATE -gt $TO_DATE ]; then
        $ECHO downgrade
    else
        $ECHO upgrade
    fi
fi

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

#
# Upgrading from 2.x.x to 3.x.x on pizza box
#
if [ $TO_MAJOR -gt 2 ] && [ $FROM_MAJOR -eq 2 ]; then
    #
    # If firmware download is performed using NSF , then the release.plist
    # may not be downloaded to the temporary fwdl directory. But the
    # release.plist will be downloaded to /tmp
    #
    if [ -f "/tmp/fwdl-${PPID}/release.plist" ]; then
        PLIST="/tmp/fwdl-${PPID}/release.plist"
    else
        PLIST="/tmp/release.plist"
    fi

    PLIST_TEMP="/tmp/release.plist"
    /bin/cp $PLIST /mnt/$PLIST_TEMP
    
    #
    # Create a version file for the 3.0.0 firmware
    #
    LD_PRELOAD=/mnt/lib/libversion.so.1.0 /mnt/lib/libc.so.6 > /dev/null 2>&1
    /usr/sbin/chroot /mnt /sbin/create_release_file / $PLIST_TEMP
    /bin/rm /mnt/$PLIST_TEMP
fi

#
# Downgrading from 3.x.x to 2.x.x on pizzabox
#
if [ $TO_MAJOR -eq 2 ] && [ $FROM_MAJOR -gt 2 ]; then
    if [ -f /mnt/var/images/${SWBD}/release.plist ]; then
        /bin/rm /mnt/var/images/${SWBD}/release.plist
    fi
    if [ -f /mnt/fabos/share/version ]; then
        /bin/rm /mnt/fabos/share/version
    fi
fi

#
# Just being paranoid and should be removed later!!
# We might run into issue when a pizzabox is upgraded from
#       2.1.x->this build (3.0.0)->a previous 3.0.0 pit build
# The previous pit build expects the /base to be there.
#
if [ $TO_MAJOR -gt 2 ]; then
    if [ ! -d /mnt/var/images/base ]; then
        mkdir /mnt/var/images/base
    fi
fi

# Create direectory for Syslog CA certificate if not already present
if [ $FROM_MAJOR -le 3 ] && [ $TO_MAJOR -ge 3 ]; then
	if [ ! -d /etc/syslog-ng/ca.d ]; then
		/bin/mkdir -p /etc/syslog-ng/ca.d
	fi
	if [ ! -d /mnt/etc/syslog-ng/ca.d ]; then
		/bin/mkdir -p /mnt/etc/syslog-ng/ca.d
	fi
	if [ -f /mnt/etc/syslog-ng/ca.d/syslog_link_hash ]; then
		CMD=`/bin/cat /mnt/etc/syslog-ng/ca.d/syslog_link_hash`
		/usr/sbin/chroot /mnt bash -c "CMD"
	fi
fi

# Handle the sync issues related to sendmail
if [ $TO_MAJOR -lt 5 ]; then
	if [ ! -d /etc/mail/ ]; then
		/bin/mkdir -p /etc/mail/
	fi
	if [ ! -d /mnt/etc/mail/ ] ;then
		/bin/mkdir -p /mnt/etc/mail/
	fi
fi

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

#
# Create power-on test skip indicator file on standby
#
>/mnt/etc/skip_poweron_test

#
# Store checksum of ldconfig and ld.so (shared loader)
# The output hash values will be used during power on test
#

# Store the checksum to ldchksum for backward compatibility
if [ $TO_MAJOR -le 3 ]; then
	$ECHO "Creating loader checksum file"
	>/mnt/etc/ldchksum

    #Find the loader checksum
    md5sum /mnt/lib/ld-* | \
    /bin/sed -e "s,\/mnt\/lib\/ld-,\/lib\/ld-,g" \
    >> /mnt/etc/ldchksum

    #Now manipulate the ldconfig checksum
    md5sum /mnt/sbin/ldconfig | \
    /bin/sed -e "s,\/mnt\/sbin\/ldconfig,\/sbin\/ldconfig,g" \
    >> /mnt/etc/ldchksum
fi

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

# create the trace dump file on the /mnt dir
if [ -e /dev/ata_dumper ];then 
    trace_create_dump_file
elif [ -f '/mnt/var/tracedump.dmp' ] ;then
    /bin/rm -f /mnt/var/tracedump.dmp
fi 

##fastloader update for PPC platforms
if [ -d /proc/device-tree ]; then
    update_fastload_mdt
fi

#
# Removing Dynamically created Symbolic Links when
# downgrading from 3.x.x to 2.x.x
#
if [ $TO_MAJOR -eq 2 ] && [ $FROM_MAJOR -gt 2 ]; then
    /bin/rm /mnt/etc/confd/fc.ccl
fi

#
# Update the PROM if upgrade from < 4.0.0 to 4.0.0
#
BIN_NAME=$(ls /mnt/boot/image/${SWBD} 2>/dev/null)
if [ -f "/mnt/boot/image/${SWBD}/${BIN_NAME}" ]; then
	rm -f /mnt/boot/bootrom.bin
	ln -sf ./image/${SWBD}/${BIN_NAME} /mnt/boot/bootrom.bin
fi
CKSUM_BIN=$(cksum /mnt/boot/bootrom.bin | cut -d ' ' -f 1)
CKSUM_DEV=$(cksum /dev/prom0 | cut -d ' ' -f 1)
if [ "$CKSUM_BIN" != "$CKSUM_DEV" ]; then
	#
	# For 4.0 and higher, prom device is updated
	# during the partition swap step
	#
	if [ $FROM_MAJOR -le 3 ]; then
		/usr/sbin/chroot /mnt /sbin/prominst
	fi
fi

#
# For Callisto, set the bootcmd according to the prom version
# 
is_callisto
if [ $? == 1 ]; then
    set_bootcmd
fi  

#
# Set the bootcmd to enable hypervisor for blackbird
# This is temporary and the command will be removed in final buils
# by that time all the blakcbird dev and SQA switch will have this
# bootcmd properly set for hv enable
#
is_blackbird
if [ $? == 1 ]; then
    set_bbd_bootcmd
fi

#
# Create dhclient directories 
#

if [ $TO_MAJOR -ge 4 ]; then
	if [ ! -d /etc/dhclientv4 ]; then
		mkdir /etc/dhclientv4
	fi
	if [ ! -f /etc/dhclientv4/dhclient.leases ]; then
		echo >> /etc/dhclientv4/dhclient.leases
	fi
	if [ ! -d /etc/dhclientv6 ]; then
		mkdir /etc/dhclientv6
	fi
	if [ ! -f /etc/dhclientv6/dhclient.leases ]; then
		echo >> /etc/dhclientv6/dhclient.leases
	fi
	
fi
# Downgrade from Taurus
# Added check for Major 6, for Rigel.
if [ $TO_MAJOR -lt 5 ] || [ $TO_MAJOR -eq 6 ] ; then
	/usr/sbin/chroot /mnt /sbin/getvf
	ret=$?
	if [ $ret -eq 0 ]; then
		/fabos/libexec/userdb_sync 2 2
	fi
fi

#
# Downgrade from Leo Patch/Capricorn Patcih/Taurus to leo
#
SSHD_CONFIG_FILE=/etc/sshd_config
SSH_CONFIG_FILE=/etc/ssh_config
SSHD_CONFIG_FILE_MNT=/mnt/etc/sshd_config
SSH_CONFIG_FILE_MNT=/mnt/etc/ssh_config

if [ $TO_MAJOR -eq 4 -a $TO_MINOR -eq 0 -a $TO_PATCH -lt 1 ]; then

	if [ -f $SSHD_CONFIG_FILE ]; then
       /bin/grep -v "MinPrime" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
       /bin/grep -v "ShaValue" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
       /bin/grep -v "KexAlgorithms diffie-hellman-group-exchange-sha256" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
		/bin/grep -v "MaxSessions 1" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
		/bin/grep -i "PermitUserEnvironment" $SSHD_CONFIG_FILE
		if [ $? -ne 0 ]; then
			echo "PermitUserEnvironment yes" >> $SSHD_CONFIG_FILE
		fi
    fi
    if [ -f $SSH_CONFIG_FILE ]; then
       /bin/grep -v "MinPrime" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
       /bin/grep -v "ServerHostKeySize" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
       /bin/grep -v "ShaValue" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
       /bin/grep -v "KexAlgorithms diffie-hellman-group-exchange-sha256" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
    fi

    if [ -f $SSHD_CONFIG_FILE_MNT ]; then
       /bin/grep -v "MinPrime" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
       /bin/grep -v "ShaValue" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
       /bin/grep -v "KexAlgorithms diffie-hellman-group-exchange-sha256" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
		/bin/grep -v "MaxSessions 1" $SSHD_CONFIG_FILE_MNT  > temp && mv temp $SSHD_CONFIG_FILE_MNT
		/bin/grep -i "PermitUserEnvironment" $SSHD_CONFIG_FILE_MNT
		if [ $? -ne 0 ]; then
			echo "PermitUserEnvironment yes" >> $SSHD_CONFIG_FILE_MNT
		fi
    fi
    if [ -f $SSH_CONFIG_FILE_MNT ]; then
       /bin/grep -v "MinPrime" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
       /bin/grep -v "ServerHostKeySize" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
       /bin/grep -v "ShaValue" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
       /bin/grep -v "KexAlgorithms diffie-hellman-group-exchange-sha256" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
    fi
fi

# Downgrade to 4.0
# Remove default-vrf which is installed at bootup
#
if [ $TO_MAJOR -eq 4 -a $TO_MINOR -eq 0 ]; then
    #/fabos/libexec/DcmClient.Linux.powerpc dcmdebug deletePreInstalledVrfs
    clustermode=0;
    if [ -f '/etc/fabos/Dcmd/cluster.conf' ]
    then
        clustermode=`cat /etc/fabos/Dcmd/cluster.conf`
    fi

    if [ $clustermode -eq 1 ]
    then 
        /usr/local/postgresql/9.1.3/bin/psql -p 9013 -d WaveDatabase -f /etc/fabos/NosSmd/vrfcleanup_lc_mode
    else 
        /usr/local/postgresql/9.1.3/bin/psql -p 9013 -d WaveDatabase -f /etc/fabos/NosSmd/vrfcleanup_fc_mode
    fi
fi

#Downgrade to <4.1.3 then remove local.conf

if [ $TO_MAJOR -eq 4 -a $TO_MINOR -eq 1 -a $TO_PATCH -lt 3 ]; then
    echo "Postinstall:Downgrade to <4.1.3 then remove local.conf" >> /etc/fabos/Dcmd/fwdl_db_copy_log
    rm -rf /etc/fabos/Dcmd/Dcmd.Linux.powerpc.local.conf
fi

modify_global_conf_file()
{
    if [ $TO_MAJOR -eq 4 -a $TO_MINOR -eq 1 ]; then
        gvlanmode=`cat /etc/fabos/Dcmd/Dcmd.Linux.powerpc.global.conf | sed 's/^.*<AvcsVirtualFabricEnable>//g' | sed 's/<\/AvcsVirtualFabricEnable>.*$//g'`;
        gvlanconfig="<AconfigAttributeType>WAVE_ATTRIBUTE_TYPE_UI32</AconfigAttributeType><AconfigName>GVlan</AconfigName><AconfigValue>0</AconfigValue>"
        if [ $gvlanmode == "true" ]; then
            echo "Postinstall : Gvlan conf file set enabled in older format" >> /etc/fabos/Dcmd/fwdl_db_copy_log
            gvlanconfig="<AconfigAttributeType>WAVE_ATTRIBUTE_TYPE_UI32</AconfigAttributeType><AconfigName>GVlan</AconfigName><AconfigValue>1</AconfigValue>"
        fi
        echo $gvlanconfig > /etc/fabos/Dcmd/Dcmd.Linux.powerpc.global.conf
        echo $gvlanconfig > /mnt/etc/fabos/Dcmd/Dcmd.Linux.powerpc.global.conf
    fi
}

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

check_if_downgrade
if [ $? -eq 1 ]; then
    is_fwdl_arg "M"
    issu_fwdl_config=$?
	is_fwdl_arg "d"
	defconfig=$?
    # Added for the defect NOS-67911
    # Skip the Dcmd performSupportOpsOnSoftwareChange for ISSU downgrad

    if [ $issu_fwdl_config -ne 0 ] && [ $defconfig -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
			FROM_REVISION_DCM=0;
		fi


		FROM_VERSION_DCM=${FROM_MAJOR}.${FROM_MINOR}.${FROM_PATCH}.${FROM_REVISION_DCM}
		TO_VERSION_DCM=${TO_MAJOR}.${TO_MINOR}.${TO_PATCH}.${TO_REVISION_DCM}

		#TODO : Should be true during downgrade from 6.x to 5.x
		TRIGGER_DBC="false"

		TRIGGER_DOWNGRADE_API="false"

		if [ -n "$FLAG" ] && [ $FLAG -eq 1 ]; then
		    echo "Postinstall : Default config downgrade. Trigger DcmClient for Downgrade without DBC without downgrade API irrespective of active/standby MM, then modify gvlan file" >> /etc/fabos/Dcmd/fwdl_db_copy_log
		    echo "/fabos/libexec/DcmClient.Linux.powerpc debug performSupportOpsOnSoftwareChange $FROM_VERSION_DCM $TO_VERSION_DCM 1 $TRIGGER_DBC $TRIGGER_DOWNGRADE_API" >> /etc/fabos/Dcmd/fwdl_db_copy_log
		    /fabos/libexec/DcmClient.Linux.powerpc debug performSupportOpsOnSoftwareChange $FROM_VERSION_DCM $TO_VERSION_DCM 1 $TRIGGER_DBC $TRIGGER_DOWNGRADE_API
			modify_global_conf_file
		else
			ha_role
			if [ $? -eq 1 ];then
				TRIGGER_DOWNGRADE_API="true"
		       echo "Postinstall : Trigger DcmClient for Downgrade without DBC with downgrade API" >> /etc/fabos/Dcmd/fwdl_db_copy_log
			   echo "/fabos/libexec/DcmClient.Linux.powerpc debug performSupportOpsOnSoftwareChange $FROM_VERSION_DCM $TO_VERSION_DCM 1 $TRIGGER_DBC $TRIGGER_DOWNGRADE_API" >> /etc/fabos/Dcmd/fwdl_db_copy_log
			  /fabos/libexec/DcmClient.Linux.powerpc debug performSupportOpsOnSoftwareChange $FROM_VERSION_DCM $TO_VERSION_DCM 1 $TRIGGER_DBC $TRIGGER_DOWNGRADE_API
			else
		       echo "Postinstall : Trigger DcmClient for Downgrade without DBC without downgrade API" >> /etc/fabos/Dcmd/fwdl_db_copy_log
			    echo "/fabos/libexec/DcmClient.Linux.powerpc debug performSupportOpsOnSoftwareChange $FROM_VERSION_DCM $TO_VERSION_DCM 1 $TRIGGER_DBC $TRIGGER_DOWNGRADE_API" >> /etc/fabos/Dcmd/fwdl_db_copy_log
			    /fabos/libexec/DcmClient.Linux.powerpc debug performSupportOpsOnSoftwareChange $FROM_VERSION_DCM $TO_VERSION_DCM 1 $TRIGGER_DBC $TRIGGER_DOWNGRADE_API
				ha_insync
				if [ $? -eq 0 ]; then
					echo "Postinstall : ha not in sync and standby mm. remove cfg and modify gvlan format" >> /etc/fabos/Dcmd/fwdl_db_copy_log
					modify_global_conf_file
					rm -rf /etc/fabos/Dcmd/Dcmd.Linux.powerpc.cfg
				fi
			fi
		fi
	fi
fi

#Add ecdsa host key to sshd_config for releases >= v5.0.0
if [ $TO_MAJOR -ge 5 ]; then
     if [ -f $SSHD_CONFIG_FILE ]; then
       /bin/grep "HostKey /etc/ssh_host_ecdsa_key" $SSHD_CONFIG_FILE > /dev/null 2>&1
       ret=`echo $?`
       if [ $ret -ne 0 ]; then
               echo "HostKey /etc/ssh_host_ecdsa_key" >> $SSHD_CONFIG_FILE
       fi
		/bin/grep -i "MaxSessions" $SSHD_CONFIG_FILE 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			/bin/grep -i "MaxSessions 1" $SSHD_CONFIG_FILE
			if [ $? -ne 0 ]; then
				/bin/grep -v "MaxSessions" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
				echo "MaxSessions 1" >> $SSHD_CONFIG_FILE
			fi
		else
			echo "MaxSessions 1" >> $SSHD_CONFIG_FILE
		fi
		/bin/grep -v "PermitUserEnvironment" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
        if [ $TO_MAJOR -ge 7 ]; then
	    #Handles case of NOS 7.3.0 fedcert
	    check_OpenSSH_75 
            if [ $? -eq 1 ]; then
               Write_SSH_75_Config $SSHD_CONFIG_FILE
	    fi
        fi
     fi
     if [ -f $SSHD_CONFIG_FILE_MNT ]; then
       /bin/grep "HostKey /etc/ssh_host_ecdsa_key" $SSHD_CONFIG_FILE_MNT > /dev/null 2>&1
       ret=`echo $?`
       if [ $ret -ne 0 ]; then
               echo "HostKey /etc/ssh_host_ecdsa_key" >> $SSHD_CONFIG_FILE_MNT
       fi

       if [ $TO_MAJOR -ge 7 ]; then
	 #Handles case of NOS 7.3.0 fedcert
           check_OpenSSH_75
           if [ $? -eq 1 ]; then
               Write_SSH_75_Config $SSHD_CONFIG_FILE_MNT
           fi
       fi #MAJOR ge 7
		/bin/grep -i "MaxSessions" $SSHD_CONFIG_FILE_MNT 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
			/bin/grep -i "MaxSessions 1" $SSHD_CONFIG_FILE_MNT
			if [ $? -ne 0 ]; then
				/bin/grep -v "MaxSessions" $SSHD_CONFIG_FILE_MNT  > temp && mv temp $SSHD_CONFIG_FILE_MNT
				echo "MaxSessions 1" >> $SSHD_CONFIG_FILE_MNT
			fi
		else
			echo "MaxSessions 1" >> $SSHD_CONFIG_FILE_MNT
		fi
		/bin/grep -v "PermitUserEnvironment" $SSHD_CONFIG_FILE_MNT  > temp && mv temp $SSHD_CONFIG_FILE_MNT
     fi
fi

if [ $TO_MAJOR -le 7 ]; then
      if [ -f $SSHD_CONFIG_FILE ]; then	
	  check_OpenSSH_62
          if [ $? -eq 1 ]; then
             Write_SSH_62_Config $SSHD_CONFIG_FILE
          fi
      fi
      if [ -f $SSHD_CONFIG_FILE_MNT ]; then
	   check_OpenSSH_62
           if [ $? -eq 1 ]; then
               Write_SSH_62_Config $SSHD_CONFIG_FILE_MNT
           fi
      fi	   
fi
#Remove ecdsa host key from sshd_config for releases < v5.0.0
if [ $TO_MAJOR -lt 5 ]; then
     if [ -f $SSHD_CONFIG_FILE ]; then
        /bin/grep -v "HostKey /etc/ssh_host_ecdsa_key" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE

     fi
     if [ -f $SSHD_CONFIG_FILE_MNT ]; then
        /bin/grep -v "HostKey /etc/ssh_host_ecdsa_key" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT

     fi
fi

#
# Downgrade from Capricorn to leo
#
if [ $TO_MAJOR -eq 4 -a $TO_MINOR -eq 0 -a $TO_PATCH -eq 0 ]; then

	STARTUP_FILE="/var/config/vcs/scripts/startup-config"
#remove the "encryption-level 0" line from radisu/tacacs list
    awk 'match($1,"encryption-level") == 0 {print $0}' $STARTUP_FILE > rad_tac_no_encr.tmp
    cp rad_tac_no_encr.tmp $STARTUP_FILE
    rm rad_tac_no_encr.tmp
fi

#
# Downgrade to cap(4.1.0)
#
if [ $TO_MAJOR -eq 4 -a $TO_MINOR -eq 1 -a $TO_PATCH -eq 0 ]; then
    /usr/local/postgresql/9.1.3/bin/psql -p 9013 -d WaveDatabase -f /etc/fabos/NosSmd/certcleanup
    rm -rf /etc/fabos/Dcmd/Dcmd.Linux.powerpc.cert
fi

#
# Downgrade to leo(4.0.0/1)
#
if [ $TO_MAJOR -eq 4 -a $TO_MINOR -eq 0 ]; then
    rm -rf /etc/fabos/Dcmd/Dcmd.Linux.powerpc.cert
fi

#
# Upgrade from Leo to Leo Patch/Capricorn Patch/Taurus
# 
#
if [ $FROM_MAJOR -eq 4 -a $FROM_MINOR -eq 0 -a $FROM_PATCH -lt 1 ]; then
    if [ -e $FIPS_CONF_FILE ]; then
		/mnt/fabos/sbin/sshdconfigupdate ServerHostKeySize 1
		/mnt/fabos/sbin/sshdconfigupdate MinPrime 1
		/mnt/fabos/sbin/sshdconfigupdate ShaValue 2 postinst
	fi
fi

if [ $FROM_MAJOR -ge 5 ] && [ $TO_MAJOR -le 4 ]; then
	STARTUP_FILE="/var/config/vcs/scripts/startup-config"
	if [ -f $STARTUP_FILE ]; then
		/bin/grep -v "clock timezone" $STARTUP_FILE > temp && mv temp $STARTUP_FILE
	fi

    TACACS_CONF_FILE="/etc/fabos/tacplus.conf"
    if [ -f $TACACS_CONF_FILE ]; then
        /bin/grep -v "tacacsplus_src_addr" $TACACS_CONF_FILE > temp && mv temp $TACACS_CONF_FILE
    fi
fi

if [ $FROM_MAJOR -le 4 ] && [ $TO_MAJOR -ge 5 ]; then
	STARTUP_FILE="/var/config/vcs/scripts/startup-config"
	if [ -f $STARTUP_FILE ]; then
		RBRIDGE_LINE=$(awk '/^rbridge-id/{print NR}' $STARTUP_FILE | head -1)
		if [ ! -z $RBRIDGE_LINE ]; then
			TZ_NAME=`/fabos/cliexec/config get ts.tz 5`
			TOTAL_LINES=`/bin/cat $STARTUP_FILE | wc -l`
			if [[ -n $TZ_NAME ]]; then
				/bin/cat $STARTUP_FILE | head -$[$RBRIDGE_LINE]> startup-cfg-final.tmp 2>/dev/null
				/bin/echo " clock timezone $TZ_NAME" >> startup-cfg-final.tmp
				/bin/cat $STARTUP_FILE | tail -$[$TOTAL_LINES - $RBRIDGE_LINE] >> startup-cfg-final.tmp
				/bin/mv startup-cfg-final.tmp $STARTUP_FILE
				/bin/rm -rf startup-cfg-final.tmp
			fi
		fi
	fi

fi

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


if [ $TO_MAJOR -eq 4 -a $TO_MINOR -ge 1 ]; then
	remove_ipfilter_rule
fi

if [ $TO_MAJOR -ge 5 -a $TO_MINOR -ge 0 ]; then
	remove_ipfilter_rule
fi

#Upgrade from pre 7.4.0 to 7.4.0
#if ([ $FROM_MAJOR -eq 7 ] && [ $TO_MAJOR -ge 7 ]) && ([ $FROM_MINOR -eq 3 ] && [ $TO_MINOR -ge 4 ]) ; then
if [ "`/bin/grep '^admin:' /etc/passwd | /usr/bin/cut -f 3 -d ':'`" == "0" ]; then
        CONVERT_FROM_MAJOR=7
        CONVERT_FROM_MINOR=3
        CONVERT_TO_MAJOR=7
        CONVERT_TO_MINOR=4
#
#        if [ "$sw_platform" != "2000" ] && [ "$sw_platform" != "4000" ]; then
#            export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/mnt/fabos/lib/
#        fi
        /mnt/fabos/libexec/passwd_convert /etc/passwd $CONVERT_FROM_MAJOR.$CONVERT_FROM_MINOR $CONVERT_TO_MAJOR.$CONVERT_TO_MINOR > /dev/null 2>&1
        /bin/cp /mnt/etc/passwd /etc/passwd > /dev/null 2>&1
fi

#Downgrade from >= 7.4.0 to pre 7.4.0
if ([ $FROM_MAJOR -ge 7 ] && [ $TO_MAJOR -le 7 ]) && ([ $FROM_MINOR -ge 4 ] && [ $TO_MINOR -le 3 ]); then
        CONVERT_FROM_MAJOR=7
        CONVERT_FROM_MINOR=4
        CONVERT_TO_MAJOR=7
        CONVERT_TO_MINOR=$TO_MINOR
        /fabos/libexec/passwd_convert /etc/passwd $CONVERT_FROM_MAJOR.$CONVERT_FROM_MINOR $CONVERT_TO_MAJOR.$CONVERT_TO_MINOR > /dev/null 2>&1
        /bin/cp /mnt/etc/passwd /etc/passwd > /dev/null 2>&1
fi
#
# For Blackbird, update to latest FPGA for upgrades from nos4.0.1_bbd builds
#
is_blackbird
if [ $? == 1 ]; then
	if [ $FROM_MAJOR -eq 4 -a $FROM_MINOR -eq 0 -a $FROM_PATCH -eq 0 ]; then
		if [ $TO_MAJOR -eq 4 -a $TO_MINOR -eq 0 -a $TO_PATCH -eq 1 ]; then
			/mnt/fabos/factory/fpga_update auto
		fi
		if [ $TO_MAJOR -eq 5 ]; then
			/mnt/fabos/factory/fpga_update auto
		fi
	fi
fi

#
# Check if access gateway is default
# Change access gateway mode based on previous 
# used mode. 
#
is_accessgateway_def
if [ $? == 1 ]; then
    FEA_CONF_FILE="/mnt/fabos/config/fea-conf"
    # From NOS4.x.x to NOS 6.x.x; There is no AG in 4.x.x
    # So disable AG in 6.x.x
    if [ $FROM_MAJOR -eq 4 -a $TO_MAJOR -eq 6 ]; then
        echo "FEA     8       0       ag" >> $FEA_CONF_FILE 
    fi
    # For SWBD 137, 151
    case ${SWBD##SWBD} in
	        '137' | '151')
        # From NOS5.x.x to NOS 6.x.x; There is no AG in 5.x.x
        # So disable AG in 6.x.x
        if [ $FROM_MAJOR -eq 5 -a $TO_MAJOR -eq 6 ]; then
            echo "FEA     8       0       ag" >> $FEA_CONF_FILE 
        fi
        # From NOS6.x.x to NOS6.x.x
        if [ $FROM_MAJOR -eq 6 -a $TO_MAJOR -eq 6 ]; then
            if [ ! -f "/fabos/config/fea-conf" ]; then
        AG_DEF=`grep ACCESS_GATEWAY_IDENTIFIER /fabos/config/cap-conf`
                if [ ! -z "$AG_DEF" ]; then
                    echo "FEA     8       0       ag" >> $FEA_CONF_FILE 
                fi
            fi
        fi
		# Downgrade to NOS5.x.x from any higher version
		# Disable AG on 137/151 as AG was not supported.
		if [ $TO_MAJOR -eq 5 ]; then
			echo "FEA     8       0       ag" > $FEA_CONF_FILE
		fi
    esac	
fi

#
# Remove AG related files from the system
#

if [ -f /mnt/etc/fabos/persistent_NPIV_config_6_4 ]; then
	rm -f /mnt/etc/fabos/persistent_NPIV_config_6_4
fi

if [ -f /mnt/etc/fabos/fcid_virt_config ]; then
	rm -f /mnt/etc/fabos/fcid_virt_config
fi

# The cfgfosclean should be executed at the end of this script.
# This will cleanup the secondary partition files and hence no
# config update should happen after this.

is_dcmd_supported
if [ $? == 1 ]; then
	if [ -n "$FLAG" ] && [ $FLAG -eq 2 ]; then
		# This is the case of default-factory
		PATH_FWDL_CONF_FILE="/etc/fwdl.conf"
		RETAIN_BASE=0

		if [ -f $PATH_FWDL_CONF_FILE ]; then
			RETAIN_BASE=`sed -n 's/keep-baseconfig : \(\-\?[0-9]\+\)/\1/p' $PATH_FWDL_CONF_FILE`
		fi

		firmwaredownload_case
		if [ $? -lt 0 ] ; then
			/sbin/cfgfosclean -s -v "/" -b $RETAIN_BASE -o
		else
			/mnt/sbin/cfgfosclean -s -v "/mnt" -b $RETAIN_BASE -o
		fi
	fi
fi

if [ $FROM_MAJOR -eq 5 ]; then
#Remove ipadmd_log from /etc for releases v5.0.0 from release v5.0.0_ipv6
    if [ $TO_MAJOR -eq 5 -a $FROM_REVISION -eq 0 -a $TO_REVISION -eq 1 ]; then
        rm -f /etc/ipadmd_log.txt*
        rm -f /mnt/etc/ipadmd_log.txt*
    fi
#Remove ipadmd_log from /var/log for releases v5.0.0_ipv6 from release v5.0.0
    if [ $TO_MAJOR -eq 5 -a $FROM_REVISION -eq 1 -a $TO_REVISION -eq 0 ]; then
        rm -f /var/log/ipadmd_log.txt*
        rm -f /mnt/var/log/ipadmd_log.txt*
    fi
fi
#Remove ipadmd_log from /etc/ for releases v5.0.0 from releases < v5.0.0
if [ $FROM_MAJOR -lt 5 -a $TO_MAJOR -ge 5 ]; then 
    rm -f /etc/ipadmd_log.txt*
    rm -f /mnt/etc/ipadmd_log.txt*
fi
#
#downgrade from 5.0.0 to 4.x.x
#ecdsa keys not supported in versions below 5.0.0
#Remove ecdsa for releases < v5.0.0 in fips mode
#
if [ $TO_MAJOR -lt 5 ]; then
      PRIVKEY_DIR=/root/.ssh
      PRIVKEY_FILE_ECDSA=id_ecdsa
      EXPORT_PUBKEY_FILE_ECDSA=id_ecdsa.pub

      HOST_KEY_DIR=/etc
      HOST_ECDSA_KEY=ssh_host_ecdsa_key
      PUB_SUFFIX=.pub

      if [ -e $FIPS_CONF_FILE ]; then
          if [ -e $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA ]; then
                  size=`/bin/ls -la $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA | /bin/awk ' { print $5 } '`
                  /bin/dd if=/dev/zero of=$PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA bs=1 count=$size 2> /dev/null
                  /fabos/cliexec/config save $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA

                  /bin/rm $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA
                  /bin/rm $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_ECDSA
                  /fabos/cliexec/config save $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA
                  /fabos/cliexec/config save $PRIVKEY_DIR/$EXPORT_PUBKEY_FILE_ECDSA
          fi
    	  
	  #Downgrade from 5.0.0 to 4.x.x
	  #ecdsa host keys not supported in version below 5.0.0
	  #Remove ecdsa host key for releases < v5.0.0 in fips mode
	  
          if [ -e $HOST_KEY_DIR/$HOST_ECDSA_KEY ]; then
                  size=`/bin/ls -la $HOST_KEY_DIR/$HOST_ECDSA_KEY | /bin/awk ' { print $5 } '`
                  /bin/dd if=/dev/zero of=$HOST_KEY_DIR/$HOST_ECDSA_KEY bs=1 count=$size 2> /dev/null
                  /fabos/cliexec/config save $HOST_KEY_DIR/$HOST_ECDSA_KEY

                  /bin/rm $HOST_KEY_DIR/$HOST_ECDSA_KEY
                  /bin/rm $HOST_KEY_DIR/$HOST_ECDSA_KEY$PUB_SUFFIX
                  /fabos/cliexec/config save $HOST_KEY_DIR/$HOST_ECDSA_KEY
                  /fabos/cliexec/config save $HOST_KEY_DIR/$HOST_ECDSA_KEY$PUB_SUFFIX
          fi
      fi
fi
#
#Downgrade from 5.0.0 to 4.x.x
#Configure the correct Mac and Kex for SSH config files.
#sshd_config and ssh_config for releases < v5.0.0
#
if [ $TO_MAJOR -lt 5 ]; then

    /bin/grep -v "Macs" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
    /bin/grep -v "Macs" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
    /bin/grep -v "KexAlgorithms" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
    /bin/grep -v "KexAlgorithms" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE

    /bin/grep -v "Macs" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
    /bin/grep -v "Macs" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
    /bin/grep -v "KexAlgorithms" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
    /bin/grep -v "KexAlgorithms" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT

    if [ -e $FIPS_CONF_FILE ]; then
        if [ -f $SSHD_CONFIG_FILE ]; then
                echo "Macs hmac-sha1" >> $SSHD_CONFIG_FILE

                echo "Macs hmac-sha1" >> $SSH_CONFIG_FILE

                echo "KexAlgorithms diffie-hellman-group-exchange-sha256" >> $SSHD_CONFIG_FILE

                echo "KexAlgorithms diffie-hellman-group-exchange-sha256" >> $SSH_CONFIG_FILE
        fi
        if [ -f $SSHD_CONFIG_FILE_MNT ]; then
                echo "Macs hmac-sha1" >> $SSHD_CONFIG_FILE_MNT

                echo "Macs hmac-sha1" >> $SSH_CONFIG_FILE_MNT

                echo "KexAlgorithms diffie-hellman-group-exchange-sha256" >> $SSHD_CONFIG_FILE_MNT

                echo "KexAlgorithms diffie-hellman-group-exchange-sha256" >> $SSH_CONFIG_FILE_MNT
        fi
    fi
fi
#
#Ugrade from 4.x.x to 5.0.0
#configure the correct Macs for SSH config files.
#Add extra macs from sshd_config for releases >= v5.0.0
#
if [ $TO_MAJOR -eq 5 ]; then
    if [ -e $FIPS_CONF_FILE ]; then
        if [ -f $SSHD_CONFIG_FILE ]; then
                /bin/grep -v "Macs" $SSHD_CONFIG_FILE > temp && mv temp $SSHD_CONFIG_FILE
                echo "Macs hmac-sha1,hmac-sha2-256,hmac-sha2-512" >> $SSHD_CONFIG_FILE

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

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

               /bin/grep -v "KexAlgorithms" $SSH_CONFIG_FILE > temp && mv temp $SSH_CONFIG_FILE
                echo "KexAlgorithms ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256" >> $SSH_CONFIG_FILE
        fi
        if [ -f $SSHD_CONFIG_FILE_MNT ]; then
               /bin/grep -v "Macs" $SSHD_CONFIG_FILE_MNT > temp && mv temp $SSHD_CONFIG_FILE_MNT
                echo "Macs hmac-sha1,hmac-sha2-256,hmac-sha2-512" >> $SSHD_CONFIG_FILE_MNT

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

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

               /bin/grep -v "KexAlgorithms" $SSH_CONFIG_FILE_MNT > temp && mv temp $SSH_CONFIG_FILE_MNT
                echo "KexAlgorithms ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256" >> $SSH_CONFIG_FILE_MNT
        fi
    fi
fi
#
#upgrade from 4.x.x to 5.0.0 
#cipher handling
#
cipher_config_50_upgrade() {
        cipher_default=`/fabos/cliexec/config get cipher.radius 5 | /bin/grep  -c '!DH:HIGH:-MD5'`
        if [ "$cipher_default" -eq 1 ]; then
                echo "RADIUS cipher will be modified to be compatible with new firmware version"
                /fabos/cliexec/config set cipher.radius 5 '!ECDH:!DH:HIGH:-MD5:!CAMELLIA:!SRP:!PSK:!AESGCM:!TLSv1.2';
        fi
        cipher_default=`/fabos/cliexec/config get cipher.ldap 5 | /bin/grep  -c '!DH:HIGH:-MD5'`
        if [ "$cipher_default" -eq 1 ]; then
                echo "LDAP cipher will be modified to be compatible with new firmware version"
                /fabos/cliexec/config set cipher.ldap 5 '!ECDH:!DH:HIGH:-MD5:!CAMELLIA:!SRP:!PSK:!AESGCM';
        fi
	/fabos/cliexec/configcommit
}

#Downgrade from 5.0.0 to 4.x.x 
#cipher handling
cipher_config_50_downgrade() {
 	cipher_default=`/fabos/cliexec/config get cipher.radius 5 | /bin/grep  -c '!ECDH:!DH:HIGH:-MD5:!CAMELLIA:!SRP:!PSK:!AESGCM:!TLSv1.2'`
        if [ "$cipher_default" -eq 1 ]; then
                echo "RADIUS cipher will be modified to be compatible with new firmware version"
                /fabos/cliexec/config set cipher.radius 5 '!DH:HIGH:-MD5';
        fi
        cipher_default=`/fabos/cliexec/config get cipher.ldap 5 | /bin/grep  -c '!ECDH:!DH:HIGH:-MD5:!CAMELLIA:!SRP:!PSK:!AESGCM'`
        if [ "$cipher_default" -eq 1 ]; then
                echo "LDAP cipher will be modified to be compatible with new firmware version"
                /fabos/cliexec/config set cipher.ldap 5 '!DH:HIGH:-MD5';
        fi
	/fabos/cliexec/configcommit
}

#
# Downgrade from 5.0.0 to 4.0
#
if [ "$TO_MAJOR" -eq 4 -a "$TO_MINOR" -ge 0 ]; then
                cipher_config_50_downgrade
fi

if [ "$TO_MAJOR" -lt 5 ] || [ "$TO_MAJOR" -eq 5 -a "$TO_MINOR" -eq 0 -a "$TO_PATCH" -le 1 ]; then
	STARTUP_FILE="/var/config/vcs/scripts/startup-config"
    if [ -f $STARTUP_FILE ]; then
		/bin/grep -v "ssh server key" $STARTUP_FILE > temp && mv temp $STARTUP_FILE
		/bin/grep -v "root enable" $STARTUP_FILE > temp && mv temp $STARTUP_FILE
		/bin/grep -v "root access console" $STARTUP_FILE > temp && mv temp $STARTUP_FILE
		/bin/grep -v "ssh server standby" $STARTUP_FILE > temp && mv temp $STARTUP_FILE
		/bin/grep -v "telnet server standby" $STARTUP_FILE > temp && mv temp $STARTUP_FILE
	fi

	if [ ! -f $FIPS_CONF_FILE  ]; then
		sed "/root:/s/:::::0:/::::::/g" $SHADOW_FILE > temp
		/bin/mv temp $SHADOW_FILE
		/fabos/cliexec/config save $SHADOW_FILE
		sed "/root:/s/:::::0:/::::::/g" $SHADOW_FILE_MNT > temp
		/bin/mv temp $SHADOW_FILE_MNT
		/fabos/cliexec/config save $SHADOW_FILE_MNT
	fi
fi

update_ssh_key() {
	if [ ! -f $FIPS_CONF_FILE  ]; then
    STARTUP_FILE="/var/config/vcs/scripts/startup-config"
    if [ -f $STARTUP_FILE ]; then
        RBRIDGE_LINE=$(awk '/^rbridge-id/{print NR}' $STARTUP_FILE | head -1)
        if [ ! -z $RBRIDGE_LINE ]; then
            TOTAL_LINES=`/bin/cat $STARTUP_FILE | wc -l`
            /bin/cat $STARTUP_FILE | head -$[$RBRIDGE_LINE]> startup-cfg-final.tmp 2>/dev/null
            /bin/echo " ssh server key rsa 2048" >> startup-cfg-final.tmp
            /bin/echo " ssh server key ecdsa 256" >> startup-cfg-final.tmp
            /bin/echo " ssh server key dsa" >> startup-cfg-final.tmp
            /bin/cat $STARTUP_FILE | tail -$[$TOTAL_LINES - $RBRIDGE_LINE] >> startup-cfg-final.tmp
            /bin/mv startup-cfg-final.tmp $STARTUP_FILE
            /bin/rm -rf startup-cfg-final.tmp
		fi
	fi
	fi
}
if [ $FROM_MAJOR -eq 5 -a $FROM_MINOR -eq 0 -a $FROM_PATCH -eq 0 ] && [ $TO_MAJOR -eq 5 -a $TO_MINOR -eq 0 -a $TO_PATCH -eq 1 ]; then
		update_ssh_key
fi

if [ $FROM_MAJOR -lt 5 ] && [ $TO_MAJOR -ge 5 -a $TO_MINOR -ge 0 -a $TO_PATCH -ge 1 ]; then
		update_ssh_key
fi

#
#upgrade to >= 5.0.0
#
if [ "$FROM_MAJOR" -eq 4 -a "$FROM_MINOR" -ge 0 ] && [ "$TO_MAJOR" -eq 5 -a "$TO_MINOR" -ge 0 ]; then
                cipher_config_50_upgrade
fi

is_bootenv_mcmode_supported
if [ $? == 1 ]; then
	if [ -f '/mnt/etc/fabos/Dcmd/cluster.conf' ]; then
		clusterconfvalue=`cat /mnt/etc/fabos/Dcmd/cluster.conf`
		if [ $clusterconfvalue == "1" ]; then
			echo "bootenv mcmode true"
			bootenv mcmode true
		else
			echo "bootenv mcmode false"
			bootenv mcmode false
		fi
	else
		echo "bootenv mcmode false1"
		bootenv mcmode false
	fi
fi

# p2 install shall always be invoked at the end of postinst.
#
case ${SWBD##SWBD} in
	'131' | '137' | '138' | '151' | '155')
		if [ $FROM_MAJOR -eq 5 ] && [ $FROM_MINOR -eq 0 ] && [ $FROM_PATCH -eq 0 ]; then
			if [ $FROM_REVISION -eq 0 ]; then
				p2_install
			fi
		fi

		if [ $FROM_MAJOR -eq 4 ]; then
			p2_install
		fi
		;;
esac

#Enable swStateChangeTrap
if [ $TO_MAJOR -ge 5 ]; then
    echo "Setting swStateChangeTrap"
    key_val=`/fabos/cliexec/config get snmp.64mibCap.SW-MIB 6` ;
       #12th bit set. Decimal value is 4096 and hexadecimal equivalent is 1000
    key_val1=$(printf "%x\n" $((0x$key_val | 0x1000)))
    /fabos/cliexec/config set snmp.64mibCap.SW-MIB 6 $key_val1
    /fabos/cliexec/configcommit
fi

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

# To Allow sw mib in AG mode in 7.1.0 greater version, checking whether
# Switch is in AG mode, is so remosig the swmib key during upgrade.
# After upgrade, sw mib key will get updated with the new mib cap value
if [ $TO_MAJOR -eq 7 -a $TO_MINOR -ge 1 ] || [ $TO_MAJOR -gt 7]; then
 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
 /fabos/cliexec/config remove snmp.64mibCap.SW-MIB
 /fabos/cliexec/configcommit
fi
fi

if [ ! -f "/mnt/etc/fabos/Dcmd/DcmUserTags.wyser" ] ; then
    /usr/sbin/chroot /mnt ln -s /etc/fabos/NosSmd/DcmUserTags.wyser /etc/fabos/Dcmd/DcmUserTags.wyser
fi

if [ $TO_MAJOR -le 5 -a $TO_MINOR -eq 0 -a $TO_PATCH -lt 2 ]; then
    echo "Postinstall:Downgrade to <5.0.2 then remove snmpIpAclDB.bin" >> /etc/fabos/Dcmd/fwdl_db_copy_log
    rm -rf /mnt/etc/fabos/snmpIpAclDB.bin
fi

if [ $TO_MAJOR -eq 4 ]; then
    echo "Postinstall:Downgrade to 4.x.x then remove snmpIpAclDB.bin" >> /etc/fabos/Dcmd/fwdl_db_copy_log
    rm -rf /mnt/etc/fabos/snmpIpAclDB.bin
fi

if [ $TO_MAJOR -le 6 -a $TO_MINOR -eq 0 -a $TO_PATCH -le 1 ]; then
    echo "Postinstall:Downgrade to <=6.0.1 then remove snmpIpAclDB.bin" >> /etc/fabos/Dcmd/fwdl_db_copy_log
    rm -rf /mnt/etc/fabos/snmpIpAclDB.bin
fi

if ([ $FROM_MAJOR -eq 5 ] && [ $FROM_MINOR -eq 0 ] && [ $TO_MAJOR -eq 6 ] && [ $TO_MINOR -eq 0 ] && [ $TO_PATCH -eq 2 ]); then
        fipsmode
        if [ $? -eq 0 ]; then
		/usr/bin/killall -9 /usr/sbin/inetd
		/usr/sbin/inetd
	fi
fi

# If default user has access-time config, file entry may retain after default.
# Handling here to remove backend stale entries during fwdl 
# from 7.0.1 & its higher version to 7.0.0 & its lower version
if [ $TO_MAJOR -eq 7 -a $TO_MINOR -eq 0 -a $TO_PATCH -eq 0 ]; then
	if [ -f /mnt/etc/time.conf ]; then
		/bin/rm -rf /mnt/etc/time.conf 2> /dev/null
	fi
fi

if [ $TO_MAJOR -lt 7 ]; then
	if [ -f /mnt/etc/time.conf ]; then
		/bin/rm -rf /mnt/etc/time.conf 2> /dev/null
	fi
fi

delete_pam_time_so() {
	MNT_CONF_DIR=/mnt/etc/pam.d
	CONF_DIR=/etc/pam.d
	CONSOLE_CONF=ttylogin
	NET_CONF=netlogin
	SSH_CONF=sshd
	TEMP=/etc/temp.txt
	MNT_TEMP=/mnt/etc/temp.txt
	RM=/bin/rm

	touch $TEMP
	if [ $? != 0 ]; then
		echo "Unable to generate temp.txt"
		exit 1
	fi
	touch $MNT_TEMP
	if [ $? != 0 ]; then
		echo "Unable to generate temp.txt"
		exit 1
	fi
	if grep -q "pam_time.so" $MNT_CONF_DIR/$NET_CONF
	then
    	sed '/pam_time.so/ d' $MNT_CONF_DIR/$NET_CONF > $MNT_TEMP
		if [ -e "$MNT_TEMP" ]; then
			/bin/cp $MNT_TEMP $MNT_CONF_DIR/$NET_CONF
        	$RM -f $MNT_TEMP > /dev/null
    	fi
	fi
	if grep -q "pam_time.so" $CONF_DIR/$NET_CONF
	then
    	sed '/pam_time.so/ d' $CONF_DIR/$NET_CONF > $TEMP
        if [ -e "$TEMP" ]; then
			/bin/cp $TEMP $CONF_DIR/$NET_CONF
            $RM -f $TEMP > /dev/null
        fi
	fi
	if grep -q "pam_time.so" $MNT_CONF_DIR/$CONSOLE_CONF
	then
    	sed '/pam_time.so/ d' $MNT_CONF_DIR/$CONSOLE_CONF > $MNT_TEMP
        if [ -e "$MNT_TEMP" ]; then
			/bin/cp $MNT_TEMP $MNT_CONF_DIR/$CONSOLE_CONF
            $RM -f $MNT_TEMP > /dev/null
        fi
	fi
	if grep -q "pam_time.so" $CONF_DIR/$CONSOLE_CONF
	then
    	sed '/pam_time.so/ d' $CONF_DIR/$CONSOLE_CONF > $TEMP
        if [ -e "$TEMP" ]; then
			/bin/cp $TEMP $CONF_DIR/$CONSOLE_CONF
            $RM -f $TEMP > /dev/null
        fi
	fi
	if grep -q "pam_time.so" $MNT_CONF_DIR/$SSH_CONF
	then
    	sed '/pam_time.so/ d' $MNT_CONF_DIR/$SSH_CONF > $MNT_TEMP
        if [ -e "$MNT_TEMP" ]; then
			/bin/cp $MNT_TEMP $MNT_CONF_DIR/$SSH_CONF
            $RM -f $MNT_TEMP > /dev/null
        fi
	fi
	if grep -q "pam_time.so" $CONF_DIR/$SSH_CONF
	then
    	sed '/pam_time.so/ d' $CONF_DIR/$SSH_CONF > $TEMP
        if [ -e "$TEMP" ]; then
			/bin/cp $TEMP $CONF_DIR/$SSH_CONF
            $RM -f $TEMP > /dev/null
        fi
	fi
}

if [ $TO_MAJOR -eq 7 -a $TO_MINOR -eq 0 -a $TO_PATCH -eq 0 ] || [ $TO_MAJOR -lt 7 ]; then
	PATH_FWDL_LOG="/var/log/loginDebug.log"
	echo "`date` : Postinstall Script : Print the OLD contents of /etc/pam.d" >> PATH_FWDL_LOG
	echo '/mnt/etc/pam.d/netlogin' >> PATH_FWDL_LOG
	cat /mnt/etc/pam.d/netlogin >> PATH_FWDL_LOG
	echo '/etc/pam.d/netlogin' >> PATH_FWDL_LOG
	cat /etc/pam.d/netlogin >> PATH_FWDL_LOG
	echo "/mnt/etc/pam.d/ttylogin" >> PATH_FWDL_LOG
	cat /mnt/etc/pam.d/ttylogin >> PATH_FWDL_LOG
	echo "/etc/pam.d/ttylogin" >> PATH_FWDL_LOG
	cat /etc/pam.d/ttylogin >> PATH_FWDL_LOG
	echo "/mnt/etc/pam.d/sshd" >> PATH_FWDL_LOG
	cat /mnt/etc/pam.d/sshd >> PATH_FWDL_LOG
	echo "/etc/pam.d/sshd" >> PATH_FWDL_LOG
	cat /etc/pam.d/sshd >> PATH_FWDL_LOG 
	delete_pam_time_so
	echo "`date` : Postinstall Script : Print the NEW contents of /etc/pam.d after deleting pam_time.so from /etc/pam.d if exists" >> PATH_FWDL_LOG
	echo '/mnt/etc/pam.d/netlogin' >> PATH_FWDL_LOG 
	cat /mnt/etc/pam.d/netlogin >> PATH_FWDL_LOG
	echo '/etc/pam.d/netlogin' >> PATH_FWDL_LOG
	cat /etc/pam.d/netlogin >> PATH_FWDL_LOG
	echo "/mnt/etc/pam.d/ttylogin" >> PATH_FWDL_LOG
	cat /mnt/etc/pam.d/ttylogin >> PATH_FWDL_LOG
	echo "/etc/pam.d/ttylogin" >> PATH_FWDL_LOG
	cat /etc/pam.d/ttylogin >> PATH_FWDL_LOG
	echo "/mnt/etc/pam.d/sshd" >> PATH_FWDL_LOG
	cat /mnt/etc/pam.d/sshd >> PATH_FWDL_LOG
	echo "/etc/pam.d/sshd" >> PATH_FWDL_LOG
	cat /etc/pam.d/sshd >> PATH_FWDL_LOG
fi

if [ $FROM_MAJOR -le 7 ]; then
    if [ $FROM_MAJOR -eq 7 -a $FROM_MINOR -eq 0 -a $FROM_PATCH -eq 0 ]; then
		handle_pam_conf_v2
    elif [ $FROM_MAJOR -eq 7 -a $FROM_MINOR -eq 0 -a $FROM_PATCH -ge 1 -a $TO_MAJOR -eq 7 -a $TO_MINOR -eq 0 -a $TO_PATCH -eq 1 ]; then
		handle_pam_conf_v2
    elif [ $FROM_MAJOR -ge 7 -a $FROM_MINOR -ge 0 -a $FROM_PATCH -ge 0 ]; then
        :
    else
		handle_pam_conf_v2
    fi
fi

if [ $sw_platform == 164 ]; then 

	TX_DISABLE="mw.l 0x877504d8 0 1; mw.l 0x87750550 0x1c8 1; sleep 1; mw.l 0x87750448 0x01000000 1; mw.l 0x87750448 0x21000000 1" 
	BOOTCMD=$( bootenv bootcmd ) 

	if ! echo $BOOTCMD | grep -q "$TX_DISABLE"; then 
		bootenv bootcmd "$TX_DISABLE;$BOOTCMD" 
	fi 

fi 

if [ $FROM_MAJOR -lt 7 ] || [ $FROM_MAJOR -eq 7 -a $FROM_MINOR -lt 4 ] || [ $FROM_MAJOR -eq 7 -a $FROM_MINOR -eq 4 -a $FROM_PATCH -le 1 -a $FROM_REVISION -lt 7 ]; then
	keyLabel=`/fabos/cliexec/config get ssl.pvtkey 5`
	keyType=`/fabos/cliexec/config get ssl.pvtkey.type 5`
	keySize=`/fabos/cliexec/config get ssl.pvtkey.size 5`
	if [ "$keyLabel" != "none" ] && [ "$keyType" != "none" ] && [ "$keySize" != "none" ]; then
		/fabos/cliexec/config set ssl.pvtkey.$keyLabel 5 $keyType,$keySize
	fi

	tp=`/fabos/cliexec/config get ssl.trustpoint 5`
	if [ "$tp" != "none" ]; then
		assoc=`/fabos/cliexec/config get ssl.association 2`
		if [ $assoc == 1 ]; then
			if [ "$keyLabel" != "none" ]; then
				/fabos/cliexec/config set ssl.trustpoint.$tp 5 $keyLabel
			fi
		else
			/fabos/cliexec/config set ssl.trustpoint.$tp 5 none
		fi
	fi

	rootcacert=`/fabos/cliexec/config get ssl.root.certfile 5`
	if [ "$rootcacert" != "none" ]; then
		/fabos/cliexec/config set ssl.cacert.https 5 $rootcacert
		if [ "$tp" != "none" ]; then
			/fabos/cliexec/config set ssl.certtp.https 5 $tp
		fi
	fi

	swcert=`/fabos/cliexec/config get ssl.certfile 5`
	if [ "$swcert" != "none" ]; then
		/fabos/cliexec/config set ssl.swcert.https 5 $swcert
	fi
	/fabos/cliexec/config update
fi

grep 3 /etc/fabos/pwron_fips_status
if [ $? -eq 0 ];then
	bootenv update_crc 0xC0DEFEED
fi

exit 0
