#!/bin/sh
#
#    Copyright (c) 2009-10 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    File name:   trig_hostkey
#    Module name: fabos/src/security/trig_hostkey.sh
#
#	This trigger will be preventing the overwriting of valid RSA keys after
#	fwdl on standby in case of 6.4->7.0
#

export PATH=/fabos/sbin:/fabos/bin:/bin:/usr/bin:/sbin:/usr/sbin:/fabos/cliexec:/fabos/libexec:
FROM_MAJOR=`echo $2 |cut -d '.' -f 1`
TO_MAJOR=`echo $3 |cut -d '.' -f 1`

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

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

}

active_file=`/bin/echo $1 | /usr/bin/cut -c 5-`
if [ $FROM_MAJOR -le 6 ] && [ $TO_MAJOR -eq 7 ]; then
	/bin/cp $active_file /mnt$active_file > /dev/null  2>&1
else
	if [ $1 = "/mnt/etc/ssh_host_rsa_key" ] || [ $1 = "/mnt/etc/ssh_host_rsa_key.pub" ]; then
		# "config get" for fips mode returns value only if called from
        # default VF. So, temporarily set FABOS_SWITCHNO to 0 and then
        # revert it back to its original value after "config get"
	checkFipsMode
    	retVal=$?
        if [ $retVal -eq 1 ]; then
	       	var=`/usr/bin/ssh-keygen -lf $1 | cut -c 1-4`
        	if [ $var -lt 2048 ]; then
			if [ -f "/mnt/etc/ssh_host_rsa_key" ]; then
		        	/bin/rm /mnt/etc/ssh_host_rsa_key > /dev/null  2>&1
			fi

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