#!/bin/sh
#
#    Copyright (c) 2006-2008 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    File name:   seccertutil
#    Module name: fabos/src/security/seccertutil.sh
#
#    This script manages third party certificates.
#
export PATH=/fabos/sbin:/fabos/bin:/bin:/usr/bin:/sbin:/fabos/cliexec
export OPENSSL_CONF=/etc/fabos/openssl.cnf

# commands
RM=/bin/rm
LS=/bin/ls
LL="/bin/ls -l"
CUT="/usr/bin/cut"
OPENSSL_CMD=/usr/bin/openssl
# OPENSSL_CMD_NO_FIPS is required as OPENSSL_CMD changes to fipsopenssl in FIPS mode.
OPENSSL_CMD_NO_FIPS=/usr/bin/openssl
CONFIGSHOW_CMD="/fabos/cliexec/configshow -chassis"
TMP_DIR=/tmp
switchIPv6=0
PROT_FTP_PORT_MODE="Falling back to PORT instead of PASV mode."
# File locations and suffixes
ROOT_DIR=/etc/fabos
CERT_DIR=$ROOT_DIR/certs/sw0
CMM_DIR=$ROOT_DIR/certs/cmm
CRT_SUFFIX=.crt
CER_SUFFIX=.cer
PEM_SUFFIX=.pem
CSR_SUFFIX=.csr
PSK_SUFFIX=.psk
CAP_PPH_SUFFIX=.pp 
PVT_KEY=pvt_key 
PVT_KEY_FILE=$CERT_DIR/$PVT_KEY
CONFIG_FILE=$ROOT_DIR/openssl.cnf
CSR_GEN_INFO=/tmp/csr_gen_info

# The options of the command
CERT_GEN_KEY=genkey
CERT_DEL_KEY=delkey
CERT_GEN_CSR=gencsr
CERT_SHOW=show
CERT_DELE=delete
CERT_GEN=generate
CERT_DEL_CSR=delcsr
CERT_SHOW_CSR=showcsr
CERT_EXPORT=export
CERT_IMPORT=import
CERT_IMPORT_CMM=import_cmm
CERT_FIPS_COMPL=fips_compl
CERT_HELP=help

PRIVKEY_DIR=/root/.ssh
PRIVKEY_FILE_OLD=id_dsa
PRIVKEY_FILE=id_rsa
IMPORT_PUBKEY_DIR=/fabos/users/admin/.ssh
IMPORT_PUBKEY_FILE=authorized_keys

# Sub-options for "delkey"
DELKEYALL_OPT="-all"
NOWARN_OPT="-nowarn"

# local variables for convenience
INFINITE_LOOP=1
CERT_FILE=certificate
CSR_FILE=CSR
CSR_FILE_PATH=$CERT_DIR/$switchIp$CSR_SUFFIX
COUNTRY_CODE="country"
FILE_NAME="file_name"
fileType=
userInput=
response=
country=
state=
cn=
locality=""
company=
host=
domain=
switchIP=
wwn=
unit=
protocol=
ipAddr=
remoteDir=
certFileName=
cmmCertFile=
userName=
password1=
PROT_FTP=ftp
PROT_SCP=scp
RSA_KEY=rsa
DSA_KEY=dsa
DSA_PARAM_FILE=/etc/fabos/dsa1024.pem
WEBDHANDLER=/fabos/libexec/webdcfghandler
HTTPCONFIG=http.ssl.enabled
CERTCONFIG=ssl.certfile
ROOTCERTCONFIG=ssl.root.certfile
DEFAULTROOTCERTCONFIG="none"
HTTPFQDN="http.fqdn"
HTTPFQD="http.domn"


# LDAP definitions
FIPS_CONF_FILE=/etc/fabos/fabos.0.conf
LDAPCACERT_OPT="-ldapcacert"
TEMP_CACERT="tempca.pem"
LDAP_DIR=$ROOT_DIR/certs/ldap
LDAP_CERT_FILE="ldap ca certificate"
LDAP_CACERT_FILE="swLdapca.pem"
TEMP_CACRT="tempca1.pem"

# SYSLOG CA definitions
SYSLOGCACERT_OPT="-syslogcacert"
SYSLOGCA_DIR=/etc/syslog-ng/ca.d
SYSLOG_CERT_FILE="Syslog CA certificate"
SYSLOGCA_CERT_FILE=
SYSLOG_LINK_HASH="syslog_link_hash"
TEMP_SYSLOG_LINK_HASH="temp_syslog_link_hash"

# Common cert definations
#COMMONCERT="-commoncert"
COMMONCERTALL="-commoncertall"
COMMONCERT_PRVT_KEY="pvt_key"
COMMONCERT_SW_CSR="-commonswcsr"
COMMONCERT_SW_CRT="-commonswcert"
COMMONCERT_CA_CRT="-commoncacert"
COMMONCERT_CA_FILE="commonCA.pem"

# FCAP definations
FCAP_ROOT_CER_SUFFIX=.rootcrt
FCAP_CERT_KEY_SUFFIX=.key
FCAPCACERT_OPT="-fcapcacert"
FCAPSWCERT_OPT="-fcapswcert"
FCAPSWCSR_OPT="-fcapswcsr"
SWCSR_OPT="-swcsr"
FCAP="-fcapall"
ALL="-all"
FCAP_ALL="fcap"
FCAP_DIR=$ROOT_DIR/pki/tp
FCAP_CERT_FILE="fcap ca certificate"
FCAP_ALL_FILE=FCAP-Files
FCAP_SW_CERT_FILE=FCAP-SW-Certificate
FCAP_CA_CERT_FILE=FCAP-CA-Certificates
FCAP_CACERT_FILE="switch.0.rootcrt"
FCAP_SWCERT_FILE="switch.0.crt"
FCAP_SWCSR_FILE="switch.0.csr"
FCAP_SWPPH_FILE="switch.0.pp"
FCAP_SWPRVKEY_FILE="switch.0.key"
FCAP_CERT_CONF_FILE="cert.conf" 
FCAP_TEMP_FILE="fcap.temp"
FCAP_TOUCH_FILE="fcap.cert"
FCAP_CERT_HEADER=-----BEGIN\ CERTIFICATE-----
FCAP_CERT_FOOTER=-----END\ CERTIFICATE-----
MAX_ALLOWED_CACERTS=5
exportFile="exportCheck.txt"
curLogin=`echo $SWLOGNAME`
AUTHPOLICY=auth.policy

#cert file name to configure in import command
certFileName=""

#used this for audit
AUDIT_NOTIFY=/fabos/libexec/seccert_notify
deleteStatus=

commoncert=0

#Exit for trapped signals
trap 'exit 1' SIGINT

#
# copied from /fabos/src/setup/profile
#
setcontext()
{
    if [ "$1" != "chassis" ]
    then
    	# 261476: in case set_switch_env() return code is -1 
	SW_CONTEXT_RC=`lscfg_util --switch $1`
        eval $(lscfg_util --switch $1)
    else
        eval $(lscfg_util --chassis)
    fi
	export ROLE_ID=root
} 

getSwichId() {
	DEFAULT_SW_FID=128
	VID=-1
                         
	if [ ! -e /fabos/link_sbin/lscfg_test ]
	then
		/bin/ln -s /fabos/cliexec/lscfg_util /fabos/link_sbin/lscfg_test 2> /dev/null        
	fi

	if [ "$(lscfg_test --vf_enabled 2> /dev/null)" = 'VF is enabled.' ]; then 
		if [ "$1" == "default" ]; then
			VID=`lscfg_test --fid 0`
		elif [ "$1" == "logical" ]; then
			VID=`printenv | grep -v '^result'| grep -v '^oldcmd'|grep CURRENT_VF | cut -d"=" -f2`
		fi
	fi
	
 	if [ -e /fabos/link_sbin/lscfg_test ]
	then
	        /bin/rm /fabos/link_sbin/lscfg_test
	fi
	
	return $VID
}
# Check if the given file can be removed
# If the file is required by Encryption, then we don't
# want to remove it
# Args - <filename> <delflag>
check_for_removal()
{
	delflag=$2
	if [ $delflag -eq 1 ]; then
		# -all option specified, truncate encryption certs as well
		return 0;
	fi

	if [ -z $1 ]; then
		return 1;
	fi

	flname=$1

	#ret=`echo $flname | grep -i "kac_[a-zA-Z0-9_]*cert"`
	ret=`echo $flname | grep -i "kac_[a-zA-Z0-9_]*"`
	if [ -n "$ret" ]; then				
		return 1
	fi
	# Skip kv files
	ret=`echo $flname | grep -i "kv[a-zA-Z0-9_]*_cert\.pem"`
	if [ -n "$ret" ]; then				
		return 1
	fi
	# Skip openssl conf
	ret=`echo $flname | grep -i "openssl_cp[a-zA-Z0-9_]*"`
	if [ -n "$ret" ]; then				
		return 1
	fi
	# Skip all FIPS certs
	ret=`echo $flname | grep -i "fips\.[a-zA-Z0-9_]*\.pem"`
	if [ -n "$ret" ]; then
		return 1
	fi
	# Skip all cp certs
	ret=`echo $flname | grep -i "[a-zA-Z0-9_]*my_cp_cert.pem"`
	if [ -n "$ret" ]; then
		return 1
	fi
	ret=`echo $flname | grep -i "[a-zA-Z0-9_]*my_cp_priv.pem"`
	if [ -n "$ret" ]; then
		return 1
	fi
	ret=`echo $flname | grep -i "[a-zA-Z0-9_]*my_priv.pem"`
	if [ -n "$ret" ]; then
		return 1
	fi
	ret=`echo $flname | grep -i "[a-zA-Z0-9_]*my_cert.pem"`
	if [ -n "$ret" ]; then
		return 1
	fi
	return 0
}

#
# prompt the user and check for errors
# arguments:
# The first argument is the actual prompt
#
readAndValidate_Export() {

	if [ -z "$2" ] && [ -z "$certFileName" ]; then
		echo "Input string is NULL"
		exit 1
	fi

	while [ $INFINITE_LOOP ]
	do
		if [ $# -eq 2 ]; then
			echo -n $2
		fi
		if [ -z "$certFileName" ]; then	
			read userInput
		else
			userInput=$certFileName
		fi
		if [ -z "$userInput" ]; then
			echo "Input must not be NULL"
			continue
		fi

		# put global certificate file name
		cLen=`expr length $userInput`
		if  [ "$cLen" -lt 5 ]; then
			echo "Invalid name: LDAP Certificate file name must have \"$PEM_SUFFIX\" or \".crt\" or  \".cer\" suffix"
			exit 1
		fi

		let dotIndex="$cLen"-3
		fileSuffix=`expr substr $userInput $dotIndex $cLen`
		if [ "$fileSuffix" != "$PEM_SUFFIX" ] && [ "$fileSuffix" != "$CER_SUFFIX" ] && \
			 [ "$fileSuffix" != "$CRT_SUFFIX" ]; then
			echo "Invalid name: Certificate file name must have \"$PEM_SUFFIX\" or \".crt\" or  \".cer\" suffix"
			exit 1
		fi

		if [ $1  = "SYSLOG" ]; then
			if [ ! -e "$SYSLOGCA_DIR/$userInput" ]; then
				echo "Specified SYSLOG CA certificate file does not exist."
				exit 1
    		fi
    		return 0
		fi

		if [ ! -e "$LDAP_DIR/$userInput" ]; then
			echo "Specified LDAP certificate file does not exist."
			exit 1
		fi

		return 0
	done
}
 
countAndValidateCertificates() {
	heads=0
	foots=0

	IFS_=${IFS}; IFS=$'\n'
	for LINE in `cat $1`;	do
		if [ $foots -gt $heads -o $(($heads-$foots)) -gt 1 ]; then
			break;
		fi

 		if [ "$LINE" == "$FCAP_CERT_HEADER" ] ; then
	        heads=$((heads+1))
		fi

		if [ "$LINE" == "$FCAP_CERT_FOOTER" ] ; then
	        foots=$((foots+1))
		fi
	done
	IFS=${IFS_} 

	if [ $heads -ne $foots ]; then
		echo "Bad certificate format."
		heads=-1
	elif [ $heads -eq 0 ]; then
		echo "Certificate in bad format."
		echo "Warning: Certificate may be need conversion if it is in windows file format."
		heads=-1
	fi

	return $heads
}

readNumFCAPRootCaCerts() {

	counter=0
	if [ -f $FCAP_DIR/$FCAP_CERT_CONF_FILE ]; then

		#Now we parse the file to look for number of root CA certificates.
		IFS_=${IFS}; IFS=$'\n'
		for LINE in `cat $FCAP_DIR/$FCAP_CERT_CONF_FILE`; do
			validate_string=`echo "$LINE" | awk -F':' ' { print $1 } '`

			if [ $validate_string == "ROOT_CA_CERTIFICATES" ] ; then
				counter=`echo "$LINE" | awk -F':' ' { print $2 } '`
			fi		
		done
		IFS=${IFS_} 
	else
		echo "Operation Failed."
	fi   

	return $counter
}

cleanUpFCAP() {
	switch_cert_name="NONE"
	cat /dev/null > $FCAP_DIR/$FCAP_SWCSR_FILE
	cat /dev/null > $FCAP_DIR/$FCAP_SWCERT_FILE
	cat /dev/null > $FCAP_DIR/$FCAP_SWPRVKEY_FILE
	cat /dev/null > $FCAP_DIR/$FCAP_SWPPH_FILE
	cat /dev/null > $FCAP_DIR/$FCAP_TOUCH_FILE
	updateFCAPConfigFile "SWITCH_CERT_NAME:$switch_cert_name"
	return 0
}

cleanUpHTTPS() {
 	file=`$LS $CERT_DIR/*$CRT_SUFFIX $CERT_DIR/*$CER_SUFFIX \
		$CERT_DIR/*$PEM_SUFFIX $CERT_DIR/*$PSK_SUFFIX \
		$CERT_DIR/*$CSR_SUFFIX 2> /dev/null`
	if [ ! -z "$file" ]; then
	    for i in $file
	    do
		if [ -s "$i" ]; then
			check_for_removal $i $delall 2> /dev/null
			if [ $? -eq 0 ]; then
				cat /dev/null > $i
			fi
		fi
	    done
	fi

	if [ -e "$PVT_KEY_FILE" ]; then
			size=`/bin/ls -la $PVT_KEY_FILE | /bin/awk ' { print $5 } '`
			/bin/dd if=/dev/zero of=$PVT_KEY_FILE bs=1 count=$size 2> /dev/null
			cat /dev/null > "$PVT_KEY_FILE"
	fi


	getSwichId "logical"
	VID=$?

	if [ $VID != -1 ];then
		 # This means VF is enabled.
		 getSwichId "default"
		 DEFAULT_VID=$?
		 setcontext $DEFAULT_VID
	fi

  	
	# reset config certificate name, disable secure protocols and
	# send notification
    	# http state info can be read only from default switch

	resetSSLState
	/fabos/cliexec/config save $CERT_DIR

	if [ $VID != -1 ];then
		setcontext $VID
	fi
 
	$AUDIT_NOTIFY "$CERT_DEL_KEY" "$file"
}

syncUpFCAP() {
 
 	config save $FCAP_DIR/$FCAP_SWCERT_FILE
	config save $FCAP_DIR/$FCAP_CACERT_FILE
	config save $FCAP_DIR/$FCAP_SWCSR_FILE
	config save $FCAP_DIR/$FCAP_SWPPH_FILE
	config save $FCAP_DIR/$FCAP_SWPRVKEY_FILE
	config save $FCAP_DIR/$FCAP_TOUCH_FILE
	config save $FCAP_DIR/$FCAP_CERT_CONF_FILE 
	return 0

}

countImportedRootCaCerts() {

	copy_cert=0
	output="NO"
	check="NO"
	counter=0

	#Now we check if all the certificates in the imported file are root CA certificates or not
	IFS_=${IFS}; IFS=$'\n'
	for LINE in `cat $1`;	do
		if [ "$LINE" == "$FCAP_CERT_HEADER" ] || [ $copy_cert -eq 1 ] ; then
			echo $LINE >> $FCAP_DIR/$FCAP_TEMP_FILE
			copy_cert=1
		fi

		if [ "$LINE" == "$FCAP_CERT_FOOTER" ] ; then
		       copy_cert=2
		fi

		if [ $copy_cert -eq 2 ] ; then
			output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $FCAP_DIR/$FCAP_TEMP_FILE $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null`
			check=`echo "$output" | awk ' {print $2} '`
			if [ "$check" == "OK" ] ; then
				copy_cert=0
				counter=`expr $counter  + 1`
			fi
			cat /dev/null > $FCAP_DIR/$FCAP_TEMP_FILE
		fi
	done
	IFS=${IFS_}

	return $counter
}

updateFCAPConfigFile() {
	found=0
	record=`echo $1 | awk -F ':' '{ print $1 }'`
	TEMP_FILE="temp"
	cat /dev/null > $FCAP_DIR/$TEMP_FILE
	
	if [ $record == "ROOT_CA_CERTIFICATES" ]; then
       		 # Search for the other record SWITCH_CERT_NAME."
		IFS_=${IFS}; IFS=$'\n'
		for LINE in `cat $FCAP_DIR/$FCAP_CERT_CONF_FILE`; do
		    validate_string=`echo "$LINE" | awk -F':' ' { print $1 } '`

		    if [ $validate_string == "SWITCH_CERT_NAME" ] ; then
			    sw_cert_name=`echo "$LINE" | awk -F':' ' { print $2 } '`
			    found=1
		    fi		
		done
		IFS=${IFS_}

		echo "$1" > $FCAP_DIR/$TEMP_FILE
        	
		if [ $found == 1 ]; then 
                	echo "SWITCH_CERT_NAME:$sw_cert_name" >> $FCAP_DIR/$TEMP_FILE
		fi
	elif [ $record == "SWITCH_CERT_NAME" ]; then
       		 # Search for the other record ROOT_CA_CERTIFICATES"
		IFS_=${IFS}; IFS=$'\n'
		for LINE in `cat $FCAP_DIR/$FCAP_CERT_CONF_FILE`; do
		    validate_string=`echo "$LINE" | awk -F':' ' { print $1 } '`

		    if [ $validate_string == "ROOT_CA_CERTIFICATES" ] ; then
			    ca_certs=`echo "$LINE" | awk -F':' ' { print $2 } '`
			    found=1
		    fi		
		done
		IFS=${IFS_}

		echo "$1" > $FCAP_DIR/$TEMP_FILE
        	
		if [ $found == 1 ]; then 
                	echo "ROOT_CA_CERTIFICATES:$ca_certs" >> $FCAP_DIR/$TEMP_FILE
		fi
	fi

	mv $FCAP_DIR/$TEMP_FILE $FCAP_DIR/$FCAP_CERT_CONF_FILE	
}

certNameValidate() {

	# put global certificate file name
	userInput=$1
	cLen=`expr length $userInput`
	if  [ "$cLen" -lt 5 ]; then
		if [ $fcapCaCert -eq 1 ] || [ $fcapSwCert -eq 1 ] || [ $caCert -eq 1 ]; then
  			echo "Invalid name: Certificate file name must have" \
				".pem suffix"
 	      	else
         		echo "Invalid name: Certificate file name must have" \
				".crt or .cer or .pem or .psk suffix"
	       	fi
		exit 1
	fi

	let dotIndex="$cLen"-3
	fileSuffix=`expr substr $userInput $dotIndex $cLen`
	if [ $fcapCaCert -eq 1 ] || [ $fcapSwCert -eq 1 ] || [ $caCert -eq 1 ]; then
		if [ "$fileSuffix" != "$PEM_SUFFIX" ]; then
   			echo "Invalid name: Certificate file name must have" \
				".pem suffix"
				exit 1
		fi
	else
		if [ "$fileSuffix" != "$CRT_SUFFIX" ] && \
			[ "$fileSuffix" != "$PEM_SUFFIX" ] && \
			[ "$fileSuffix" != "$CER_SUFFIX" ]&& \
			[ "$fileSuffix" != "$PSK_SUFFIX" ]; then
			echo "Invalid name: Certificate file name must have" \
				" .cer or .crt or .pem or .psk suffix $fileSuffix"
			exit 1
		fi

		if [ "$2" != "CERT_IMPORT_CMM" ]; then
#			In case of CMM we already will have the file in location
			if [ $ldapCaCert -eq 1 ]; then
				if [ -e "$LDAP_DIR/$userInput" ]; then
					echo "$userInput: LDAP Certificate already exists."
					echo "Delete $userInput with delete option."
					exit 1
				fi
			else
				if [ -s "$CERT_DIR/$userInput" ]; then
					echo "$userInput: Certificate already exists."
					echo "Delete $userInput with delete option."
					exit 1
				fi
			fi
		fi
	fi
}


# routine to validate a certificate being imported against the private key of the switch.
certPvtKeyValidate() {
	invalSwCert=0
	if [ $swCert -eq 1 ]; then
		if [ ! -f $PVT_KEY_FILE ]; then
			echo "Https key does not exist on the switch. Please generate https key and csr.Aborting $1 operation.."
			if [ -e $CERT_DIR/$userInput ]; then
				rm $CERT_DIR/$userInput
			fi
			exit 1
		fi	
	fi
	if [ $fcapSwCert -eq 1 ]; then
		if [ ! -f $FCAP_DIR/$FCAP_SWPRVKEY_FILE ]; then
			echo " Fcap key does not exist on the switch. Please generate fcap key and csr.Aborting $1 operation.."
			if [ -e $FCAP_DIR/$userInput ]; then
				rm $FCAP_DIR/$userInput
			fi	
			exit 1
		fi	
	fi	
	if [ $commonSwCert -eq 1 ]; then
		if [ ! -f $FCAP_DIR/$FCAP_SWPRVKEY_FILE ]; then
			echo " Common Cert key does not exist on the switch. Please generate commoncert keys and csr.Aborting $1 operation.."
			if [ -e $FCAP_DIR/$userInput ]; then
				rm $FCAP_DIR/$userInput
			fi	
			exit 1
		fi
		if [ ! -f $PVT_KEY_FILE ]; then
			echo "Common Cert key does not exist on the switch. Please generate commoncert keys and csr.Aborting $1 operation.."
			if [ -e $CERT_DIR/$userInput ]; then
				rm $CERT_DIR/$userInput
			fi
			exit 1
		fi	
	fi

	if [ $fcapSwCert -eq 1 ] || [ $commonSwCert -eq 1 ]; then
			$OPENSSL_CMD x509 -in $FCAP_DIR/$userInput -inform PEM -outform DER -out $FCAP_DIR/$userInput.der > /dev/null 2>&1
			if [ $? != 0 ]; then
				echo "Bad format certificate. Exiting.."
				rm $FCAP_DIR/$userInput
				exit 1
			fi
			if [ -f $FCAP_DIR/$userInput.der ]; then
				rm $FCAP_DIR/$userInput.der
			fi
			certificate=$FCAP_DIR/$userInput
	else
		if [ "$fileSuffix" == "$CER_SUFFIX" ] || [ "$fileSuffix" == "$CRT_SUFFIX" ]; then
			$OPENSSL_CMD x509 -in $userInput -inform DER -outform PEM -out $CERT_DIR/$userInput.pem > /dev/null 2>&1
			if [ $? != 0 ]; then
				echo "Bad format certificate. Exiting.."
				rm $CERT_DIR/$userInput
				exit 1
			fi
			certificate=$CERT_DIR/$userInput.pem
		else
			#validate the file format
			$OPENSSL_CMD x509 -in $userInput -inform PEM -outform DER -out $CERT_DIR/$userInput.der > /dev/null 2>&1
			if [ $? != 0 ]; then
				echo "Bad format certificate. Exiting.."
				rm $CERT_DIR/$userInput
				exit 1
			fi
			if [ -f $CERT_DIR/$userInput.der ]; then
				rm $CERT_DIR/$userInput.der
			fi
			certificate=$CERT_DIR/$userInput
		fi
	fi
	
	if [ $fcapSwCert -eq 1 ] || [ $commonSwCert -eq 1 ]; then
		csrFile=$FCAP_DIR/$FCAP_SWCSR_FILE
	else
		csrFile=$CERT_DIR/$switchIp$CSR_SUFFIX
		pvtkeyhash=`$OPENSSL_CMD rsa -noout -modulus -in $PVT_KEY_FILE  2> /dev/null | \
						$OPENSSL_CMD_NO_FIPS md5`
		/bin/chmod 400 $PVT_KEY_FILE
	fi	
	

	certkeyhash=`$OPENSSL_CMD x509 -noout -modulus -in $certificate  2> /dev/null | $OPENSSL_CMD_NO_FIPS md5`
	csrhash=`$OPENSSL_CMD req -in $csrFile -noout -modulus  2> /dev/null | $OPENSSL_CMD_NO_FIPS md5`

	# delete the temporary .pem created for validating .cer/.crt certificates
	if [ -f $CERT_DIR/$userInput.pem ]; then
		rm $CERT_DIR/$userInput.pem
		certificate=$CERT_DIR/$userInput
	fi
	# Comparicon against pvt key is needed for swcert
	if [ $fcapSwCert != 1 ] &&  [ $commonSwCert != 1 ] && [ "$certkeyhash" != "$pvtkeyhash" ]; then
		invalSwCert=1
	fi
	if [ "$certkeyhash" != "$csrhash" ] || [ $invalSwCert -eq 1 ]; then
		echo "Invalid switch certificate.Exiting"
		rm $certificate
		exit 1
	fi

}



#
# prompt the user and check for errors
#
# arguments:
#
# The first argument is the actual prompt
# The second argument is the type. Based on this validation is done.
# If the second arg is null, not validation is done.
#
readInput() {

	if [ -z "$1" ]; then
		echo "Input string is NULL"
		exit 1
	fi

	while [ $INFINITE_LOOP ]
	do
		echo -n $1
		read userInput
		if [ -z "$userInput" ]; then
			echo "Input must not be NULL"
			continue
		fi
	
		return 0
	done
}

#
# This routine checks the following
# 1. If the certificate being deleted is configured as
# 	 as the current certificate
# 2. Check if the secure protocols are enabled
# 3. If the certficate is NOT current active one,
# 	 return 0, else if secure protocols are enabled, exit.
# 4. return 0
#
check_secure_protocols() {

	configCert=`config get $CERTCONFIG 5`
	caCert=`config get $ROOTCERTCONFIG 5`

	if [ "$1" != "$configCert" ] && [ "$1" != "$caCert" ]; then
		return 0
	fi

	httpSEnabled=`config get $HTTPCONFIG 1`

	if [ "$httpSEnabled" -eq 1 ]
	then
		echo
		echo "Deleting the certificate will disable"
		echo "Secure protocols."
		echo
		return 0
	fi

	return 0
}

#
# Ask the user if he really wants to delete a file.
# If "yes", then delete, else return.
# arguments:
# arg1: The file type, usually CSR or CRT
# arg2: The name of the actual file to be deleted
#
confirmDelete() {
	if [ -z $response ]; then
		echo "WARNING!!!"
		echo
		if [ $commoncert -eq 1 ];then
			echo "This will delete all switch specific common certificate(s) and disable secure protocols such as HTTPS"
			echo "ISLs may be segmented during next E-port(s) bring-up"
			echo "About to delete common cert: $2"
		else
			echo "About to delete $1: $2"
		fi

		echo -n "ARE YOU SURE (yes, y, no, n): [no] "
		read response

		if [ "$response" == "" ]; then
			response=no
		fi
	fi
	resp=`echo $response | tr "[:lower:]" "[:upper:]"`

	if [ "$resp" = "N" -o "$resp" = "NO" ]; then
		echo "Operation cancelled."
		return 1
	fi

	if [ "$resp" != "Y" -a "$resp" != "YES" ]; then
		echo "Invalid response."
		return 1
	fi

	if [ "$1" = "$CERT_FILE" ]; then
		if [ $ldapCaCert -eq 1 ];then
			# zeroize before delete
			size=`/bin/ls -la $LDAP_DIR/$2 | /bin/awk ' { print $5 } '`
                        /bin/dd if=/dev/zero of=$LDAP_DIR/$2 bs=1 count=$size 2> /dev/null
			$RM -rf $LDAP_DIR/$2 > /dev/null
			if [ $? -ne 0 ];then
				echo "Could not delete LDAP certificate"
				exit 1
			else
				echo "Deleted LDAP certificate successfully"
				config save $LDAP_DIR/$2
				return 0
			fi
		elif [ $syslogCaCert -eq 1 ];then
			if [ "$2" = "-all" ]; then
				file=`$LS $SYSLOGCA_DIR/*$PEM_SUFFIX  2> /dev/null`
				if [ ! -z "$file" ]; then
				 for i in $file
 				 do
				   size=`/bin/ls -la $i | /bin/awk ' { print $5 } '`
                        	   /bin/dd if=/dev/zero of=$i bs=1 count=$size 2> /dev/null
 				 done
				fi

				if [  -f $SYSLOGCA_DIR/$SYSLOG_LINK_HASH ]; then
			 	  cat /dev/null > $SYSLOGCA_DIR/$SYSLOG_LINK_HASH
				fi
				$RM -rf $SYSLOGCA_DIR/* > /dev/null
				if [ $? -ne 0 ];then
					echo "Could not delete Syslog CA certificates"
					exit 1
				else
					echo "Deleted all Syslog CA certificates successfully"
					/fabos/cliexec/config save $SYSLOGCA_DIR
					return 0
				fi
			else
				#Get the syslog link file
				SYSLOG_LINK=`/bin/cat $SYSLOGCA_DIR/$SYSLOG_LINK_HASH | /bin/grep "$2" | /bin/awk ' { print $2 }'`
				size=`/bin/ls -la $SYSLOGCA_DIR/$2 | /bin/awk ' { print $5 } '`

				# zeroize before delete
				/bin/dd if=/dev/zero of=$SYSLOGCA_DIR$/$2 bs=1 count=$size 2> /dev/null
				$RM -rf $SYSLOGCA_DIR/$2 > /dev/null

				if [ $? -ne 0 ];then
					echo "Could not delete Syslog CA certificate"
					exit 1
				else
					$RM -rf $SYSLOG_LINK > /dev/null
					/bin/sed "/$2/d" $SYSLOGCA_DIR/$SYSLOG_LINK_HASH > $SYSLOGCA_DIR/$TEMP_SYSLOG_LINK_HASH	
					/bin/cat  $SYSLOGCA_DIR/$TEMP_SYSLOG_LINK_HASH > $SYSLOGCA_DIR/$SYSLOG_LINK_HASH	
					$RM -rf $SYSLOGCA_DIR/$TEMP_SYSLOG_LINK_HASH > /dev/null
					echo "Deleted Syslog CA certificate successfully"
					/fabos/cliexec/config save $SYSLOGCA_DIR/$2
					/fabos/cliexec/config save $SYSLOG_LINK
					/fabos/cliexec/config save $SYSLOGCA_DIR/$SYSLOG_LINK_HASH
					/usr/bin/killall -q -s SIGHUP syslog-ng >> /var/log/syslog.log 2>&1
					return 0
				fi
			fi
		fi

		cat /dev/null > $CERT_DIR/$2

		if [ $? -ne 0 ];then
			echo "Could not delete specified certificate"
			exit 1
		else
			echo "Deleted specified certificate successfully"
		fi
 
        getSwichId "logical"
        VID=$?

        # Change the context to default.
        if [ $VID != -1 ];then
            # This means VF is enabled. 
            getSwichId "default"
            DEFAULT_VID=$?
            setcontext $DEFAULT_VID
        fi

		# Reset the config values
		configCert=`config get ssl.certfile 5`
		if [ "$2" == "$configCert" ]; then
		    resetSSLState
		fi

		# Check if the file is the CA root certificate
		caCertFile=`config get $ROOTCERTCONFIG 5`
		if [ "$2" == "$caCertFile" ]; then
			config set $ROOTCERTCONFIG 5 none
		fi
 
		
		config save $CERT_DIR
		config update

		# Change the VF back to current context.
		if [ $VID != -1 ];then 
			setcontext $VID
		fi
		
	elif [ "$1" = "$CSR_FILE" ]; then
		cat /dev/null > $2
		config save $CERT_DIR

	elif [ "$1" == "$FCAP_ALL_FILE" ]; then
 		getSwichId "logical"
		VID=$?
		if [ $VID != -1 ];then
			# This means VF is enabled.
			getSwichId "default"
			DEFAULT_VID=$?
			setcontext $DEFAULT_VID
		fi 
		# /usr/bin/yes | /fabos/cliexec/pkiremove --fcap	> /dev/null 2>&1
		# TR000327481 above 'yes' bin was running infinitely 
		# after pkiremove exits. So replaced with echo cmd.
		echo "y" | /fabos/cliexec/pkiremove --fcap	> /dev/null 2>&1
		cat /dev/null > $FCAP_DIR/$FCAP_CERT_CONF_FILE
		config save $FCAP_DIR/$FCAP_CERT_CONF_FILE
		updateFCAPConfigFile "ROOT_CA_CERTIFICATES:0"
 		cat /dev/null > $FCAP_DIR/$FCAP_TOUCH_FILE
		config save $FCAP_DIR/$FCAP_TOUCH_FILE
		syncUpFCAP
 		if [ $VID != -1 ];then 
			setcontext $VID
		fi

  		if [ $? != 0 ] ; then
			echo "Operation Failed."
			exit 1
		fi

	elif [ "$1" == "$FCAP_CA_CERT_FILE" ]; then
		updateFCAPConfigFile "ROOT_CA_CERTIFICATES:0"
		cat /dev/null > $FCAP_DIR/$FCAP_CACERT_FILE
 		config save $FCAP_DIR/$FCAP_CACERT_FILE
		syncUpFCAP

	elif [ "$1" == "$FCAP_SW_CERT_FILE" ]; then
		cat /dev/null > $FCAP_DIR/$FCAP_SWCERT_FILE
  		config save $FCAP_DIR/$FCAP_SWCERT_FILE
		cat /dev/null > $FCAP_DIR/$FCAP_TOUCH_FILE
		config save $FCAP_DIR/$FCAP_TOUCH_FILE
		updateFCAPConfigFile "SWITCH_CERT_NAME:None"
		config save $FCAP_DIR/$FCAP_CERT_CONF_FILE
		syncUpFCAP

	else
		#
		# Must be key file
		#
		cat /dev/null > $CERT_DIR/$2 > /dev/null
		config save $CERT_DIR

	fi

	return 0
}

#
# Ask the user if he really wants to delete a file.
# If "yes", then delete, else return.
# arguments:
# arg1: keySize
#
confirmGenerate() {
	/fabos/cliexec/pkicreate --fcap -keysize $1
	return $?
}

#
#
# A function to list the certificates or the CSRs
#
showFiles() {
	isCertExist=0;
	if [ $ldapCaCert -ne 1 ] && [ -s $PVT_KEY_FILE ] && [ $fcap -ne 1 ]; then
	    echo
	    echo "ssl private key: Exists"
	    echo
	fi

	echo "List of $1 files:"

	# first check if any files exist
	if [ $ldapCaCert -eq 1 ];then
	
		file=`$LS $LDAP_DIR/*$PEM_SUFFIX $LDAP_DIR/*$CER_SUFFIX \
		$LDAP_DIR/*$CRT_SUFFIX 2> /dev/null`
	elif [ $syslogCaCert -eq 1 ];then
		file=`$LS $SYSLOGCA_DIR/*$PEM_SUFFIX  2> /dev/null`
 	elif [ $fcap -eq 1 ]; then 
		/fabos/cliexec/pkishow --fcap
        else	
		file=`$LS $CERT_DIR/*$CRT_SUFFIX $CERT_DIR/*$CER_SUFFIX \
		$CERT_DIR/*$PEM_SUFFIX $CERT_DIR/*$PSK_SUFFIX 2> /dev/null`
	fi
	if [ ! -z "$file" ]; then
	    echo
	    for i in $file
	    do
		if [  -s "$i" ]; then
			isCertExist=1;
			echo `basename $i`
		fi
	    done
		if [ $isCertExist == 0 ]; then
	    	echo "No $1(s) found."
		fi
  	elif [ $fcap -ne 1 ]; then
	    echo "No $1(s) found."
	fi

}

#
# Print the usage of this utility
#
usage() {
	echo
	echo "Usage:"
	echo "seccertutil  genkey [-nowarn] [-keysize <1024 | 2048>]"
	echo
	echo "             delkey [-nowarn] [-all]"
	echo
	echo "             gencsr -hash <sha1 | sha256> [-country <2 letter country name>] [-state <state>] [-locality <locality>]"
	echo "                    [-org <organization>] [-orgunit <organization unit>] [-cn <common name>]"
	echo
	echo "             delcsr [-nowarn]"
	echo
	echo "             showcsr"
	echo
	echo "             generate [-fcapall | -commoncertall ] [-keysize <1024 | 2048>] [-nowarn]"
	echo
    echo "             delete [-ldapcacert [<certificate name>] | -syslogcacert [<certificate name>] | -fcapcacert | -fcapswcert | -fcapall |"
	echo "                     -commoncertall | <certificate name>] [-nowarn]"
	echo
    echo "             export [-ldapcacert [-certname <certificate name>] | -syslogcacert [-certname <certificate name>] | -fcapswcert | -fcapswcsr | -fcapcacert |"
	echo "                     -commonswcert | -commonswcsr | -commoncacert ]"
	echo "                    [-protocol  SCP] [-ipaddr <IP address>] [-remotedir <remote directory>]"
	echo "                    [-login <login name>] [-password <password>]"
	echo
    echo "             import [-ldapcacert | -syslogcacert | -fcapswcert | -fcapcacert | -config <cacert | swcert [-enable https]> |"
	echo "                     -commonswcert | -commoncacert ]"
	echo "                    [-protocol SCP] [-ipaddr <IP address>] [-remotedir <remote directory>]"
	echo "                    [-certname <certificate name>] [-login <login name>] [-password <password>]"
	echo
    echo "             show [-ldapcacert] |  [-syslogcacert] | [-fcapall] | [-fcapswcert] | [-commoncertall] | [<file name>]"
    echo
    echo "             help - shows the usage"
	echo
}

#
# Validates whether the imported certificate is self signed or not
#
validateSelfSigned() {
	if [ ! -z $userInput ] && [ $highSecurityModeFlag -eq 0 ]; then
		if [ $fcapSwCert -eq 1 ]; then
			output=`$OPENSSL_CMD_NO_FIPS verify $FCAP_DIR/$userInput 2> /dev/null | /bin/grep "error" | awk ' {print $1$2} '`
			if [ "$output" == "error18" ] ; then
				echo "Self signed certificate cannot be imported"
				rm -rf $FCAP_DIR/$userInput
				exit 1
			fi
		fi
		if [ $swCert -eq 1 ]; then

			 output=`$OPENSSL_CMD_NO_FIPS verify $CERT_DIR/$userInput 2> /dev/null | /bin/grep "error" | awk ' {print $1$2} '`
			if [ "$output" == "error18" ] ; then
				echo "Self signed certificate cannot be imported"
				rm -rf $CERT_DIR/$userInput
				exit 1
			fi
		fi	
	fi	
}

# check if FIPS mode is enabled or disabled.
fipsCheck() {
 	`$CONFIGSHOW_CMD | /bin/grep 'fips.mode' | /bin/grep -qE '1'`
	fips_mode=`echo $? ` 
	return $fips_mode
}

checkForFIPsCompl() {
	AuditSz=0
	AuditSha=""
	RET=0

	AuditSha=`$OPENSSL_CMD x509 -in $1 -text -noout 2> /dev/null| \
                        grep "Signature Algorithm:" 2> /dev/null`
	AuditSz=`$OPENSSL_CMD x509 -in $1 -text -noout 2> /dev/null| \
                        grep "Key:" 2> /dev/null`
	case "$AuditSha" in
		(*"sha1"*) AuditSha=sha1;;
		(*"sha224"*) AuditSha=sha224;;
		(*"sha256"*) AuditSha=sha256;;
		(*"sha384"*) AuditSha=sha384;;
		(*"sha512"*) AuditSha=sha512;;
		(*"md5"*) AuditSha=md5;;
	esac
	case "$AuditSz" in
		(*"512"*) AuditSz=512;;
		(*"768"*) AuditSz=768;;
		(*"1024"*) AuditSz=1024;;
		(*"2048"*) AuditSz=2048;;
		(*"3072"*) AuditSz=3072;;
		(*"4096"*) AuditSz=4096;;
		(*"8192"*) AuditSz=8192;;
	esac
	if [ ! -z "$fips_mode" ] && [ $fips_mode -eq 0 ]; then
		if [ $AuditSz != "2048" ] || [ $AuditSha != "sha256" ]; then
			echo -n "You are importing a Non-FIPS complaint certificate." \
				"Do you want to continue: (yes, y, no, n) [no] "
			read response
			if [ "$response" == "" ]; then
				response="no"
			fi
			resp=`echo $response | tr "[:lower:]" "[:upper:]"` 
			if [ "$resp" == "N" -o "$resp" == "NO" ]; then
				RET=1
			elif [ "$resp" == "Y" -o "$resp" == "YES" ]; then
				RET=0
			else
				echo "Invalid input." 
				RET=1
			fi

		fi
	fi
	return $RET
}

#
# Prompt the user for remote host IP, login name, password, etc.,
# Login to the host with name and password, then download or
# upload the specified file
#
promptHostInfo() {

	swbd=`sin | awk ' {print $2} ' | grep SWBD | sed 's@,@@'`
	`$CONFIGSHOW_CMD | /bin/grep 'fips.mode' | /bin/grep -qE '1'`
	fips_mode=`echo $? `
	`$CONFIGSHOW_CMD | /bin/grep 'cfgload.secure' | /bin/grep -qE '1'`
	secure_mode=`echo $? `

	if [ -z "$protocol" ]; then
	    echo -n "Select protocol ["$PROT_FTP" or "$PROT_SCP"]: "
	    read protocol
	fi
  	
	if [ "$protocol" == "$PROT_FTP" ] && [ ! -z "$secure_mode" ] && [ $secure_mode -eq 0 ]; then
		echo "Secure communication is enabled. FTP is disabled.Use SCP for file transfer..."
		exit 1
	fi

	if [ "$protocol" == "$PROT_FTP" ] && [ ! -z "$fips_mode" ] && [ $fips_mode -eq 0 ]; then
	    echo "Fips mode is active. Use SCP for file transfer..."
	    exit 1
	fi
	    
	if [ "$protocol" != "$PROT_FTP" ] && [ "$protocol" != "$PROT_SCP" ]; then
		echo Unknown protocol: "$protocol"
		exit 1
	fi

	if [ -z "$ipAddr" ]; then
		printf "Enter IP address: "
		read ipAddr
		if [ -z "$ipAddr" ]; then
			printf "IP address should not be empty\n"
			exit 1;
		fi
	fi

	if [ -z "$remoteDir" ]; then
		printf "Enter remote directory: "
		read remoteDir
		if [ -z "$remoteDir" ]; then
			printf "remote directory should not be empty\n"
			exit 1;
		fi
	fi

	if [ "$1" = "$CERT_IMPORT" ]; then
		if [ -z "$certFileName" ]; then
			if [ $fcapCaCert -eq 1 ] || [ $fcapSwCert -eq 1 ] || [ $caCert -eq 1 ] || [ $syslogCaCert -eq 1 ]; then 
				readInput "Enter certificate name (must have \".pem\" suffix): "
			else
  				readInput "Enter certificate name (must have \".crt\" or \".cer\"  \".pem\" or \".psk\" suffix): " 
			fi
 			certFileName=$userInput 
			echo "$certFileName" | grep '/' >/dev/null 2>&1
			if [ "$?" -eq 0 ]; then
				echo "Filename cannot be provided with path"
				exit 1
			fi
		fi
		certNameValidate $certFileName
		certFileOnly=1
	fi

	if [ -z "$userName" ]; then
		printf "Enter Login Name: "
		read userName
		if [ -z "$userName" ]; then
			printf "Login name should not be empty\n"
			exit 1;
		fi
	fi

	if [ -z "$password1" ]; then
		if [ "$protocol" == "$PROT_FTP" ]; then
			trap 2 3
			stty -echo
			printf "Enter Password: "
			read password1
			if [ -z "$password1" ]; then
				trap '' 2 3
				echo
				stty echo
				printf "password should not be empty\n"
				exit 1;
			fi
			trap '' 2 3
			echo
			stty echo
		fi
	fi

	if [ "$1" == "$CERT_IMPORT" ]; then

		if [ $ldapCaCert -eq 1 ];then
			if [ ! -e "$LDAP_DIR" ]; then 
				mkdir -p $LDAP_DIR
			fi
			cd $LDAP_DIR

		elif [ $syslogCaCert -eq 1 ];then
 			if [ ! -e "$SYSLOGCA_DIR" ]; then
 	    		mkdir -p $SYSLOGCA_DIR
 			fi
 			cd $SYSLOGCA_DIR
			if [ ! -z "$ipAddr" ]; then
				SYSLOGCA_CERT_FILE="$ipAddr.pem"
			fi

		elif [ $fcapCaCert -eq 1 ];then
			if [ ! -e "$FCAP_DIR" ]; then
				mkdir -p $FCAP_DIR
			fi
			cd $FCAP_DIR

		elif [ $fcapSwCert -eq 1 ]; then 
			if [ ! -e "$FCAP_DIR" ]; then
				mkdir -p $FCAP_DIR
			fi
			cd $FCAP_DIR
			CertConfExist=0
			# Checking if the cert.conf file exist. So we can store the name
			# of the imported file into that file.
			if [ -e "$FCAP_DIR/$FCAP_CERT_CONF_FILE" ]; then
				CertConfExist=1				
			fi

		else
			cd $CERT_DIR
			if [ -f $userInput ] && [ ! -s $userInput ]; then
				rm -rf $userInput
			fi

		fi

		if [ "$protocol" == "$PROT_FTP" ]; then
		    if [ $syslogCaCert -eq 1 ]; then
				fileext=`/bin/echo $certFileName | /bin/awk -F . '{ print $NF }'`
 	 			if [ $fileext != "pem" ]; then
 	 	    		echo "error: Only .pem formatted certificate files can be imported."
 	 	   			exit 3
		 	 	elif [ -f $SYSLOGCA_DIR/$SYSLOGCA_CERT_FILE ]; then
 	 			    echo "error: Syslog CA Certificate is already installed. Please delete existing certificate."
 	 	    		exit 2
 	 			fi
 			fi

			/bin/wget -T 60 -t 1 --user=$userName --password=$password1 \
				ftp://$ipAddr/$remoteDir/$userInput 2> /dev/null
			if [ $? != 0 ]; then
				/bin/wget -T 60 -t 1 --user=$userName --password=$password1 \
					ftp://\[$ipAddr\]/$remoteDir/$userInput 2> /dev/null
			fi
            if [ $syslogCaCert -eq 1 ]; then
                if [ -f $SYSLOGCA_DIR/$certFileName ]; then
                    /bin/mv $SYSLOGCA_DIR/$certFileName $SYSLOGCA_DIR/$SYSLOGCA_CERT_FILE
                fi
            fi
		else
			if [ $ldapCaCert -eq 1 ]; then
				/usr/bin/scp -q -oStrictHostKeyChecking=no \
					$userName@\[$ipAddr\]:$remoteDir/$userInput $LDAP_DIR/$userInput 2> /dev/null
                if [ $? != 0 ]; then
                    echo "error: Certificate import failed. Please check the certificate location and user credentials."
                    exit 1
                fi

            elif [ $syslogCaCert -eq 1 ]; then
                fileext=`echo $certFileName | awk -F . '{ print $NF }'`
                if [ $fileext != "pem" ]; then
                    echo "error: Only .pem formatted certificate files can be imported."
                    exit 3
                elif [ ! -f $SYSLOGCA_DIR/$SYSLOGCA_CERT_FILE ]; then
                    /usr/bin/scp -q -oStrictHostKeyChecking=no \
                        $userName@\[$ipAddr\]:$remoteDir/$certFileName $SYSLOGCA_DIR/$SYSLOGCA_CERT_FILE 2> /dev/null
                    if [ $? != 0 ]; then

                        echo "error: Certificate import failed. Please check the certificate location and user credentials."
                        exit 1
                    fi
                else
                    echo "error: Syslog CA Certificate is already installed. Please delete existing certificate."
                    exit 2
                fi

 			elif [ $fcapCaCert -eq 1 ] || [ $fcapSwCert -eq 1 ]; then
				/usr/bin/scp -q -oStrictHostKeyChecking=no \
					$userName@\[$ipAddr\]:$remoteDir/$userInput $FCAP_DIR/$userInput 2> /dev/null
			else
				/usr/bin/scp -q -oStrictHostKeyChecking=no \
					$userName@\[$ipAddr\]:$remoteDir/$userInput $CERT_DIR/$userInput 2> /dev/null
			fi
		fi

 		#if wrong password is supplied 3 times, then it returns 1 and gives errors. CHECK - kumar
		if [ $? != 0 ]; then
			echo "Failed to $1 certificate from remote host: $ipAddr"
			exit 1
		fi    
		cLen=`expr length $userInput`	
		let dotIndex="$cLen"-3
		fileSuffix=`expr substr $userInput $dotIndex $cLen`
		if [ $caCert -eq 1 ] && [ "$fileSuffix" == "$PEM_SUFFIX" ]; then
				$OPENSSL_CMD x509 -in $userInput -inform PEM -outform DER -out $TMP_DIR/$userInput.der > /dev/null 2>&1
					if [ $? != 0 ]; then
					echo " $userInput is an invalid CA certificate."
					rm $CERT_DIR/$userInput
					exit 1
					fi
			rm $TMP_DIR/$userInput.der
		fi
		if [ $ldapCaCert -eq 1 ]; then
			if [ "$fileSuffix" == "$CER_SUFFIX" ] || [ "$fileSuffix" == "$CRT_SUFFIX" ];then

				# User has imported certificate with .cer or .crt extension
				# Hence use Openssl command to convert the certificate to .pem
	
				$OPENSSL_CMD x509 -in $userInput -inform DER -outform PEM -out $LDAP_DIR/$TEMP_CACERT > /dev/null 2>&1
        	
				if [ $? != 0 ]; then
					echo "Failed to convert certificate to .pem"
					rm $LDAP_DIR/$userInput
					exit 1
				fi
			else
				#validate the file format
				$OPENSSL_CMD x509 -in $userInput -inform PEM -outform DER -out $LDAP_DIR/$userInput.der > /dev/null 2>&1
				if [ $? != 0 ]; then
					echo "Bad format certificate. Exiting.."
					rm $LDAP_DIR/$userInput
				exit 1
				fi
				if [ -f $LDAP_DIR/$userInput.der ]; then
					rm $LDAP_DIR/$userInput.der
				fi
				cat $LDAP_DIR/$userInput >  $LDAP_DIR/$TEMP_CACERT
			fi
			# Certificate compliance with FIPs mode
			checkForFIPsCompl $LDAP_DIR/$TEMP_CACERT
			if [ $? != 0 ]; then
				echo "Operation cancelled."
				rm $LDAP_DIR/$TEMP_CACERT
				if [ "$userInput" != "swLdapca.pem" ]; then
					rm $LDAP_DIR/$userInput
				fi
				exit 1
			fi
			cat $LDAP_DIR/$TEMP_CACERT >> $LDAP_DIR/$LDAP_CACERT_FILE
			rm $LDAP_DIR/$TEMP_CACERT
			# As the certificate is appended to the LDAP_CACERT_FILE
			# it is not required any more. The reason for deleting is 
			# it is confusing the user when the user deletes it.

			# Also we need the following check to make sure that if user enters certificate
			# name as swLdapca.pem, then it was getting deleted. 
			if [ "$userInput" != "swLdapca.pem" ]; then
 				rm $LDAP_DIR/$userInput
			fi
			config save $LDAP_DIR/$LDAP_CACERT_FILE

			echo "Success: $1ed LDAP CA certificate ["$userInput"]."

        elif [ $syslogCaCert -eq 1 ]; then
            # User has imported Syslog CA certificate with .pem extension
            hashval=`$OPENSSL_CMD x509 -noout -hash -in $SYSLOGCA_CERT_FILE`
            /bin/ln -sf  $SYSLOGCA_DIR/$SYSLOGCA_CERT_FILE $SYSLOGCA_DIR/$hashval.0
            echo "$SYSLOGCA_DIR/$SYSLOGCA_CERT_FILE $SYSLOGCA_DIR/$hashval.0" >> $SYSLOGCA_DIR/$SYSLOG_LINK_HASH
            /fabos/cliexec/config save $SYSLOGCA_DIR/$SYSLOGCA_CERT_FILE
            /fabos/cliexec/config save $SYSLOGCA_DIR/$SYSLOGCA_DIR/$SYSLOG_LINK_HASH
            echo "Success: $1ed Syslog CA certificate ["$certFileName"]."

 		elif [ $fcapCaCert == 1 ]; then
			# First checking if the root certificate file exists

			if [ ! -f "$FCAP_DIR/$FCAP_CACERT_FILE" ]; then
				cat /dev/null > $FCAP_DIR/$FCAP_CACERT_FILE
			fi

			countAndValidateCertificates $FCAP_DIR/$userInput 
			return_val_imported_file=$?
			if [ $return_val_imported_file -eq -1 ]; then
				rm -rf $FCAP_DIR/$userInput
				exit 1;
			fi

			existing_root_ca_certs_counter=0
			import_root_ca_certs_counter=0
			root_ca_cert_import=1
			total_certs=0

			# Reading Certificate Configuration File to check how many root CA certificates exist.
			readNumFCAPRootCaCerts
			existing_root_ca_certs_counter=$?

			# Counting number of root CA certificates in the imported file.
			countImportedRootCaCerts $FCAP_DIR/$userInput
			import_root_ca_certs_counter=$?

			total_certs=`expr $existing_root_ca_certs_counter + $import_root_ca_certs_counter`

			rm -rf $FCAP_DIR/$FCAP_TEMP_FILE
			if [ $total_certs -gt $MAX_ALLOWED_CACERTS ]; then
				if [ $fcapCaCert -eq 1 ]; then 
					echo "Maximum limit of FCAP Root CA certificates : $MAX_ALLOWED_CACERTS"
					echo "Number of existing Root CA certificates    : $existing_root_ca_certs_counter"
					echo "Importing exceeds the maximum limit of FCAP Root CA certificates."
					echo "Please reduce the number of certificates being imported and try again."
				elif [ $commonCaCert -eq 1 ]; then
 					echo "Maximum limit of Common Root CA certificates : $MAX_ALLOWED_CACERTS"
					echo "Number of existing Root CA certificates    : $existing_root_ca_certs_counter"
					echo "Importing exceeds the maximum limit of Common Root CA certificates."
					echo "Please reduce the number of certificates being imported and try again."
				fi
				rm $FCAP_DIR/$userInput        		    
				exit 1
			fi

			# Verifying each imported certificate to make sure its root CA certificate exist.
			i=1
			cat /dev/null > $FCAP_DIR/$FCAP_TEMP_FILE
			IFS_=${IFS}; IFS=$'\n'
			for LINE in `cat $FCAP_DIR/$userInput`;	do
				if [ "$LINE" == "$FCAP_CERT_HEADER" ] || [ $copy_cert -eq 1 ] ; then
					echo $LINE >> $FCAP_DIR/$FCAP_TEMP_FILE
					copy_cert=1
				fi

				if [ "$LINE" == "$FCAP_CERT_FOOTER" ] ; then
					copy_cert=2
				fi
				if [ $copy_cert -eq 2 ] ; then
					#First we verify if the Root CA is in the imported file.
					output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $FCAP_DIR/$userInput $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null`
					check=`echo "$output" | awk ' {print $2} '`
					if [ "$check" != "OK" ] ; then
						# If its not in imported file then we check if its in existing file.
 						output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $FCAP_DIR/$FCAP_CACERT_FILE $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null`
						check=`echo "$output" | awk ' {print $2} '`
						if [ "$check" != "OK" ] ; then
							echo "Error: One of the certificates being imported does not have its Root CA Certificate."
							rm $FCAP_DIR/$userInput
							rm -rf $FCAP_DIR/$FCAP_TEMP_FILE
							exit 1
						fi
					fi
					imported_ca_certs_mods[$i]=`$OPENSSL_CMD_NO_FIPS x509 -noout -modulus -in $FCAP_DIR/$FCAP_TEMP_FILE | $OPENSSL_CMD_NO_FIPS md5`
					i=$(($i + 1))
					copy_cert=0
					cat /dev/null > $FCAP_DIR/$FCAP_TEMP_FILE 
				fi
			done
			IFS=${IFS_} 

			# Checking certificate dups against other certs in the file imported
			if [ $import_root_ca_certs_counter -gt 1 ]; then
				for (( j = 1; j <= $import_root_ca_certs_counter-1; j++ )); do
					for (( k = $j+1; k <= $import_root_ca_certs_counter; k++ )); do
						if [ "${imported_ca_certs_mods[$j]}" = "${imported_ca_certs_mods[$k]}" ]; then
							echo "Error: Duplicate certificates present in the Root CA certificate being imported."
							rm $FCAP_DIR/$userInput
							rm -rf $FCAP_DIR/$FCAP_TEMP_FILE
							exit 1
						fi
					done 
				done
			fi

			# Checking dups against those already present
			cat /dev/null > $FCAP_DIR/$FCAP_TEMP_FILE
			i=1
			IFS_=${IFS}; IFS=$'\n'
			for LINE in `cat $FCAP_DIR/$FCAP_CACERT_FILE`; do
				echo $LINE >> $FCAP_DIR/$FCAP_TEMP_FILE
				if [ "$LINE" == "$FCAP_CERT_FOOTER" ] ; then
					existing_ca_certs_mods[$i]=`$OPENSSL_CMD_NO_FIPS x509 -noout -modulus -in $FCAP_DIR/$FCAP_TEMP_FILE | $OPENSSL_CMD_NO_FIPS md5`
					i=$(($i + 1))
					cat /dev/null > $FCAP_DIR/$FCAP_TEMP_FILE
				fi
			done

			for (( j = 1; j <= $import_root_ca_certs_counter; j++ )); do
				for (( k = 1; k <= $existing_root_ca_certs_counter; k++ )); do
					if [ "${imported_ca_certs_mods[$j]}" = "${existing_ca_certs_mods[$k]}" ]; then
						echo "Error: Root CA certificate(s) being imported already exists on the switch."
						rm $FCAP_DIR/$userInput
						rm -rf $FCAP_DIR/$FCAP_TEMP_FILE
						exit 1
					fi
				done 
			done
			IFS=${IFS_};
			# Certificate compliance with FIPs mode
			checkForFIPsCompl $FCAP_DIR/$userInput
			if [ $? != 0 ]; then
				echo "Operation cancelled."
				rm $FCAP_DIR/$userInput
				rm -rf $FCAP_DIR/$FCAP_TEMP_FILE
				exit 1
			fi
			# If reached here, then we can append new imported certificate to the existing list of certificates. 
			cat $FCAP_DIR/$userInput >> $FCAP_DIR/$FCAP_CACERT_FILE
			rm $FCAP_DIR/$userInput
			rm -rf $FCAP_DIR/$FCAP_TEMP_FILE
			updateFCAPConfigFile "ROOT_CA_CERTIFICATES:$total_certs"
 	 		getSwichId "logical"
			VID=$?

			if [ $VID != -1 ];then
				# This means VF is enabled.
				getSwichId "default"
				DEFAULT_VID=$?
				setcontext $DEFAULT_VID
			fi
		
			config save $FCAP_DIR/$FCAP_CERT_CONF_FILE
	  		config save $FCAP_DIR/$FCAP_CACERT_FILE
			
	 		if [ $VID != -1 ];then 
				setcontext $VID
			fi 

 			if [ $commonCaCert -eq 1 ]; then
				echo "success: $1ed Common ca certificate ["$userInput"]." 
			elif [ $fcapCaCert -eq 1 ]; then
				echo "success: $1ed fcap ca certificate ["$userInput"]."
			fi

 		elif [ $fcapSwCert == 1 ]; then

 			# First checking if the switch certificate file exists
			if [ ! -f "$FCAP_DIR/$FCAP_SWCERT_FILE" ]; then
				cat /dev/null > $FCAP_DIR/$FCAP_SWCERT_FILE
			fi
			
			# Checking the file size to make sure that new certificate can be appended to the file.
   			countAndValidateCertificates $FCAP_DIR/$userInput
			return_val_imported_file=$?
			if [ $return_val_imported_file -eq -1 ]; then
				rm -rf $FCAP_DIR/$userInput
				rm -rf $FCAP_DIR/$FCAP_TEMP_FILE
				exit 1;
			fi

			flag=1
			copy_cert=0
			counter=0
			response="no"
			output="NO"
			if [ $swbd == "SWBD117" ]; then
				validateSelfSigned
			fi	
			# Checking if root CA certificate exists for the imported sw cert.
 			output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $FCAP_DIR/$FCAP_CACERT_FILE $FCAP_DIR/$userInput 2> /dev/null`
			check=`echo "$output" | awk ' {print $2} '`
 		   	if [ "$check" != "OK" ]; then
				echo "File cannot be imported either because (a) the root CA certificate for the " \
					"importing switch certificate does not exist, or (b) the certificate has expired. " \
					"Please import CA certificate or check the validity before importing switch certificate."
				rm $FCAP_DIR/$userInput
				exit 1
			fi

			if [ $nowarn -eq 1 ]; then 
				flag=1
			else
				if [ -s $FCAP_DIR/$FCAP_SWCERT_FILE ]; then
					echo -n "Switch certificate already exists. Do you want to" \
						"override with new certificate: (yes, y, no, n) [no] "
					read response
					resp=`echo $response | tr "[:lower:]" "[:upper:]"` 
					if [ "$resp" == "N" -o "$resp" == "NO" ]; then
						flag=0
					elif [ "$resp" == "Y" -o "$resp" == "YES" ]; then
						flag=1
					else
						echo "Invalid input. Certificate file not imported."
						rm -rf $FCAP_DIR/$userInput
						exit 1
					fi
				fi
			fi
			# validation with pvt key and csr - needed for sw certs 
			certPvtKeyValidate $1

 			# Certificate compliance with FIPs mode
			checkForFIPsCompl $FCAP_DIR/$userInput
			if [ $? != 0 ]; then
				echo "Operation cancelled."
				rm $FCAP_DIR/$userInput
				rm -rf $FCAP_DIR/$FCAP_TEMP_FILE
				exit 1
			fi
			cat /dev/null > $FCAP_DIR/$FCAP_TEMP_FILE
			if [ $flag == 1 ]; then
 				cat /dev/null > $FCAP_DIR/$FCAP_SWCERT_FILE
 				IFS_=${IFS}; IFS=$'\n'
				for LINE in `cat $FCAP_DIR/$userInput`;	do
					if [ "$LINE" == "$FCAP_CERT_HEADER" ] || [ $copy_cert -ge 1 ] ; then
						echo $LINE >> $FCAP_DIR/$FCAP_TEMP_FILE
						copy_cert=`expr $copy_cert + 1`
					fi
				
					if [ "$LINE" == "$FCAP_CERT_FOOTER" ] ; then
						copy_cert=0
					fi
				done
				IFS=${IFS_} 
			elif [ $flag == 0 ] ; then
				rm -rf $FCAP_DIR/$userInput
				rm -rf $FCAP_DIR/$FCAP_TEMP_FILE
				echo "Certificate file not imported."
				exit 1
			fi

 			updateFCAPConfigFile "SWITCH_CERT_NAME:$userInput"
			cp $FCAP_DIR/$FCAP_TEMP_FILE $FCAP_DIR/$FCAP_SWCERT_FILE
			cp $FCAP_DIR/$userInput $FCAP_DIR/$FCAP_TOUCH_FILE
			rm -rf $FCAP_DIR/$userInput
			rm -rf $FCAP_DIR/$FCAP_TEMP_FILE
			
  	 		getSwichId "logical"
			VID=$?

			if [ $VID != -1 ];then
				# This means VF is enabled.
				getSwichId "default"
				DEFAULT_VID=$?
				setcontext $DEFAULT_VID
			fi
       			 
			config save $FCAP_DIR/$FCAP_SWCERT_FILE
			config save $FCAP_DIR/$FCAP_TOUCH_FILE
			config save $FCAP_DIR/$FCAP_CERT_CONF_FILE
 			
	 		if [ $VID != -1 ];then 
				setcontext $VID
			fi
				
 			if [ $commonSwCert -eq 1 ]; then
				echo "Success: $1ed Common switch certificate ["$userInput"]." 
			elif [ $fcapSwCert -eq 1 ]; then
				echo "Success: $1ed FCAP switch certificate ["$userInput"]."
			fi
		else
			if [ $swbd == "SWBD117" ]; then
				validateSelfSigned
			fi	
 			# Perform pvtkey based validation for '-config swcert' 
			if [ $swCert -eq 1 ]; then
				# validate the certificate by comparing with private key and csr of the switch 
				certPvtKeyValidate $1
			fi

 			# Certificate compliance wimh FIPs mode
			checkForFIPsCompl $CERT_DIR/$userInput
			if [ $? != 0 ]; then
				echo "Operation cancelled."
				rm $CERT_DIR/$userInput
				exit 1
			fi
			getSwichId "logical"
			VID=$?

			if [ $VID != -1 ];then
				# This means VF is enabled.
				getSwichId "default"
				DEFAULT_VID=$?
				setcontext $DEFAULT_VID
			fi
       			 
			config save $CERT_DIR 	
 	 		if [ $VID != -1 ];then 
				setcontext $VID
			fi  
			echo "Success: $1ed certificate ["$userInput"]."

		fi

		$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr"

	else    #This is where export starts.
		ROOT_CA_SUFFIX="fcapRootCA.pem"
		COMMONCERT_CA_SUFFIX="commonRootCA.pem"
		SW_CSR_SUFFIX="fcapSw.csr"
		COMMON_SW_CSR_SUFFIX="commonSw.csr"
 		fcapCAFileName=$switchIp$ROOT_CA_SUFFIX
		commonCAFileName=$switchIp$COMMONCERT_CA_SUFFIX
		fcapSWCsr=$switchIp$SW_CSR_SUFFIX
		commonSWCsr=$switchIp$COMMON_SW_CSR_SUFFIX
	
		if [ $ldapCaCert -eq 1 ];then
			if [ -z "$certFileName" ]; then
                readAndValidate_Export "LDAP" "Enter LDAP certificate name (must have \"$PEM_SUFFIX\" or  \"$CRT_SUFFIX\" or  \"$CER_SUFFIX\" suffix): "
				certFileName=$userInput
				echo "$certFileName" | grep '/' >/dev/null 2>&1
				if [ "$?" -eq 0 ]; then
					echo "Filename cannot be provided with path"
					exit 1
				fi
			else
				readAndValidate_Export "LDAP"
			fi
        elif [ $syslogCaCert -eq 1 ];then
            if [ -z "$certFileName" ]; then
                readAndValidate_Export "SYSLOG" "Enter SYSLOG CA certificate name (must have \"$PEM_SUFFIX\" suffix): "
                certFileName=$userInput
                echo "$certFileName" | grep '/' >/dev/null 2>&1
                if [ "$?" -eq 0 ]; then
                    echo "Filename cannot be provided with path"
                    exit 1
                fi
            else
                readAndValidate_Export "SYSLOG"
			fi
  		elif [ $fcapCaCert -eq 1 ] ; then
			if [ $commonCaCert -eq 1 ]; then
				cat $FCAP_DIR/$FCAP_CACERT_FILE > $FCAP_DIR/$commonCAFileName
				certFileName=$commonCAFileName
			else
				cat $FCAP_DIR/$FCAP_CACERT_FILE > $FCAP_DIR/$fcapCAFileName
		       	certFileName=$fcapCAFileName
			fi
		elif [ $fcapSwCert -eq 1 ];then 
 			if [ -f $FCAP_DIR/$FCAP_CERT_CONF_FILE ]; then
		       		 #Now we parse the file to look for switch certificate name.
				IFS_=${IFS}; IFS=$'\n'
				for LINE in `cat $FCAP_DIR/$FCAP_CERT_CONF_FILE`; do
				    validate_string=`echo "$LINE" | awk -F':' ' { print $1 } '`
	
				    if [ $validate_string == "SWITCH_CERT_NAME" ] ; then
					    certFileName=`echo "$LINE" | awk -F':' ' { print $2 } '`
				    fi		
				done
				IFS=${IFS_} 
			fi   
		      	cat $FCAP_DIR/$FCAP_TOUCH_FILE > $FCAP_DIR/$certFileName
		elif [ $fcapSwCsr -eq 1 ];then 
				if [ $commonSwCsr -eq 1 ]; then
        			cat $FCAP_DIR/$FCAP_SWCSR_FILE > $FCAP_DIR/$commonSWCsr
	       			certFileName=$commonSWCsr 
				else
	       			cat $FCAP_DIR/$FCAP_SWCSR_FILE > $FCAP_DIR/$fcapSWCsr
	       			certFileName=$fcapSWCsr
				fi
        	fi

		if [ ! -f "$FCAP_DIR/$exportFile" ]; then
			cat /dev/null > $FCAP_DIR/$exportFile
		fi

		flag=0

		if [ "$protocol" == "$PROT_FTP" ]; then
			if [ $ldapCaCert -eq 1 ];then
				/bin/ncftpput -t 60 -u $userName -p $password1 $ipAddr \
					$remoteDir $LDAP_DIR/$certFileName 2> $FCAP_DIR/$exportFile
				flag=$?

            elif [ $syslogCaCert -eq 1 ];then
                /bin/ncftpput -t 60 -u $userName -p $password1 $ipAddr \
                    $remoteDir $SYSLOGCA_DIR/$certFileName 2> $FCAP_DIR/$exportFile
                flag=$?

 			elif [ $fcapCaCert -eq 1 ] || [ $fcapSwCert -eq 1 ] || [ $fcapSwCsr -eq 1 ];then
				/bin/ncftpput -t 60 -u $userName -p $password1 $ipAddr \
					$remoteDir $FCAP_DIR/$certFileName 2> $FCAP_DIR/$exportFile
				flag=$?
				rm -rf $FCAP_DIR/$certFileName
			else
				if [ ! -s "$CERT_DIR/$switchIp$CSR_SUFFIX" ]; then
			        echo "CSR does not exist."
		    	    exit 1
			    fi
				/bin/ncftpput -t 60 -u $userName -p $password1 $ipAddr \
					$remoteDir $CERT_DIR/$switchIp$CSR_SUFFIX 2> $FCAP_DIR/$exportFile
				flag=$?
			fi
		else
			if [ $ldapCaCert -eq 1 ]; then
				/usr/bin/scp -q -oStrictHostKeyChecking=no $LDAP_DIR/$certFileName \
					$userName@\[$ipAddr\]:$remoteDir 2> $FCAP_DIR/$exportFile
				flag=$?
            elif [ $syslogCaCert -eq 1 ]; then
                /usr/bin/scp -q -oStrictHostKeyChecking=no $SYSLOGCA_DIR/$certFileName \
                    $userName@\[$ipAddr\]:$remoteDir 2> $FCAP_DIR/$exportFile
                flag=$?
			elif [ $fcapCaCert -eq 1 ] || [ $fcapSwCert -eq 1 ] || [ $fcapSwCsr -eq 1 ]; then
			        /usr/bin/scp -q -oStrictHostKeyChecking=no \
				$FCAP_DIR/$certFileName $userName@\[$ipAddr\]:$remoteDir 2> $FCAP_DIR/$exportFile
				flag=$?
				rm -rf $FCAP_DIR/$certFileName
			else
				if [ ! -s "$CERT_DIR/$switchIp$CSR_SUFFIX" ]; then
			        echo "CSR does not exist."
		    	    exit 1
			    fi
				/usr/bin/scp -q -oStrictHostKeyChecking=no $CERT_DIR/$switchIp$CSR_SUFFIX \
					$userName@\[$ipAddr\]:$remoteDir 2> $FCAP_DIR/$exportFile
				flag=$?
			fi
		fi

   		# If wrong password is supplied three times, still success message is printed. This is because even if
		# wrong password is provided, scp returns 0. Thus we check for lost connection message.
		output=`cat $FCAP_DIR/$exportFile`
		if [ "$protocol" == "$PROT_FTP" ]; then
			if [ -f "$FCAP_DIR/$exportFile" ]; then
				if [ "$output" != "" ] && [ "$flag" -eq 0 ]; then
					IFS_=${IFS}; IFS=$'\n'
					for LINE in `cat $FCAP_DIR/$exportFile`; do
						check=`echo "$LINE" | awk 'END { print }'`
					done
					IFS=${IFS_}
					if [ "$check" == "$PROT_FTP_PORT_MODE" ]
					then
						flag=0
					else
						flag=1
					fi
				fi
			fi
		else
			if [ "$output" == "lost connection" ]; then
				flag=1
			fi
		fi

		if [ $flag == 1 ]; then
			if [ $ldapCaCert -eq 1 ]; then
				echo "Failed to $1 LDAP certificate to remote host: $ipAddr"
            elif [ $syslogCaCert -eq 1 ]; then
                echo "Failed to $1 SYSLOG CA certificate to remote host: $ipAddr"
			elif [ $fcapCaCert -eq 1 ]; then
				echo "Failed to $1 FCAP CA certificate(s) to remote host: $ipAddr"
			elif [ $fcapSwCert -eq 1 ]; then
				echo "Failed to $1 FCAP switch certificate to remote host: $ipAddr"
			elif [ $fcapSwCsr -eq 1 ]; then
				echo "Failed to $1 FCAP CSR to remote host: $ipAddr"
			else
				echo "Failed to $1 CSR to remote host: $ipAddr"
			fi
		elif [ $flag == 0 ]; then
			if [ $ldapCaCert -eq 1 ]; then
				$AUDIT_NOTIFY "$CERT_EXPORT" "$certFileName" "$ipAddr"
				echo "Success: $1ed LDAP certificate"
            elif [ $syslogCaCert -eq 1 ]; then
                $AUDIT_NOTIFY "$CERT_EXPORT" "$certFileName" "$ipAddr"
                echo "Success: $1ed SYSLOG CA certificate"
 			elif [ $fcapCaCert -eq 1 ]; then
				rm -rf $FCAP_DIR/$fcapCAFileName
				$AUDIT_NOTIFY "$CERT_EXPORT" "$certFileName" "$ipAddr"
				if [ $commonCaCert -eq 1 ]; then
	 				echo "Success: $1ed Common CA certificate [$certFileName]." 
				else
					echo "Success: $1ed FCAP CA certificate [$certFileName]."
				fi
			elif [ $fcapSwCert -eq 1 ]; then
				$AUDIT_NOTIFY "$CERT_EXPORT" "$certFileName" "$ipAddr"
 				if [ $commonSwCert -eq 1 ]; then
	 				echo "Success: $1ed Common switch certificate [$certFileName]." 
				else 
 		   			echo "Success: $1ed FCAP switch cetificate [$certFileName]."
				fi
			elif [ $fcapSwCsr -eq 1 ]; then
				rm -rf $FCAP_DIR/$fcapSWCsr
				$AUDIT_NOTIFY "$CERT_EXPORT" "$certFileName" "$ipAddr"
 				if [ $commonSwCsr -eq 1 ]; then
	 				echo "Success: $1ed Common CSR [$certFileName]." 
				else 
 		   			echo "Success: $1ed FCAP CSR [$certFileName]."
				fi
			else
				$AUDIT_NOTIFY "$CERT_EXPORT" "$switchIp$CSR_SUFFIX" "$ipAddr"
				echo "Success: $1ed CSR [$switchIp$CSR_SUFFIX]."
			fi
		fi
		
		if [ -f "$FCAP_DIR/$exportFile" ]; then
	       		rm -rf $FCAP_DIR/$exportFile
		fi
	fi

}

addCMMSentCerts() {
	certFileName=$cmmCertFile
	# hack for certificate validation later
	userInput=$cmmCertFile
	certNameValidate $certFileName CERT_IMPORT_CMM

	if [ "$1" == "$CERT_IMPORT" ]; then

		if [ $ldapCaCert -eq 1 ];then
			if [ ! -e "$LDAP_DIR" ]; then 
				mkdir -p $LDAP_DIR
			fi
			cd $LDAP_DIR
		else
			cd $CERT_DIR
			if [ -f $cmmCertFile ] && [ ! -s $cmmCertFile ]; then
				rm -rf $cmmCertFile
			fi

		fi

		cLen=`expr length $cmmCertFile`	
		let dotIndex="$cLen"-3
		fileSuffix=`expr substr $cmmCertFile $dotIndex $cLen`
		if [ $ldapCaCert -eq 1 ]; then
			if [ "$fileSuffix" == "$CER_SUFFIX" ] || [ "$fileSuffix" == "$CRT_SUFFIX" ];then

				# User has imported certificate with .cer or .crt extension
				# Hence use Openssl command to convert the certificate to .pem
	
				$OPENSSL_CMD x509 -in $LDAP_DIR/$cmmCertFile -inform DER -outform PEM -out $LDAP_DIR/$TEMP_CACERT > /dev/null 2>&1
        	
				if [ $? != 0 ]; then
					echo "Failed to convert certificate to .pem"
					rm $LDAP_DIR/$cmmCertFile
					exit 1
				fi
			else
				#validate the file format
				$OPENSSL_CMD x509 -in $LDAP_DIR/$cmmCertFile -inform PEM -outform DER -out $LDAP_DIR/$cmmCertFile.der > /dev/null 2>&1
				if [ $? != 0 ]; then
					echo "Bad format certificate. Exiting.."
					rm $LDAP_DIR/$cmmCertFile
					exit 1
				fi
				if [ -f $LDAP_DIR/$cmmCertFile.der ]; then
					rm $LDAP_DIR/$cmmCertFile.der
				fi
				cat $LDAP_DIR/$cmmCertFile>  $LDAP_DIR/$TEMP_CACERT
			fi
			cat $LDAP_DIR/$TEMP_CACERT >> $LDAP_DIR/$LDAP_CACERT_FILE
			rm $LDAP_DIR/$TEMP_CACERT
			# As the certificate is appended to the LDAP_CACERT_FILE
			# it is not required any more. The reason for deleting is 
			# it is confusing the user when the user deletes it.

 			rm $LDAP_DIR/$cmmCertFile
			config save $LDAP_DIR/$LDAP_CACERT_FILE

			echo "Success: $1ed LDAP CA certificate ["$cmmCertFile"]."

		else
 			# Validate the switch certificate (-config swcert option).
			if [ $swCert -eq 1 ]; then
				# validate the certificate by comparing private key of the switch and that in the certificate
				certPvtKeyValidate $1
			fi

			getSwichId "logical"
			VID=$?

			if [ $VID != -1 ];then
				# This means VF is enabled.
				getSwichId "default"
				DEFAULT_VID=$?
				setcontext $DEFAULT_VID
			fi
       			 
			config save $CERT_DIR 	
 	 		if [ $VID != -1 ];then 
				setcontext $VID
			fi  
			echo "Success: $1ed certificate ["$cmmCertFile"]."

		fi
	fi
}

#
# Reset all parameters for SSL and notify applications
#
resetSSLState() {
	/fabos/cliexec/config set $ROOTCERTCONFIG 5 none
	/fabos/cliexec/config set $CERTCONFIG 5 none
	# set http ssl state only if it is already enabled
	isHttpsEnabled=`/fabos/cliexec/config get $HTTPCONFIG 1`
	if [ "$isHttpsEnabled" == 1 ]; then
		# reset secure protocols, overwrite previous value
		/fabos/cliexec/config set $HTTPCONFIG 1 0
		# notify secure apps
		$WEBDHANDLER $HTTPCONFIG:0
	fi
	/fabos/cliexec/config update
}

#
# Prompt the user for all the required fields for generating a CSR
#
promptCSRInfo() {
		version3Certs=0
# First write the header to the file
		echo "#Generated file. Do not edit" > $CSR_GEN_INFO
		echo "prompt=no" >> $CSR_GEN_INFO
		echo "" >> $CSR_GEN_INFO
		echo "distinguished_name = req_distinguished_name" >> $CSR_GEN_INFO
		echo "attributes = req_attributes" >> $CSR_GEN_INFO
		echo "req_extensions = v3_req" >> $CSR_GEN_INFO
		echo "" >> $CSR_GEN_INFO

		echo "[ req_distinguished_name ]" >> $CSR_GEN_INFO

# Now ask for user input
		if [ -z "$country" ]; then 
			readInput "Country Name (2 letter code, eg, US): "
			country=$userInput
		fi
		country=`echo $country | tr "[:lower:]" "[:upper:]"`
		echo "countryName=$country" >> $CSR_GEN_INFO

		# validate country code
		cLen=`expr length $country`
		if  [ "$cLen" != 2 ]; then
			echo "Invalid length: Country code can be only" \
				"two characters [A-Z]"
			exit 1
		fi

		numChars=`expr match "$country" '[A-Z]*'`
		if [ $numChars != 2 ]; then
			echo "Invalid characters: Country code can be only" \
				"two characters [A-Z] $country"
			exit 1
		fi

		if [ -z "$state" ]; then 
			readInput "State or Province Name (full name, eg, California): "
			state=$userInput
		fi
		echo "stateOrProvinceName=$state" >> $CSR_GEN_INFO

		if [ -z "$locality" ]; then
			readInput "Locality Name (eg, city name): "
			locality=$userInput
		fi
		echo "localityName=$locality" >> $CSR_GEN_INFO

		if [ -z "$company" ]; then
			readInput "Organization Name (eg, company name): "
			company=$userInput
		fi
		echo "organizationName=$company" >> $CSR_GEN_INFO

		if [ -z "$unit" ]; then
			readInput "Organizational Unit Name (eg, department name): "
			unit=$userInput
		fi
		echo "organizationalUnitName=$unit" >> $CSR_GEN_INFO

		if [ -z "$cn" ]; then
			readInput "Common Name (Fully qualified Domain Name, or IP address): "
			cn=$userInput
		fi
		echo "commonName=$cn" >> $CSR_GEN_INFO

		if [ ! -z "$host" ] && [ ! -z "$domain" ] && [ ! -z "$switchIP" ]; then
			if [[ "$cn" == *"$host"* ]] && [[ "$cn" == *"$domain"* ]]; then
				version3Certs=1
			else
				echo "Host name or domain name does not match with common name."
				exit 1
			fi
		elif [ -z "$host" ] && [ -z "$domain" ] && [ -z "$switchIP" ]; then
			version3Certs=0
		else
			if [ -z "$host" ]; then
				echo "Please provide a host name."
			elif [ -z "$domain" ]; then
				echo "Please provide a domain name."
			elif [ -z "$switchIP" ]; then
				echo "Please provide the switch IP Address."
			fi
			exit 1
		fi

		echo "" >> $CSR_GEN_INFO
		echo "[ req_attributes ]" >> $CSR_GEN_INFO
#		echo "unstructuredName=$switchIp" >> $CSR_GEN_INFO
		echo "serialNumber=`wwn`" >> $CSR_GEN_INFO

		echo "" >> $CSR_GEN_INFO
		echo "[ v3_req ]" >> $CSR_GEN_INFO
		if [ $switchIPv6 != 0 ]; then
			echo "subjectAltName=DNS:$cn, IP:$switchIPv6" >> $CSR_GEN_INFO
		else
			if [ $version3Certs -eq 1 ]; then
				echo "keyUsage=digitalSignature, keyEncipherment" >> $CSR_GEN_INFO
				echo "extendedKeyUsage=serverAuth, clientAuth" >> $CSR_GEN_INFO
			fi
			echo "subjectAltName=DNS:$cn, IP:$switchIp" >> $CSR_GEN_INFO
		fi
}

#
# Set the OPENSSL_CMD if fips selftests is set 
setSelfTestsMode()
{
	STESTS_SET=3
	export PATH="$PATH:/fabos/abin"
	FIPSCFGFILE="/etc/fabos/fips_selftests.conf"

	if [ -r $FIPSCFGFILE ]
	then
   		read steststatus <$FIPSCFGFILE
   		rc=$steststatus
	else
    	return
	fi

	if [ $rc -eq $STESTS_SET ]
	then
		OPENSSL_CMD=/usr/bin/fipsopenssl
	fi
}

#
# Set the OPENSSL_CMD if fips.mode is set 
setFipsMode()
{
	# "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
    	retVal=`/fabos/cliexec/config get fips.mode 2`
    	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
    	if [ $retVal -eq 1 ]; then
		OPENSSL_CMD=/usr/bin/fipsopenssl
	fi
}

caCertComplTest() {
	i=1
	ret=0

	while read line
	do
		echo "$line" >> tmp_fips_$i
		echo $line | grep END > /dev/null 2>&1
		if [ $? = 0 ]; then
			i=`expr $i + 1`
		fi
	done < $1

	j=1
	while [ "$j" -lt "$i" ]
	do
		$OPENSSL_CMD x509 -in tmp_fips_$j -text -noout | \
			grep "Key" | grep 2048 > /dev/null 2>&1
		if [ $? != 0 ]; then
			echo "Key size of $2 is not 2048 bits"
			ret=1

		fi
		$OPENSSL_CMD x509 -in tmp_fips_$j -text -noout | \
			grep "Signature Algorithm" | grep sha256 > /dev/null 2>&1
		if [ $? != 0 ]; then
			echo "Signature Algorithm used in $2 is not Sha256"
			ret=1
		fi
		j=`expr $j + 1`
	done
	j=1
	while [ "$j" -lt "$i" ]
	do
		$RM -rf tmp_fips_$j > /dev/null
		j=`expr $j + 1`
	done
	return $ret
} 
 
fqdn_set() {
	alias="*"
	DEFAULT_VID=-1
		getSwichId "logical"
		CURRENT_VID=$?
		if [ $CURRENT_VID != -1 ];then
			# This means VF is enabled.
			getSwichId "default"
			DEFAULT_VID=$?
			if [ $DEFAULT_VID != $CURRENT_VID ]; then
				setcontext $DEFAULT_VID
			fi
		fi
		config set $HTTPFQDN 5 "$alias"
		config update
		$WEBDHANDLER $HTTPFQDN:"$alias"
		if [ $DEFAULT_VID != $CURRENT_VID ]; then
			setcontext $CURRENT_VID	
		fi
}

# Everything triggers of the switch ID and IP.

ipAddrShowCmd="/fabos/cliexec/ipaddrshow"

switchIp=`$ipAddrShowCmd |  sed -n '/CHASSIS\|SWITCH/{n;p;}' | sed -n -e 's/Ethernet IP Address: //p'`

if [ "$switchIp" == "none" ] ; then
	# get the static IPv6 address 
	chassisName="CHASSIS"
	ipAddrCmd=`$ipAddrShowCmd`
	switchType=`echo ${ipAddrCmd:0:8}`

	if [ $switchType == $chassisName ] ; then
		ipv6addr=`$ipAddrShowCmd | sed -n -e 's/chassis\(.*\)static //p'`
	else
		ipv6addr=`$ipAddrShowCmd | sed -n -e 's/\(.*\)static //p'`
	fi
	switchIp=`echo $ipv6addr | sed 's/\(.*\)\(\/.*\)/\1/'`
	if [ "$switchIp" == "" ] ; then
		# get the stateless IPv6 address 
		if [ $switchType == $chassisName ] ; then
    		ipv6addr=`$ipAddrShowCmd | sed -n -e 's/chassis\(.*\)stateless //p'`
		else
			ipv6addr=`$ipAddrShowCmd | sed -n -e 's/\(.*\)stateless //p'`
		fi
		# remove the prefix part from the ip addres
    	switchIp=`echo $ipv6addr | sed 's/\(.*\)\(\/.*\)/\1/'`
		if [ "$switchIp" == "" ] ; then
				echo "Configure a Valid IPv4 or IPv6 address"
				exit 1
		fi
	fi
	switchIPv6=$switchIp
	switchIp=$(echo $switchIp | sed 's/\:/./g')
fi

#echo "##### The switch IP is: $switchIp"

##################################################################
#
# the main execution. A case statment of the commands.
#
##################################################################

# check for Access Gateway

#/fabos/libexec/ag_check `/bin/basename $0`
#ret=`echo $?`

# Return value of 2 indicates this CLI is not allowed to execute in AG mode.
#if [ $ret -ne 1 ]; then
#	exit 127
#fi

#if [ $# -lt 1 ]
#then
#	usage
#	exit 1
#fi

# check for RBAC permission.
rbac_check_done=0

if [ $# -ge 1 ]; then
        if [ $1 = "showall" ]; then
		/fabos/libexec/rbac_check -opt `/bin/basename $0` "show"
		rbac_check_done=1
	fi
fi

if [ $rbac_check_done -eq 0 ]; then
/fabos/libexec/rbac_check -opt `/bin/basename $0` $1
fi

ret=`echo $?`
# Return value of 2 indicates wrong options were passed, hence usage is shown.
if [ $ret -ne 0 -a $ret -ne 2 ]; then
	exit 127
fi

# Set the openssl binary to be used
setFipsMode

# First convert option to all lower case
cmd_option=`echo $1 | tr "[:upper:]" "[:lower:]"`

case "$cmd_option" in

# Generate a key (public private) key pair
"$CERT_GEN_KEY" )
	declare -a cmdargs
	count=0
	for arg in "$@"
	do
		cmdargs[$count]=$arg
		count=`expr $count + 1`
	done
	cmdargs[$count]="NULL"
	count=1
	response="no"
	key_size=0
	# enforce encryptions checks before truncation
	delall=0;

	while [ $INFINITE_LOOP ]
	do
		case ${cmdargs[count]} in
		"-nowarn" )
			response="yes"
		;;
	    	"-keysize" )
	    		count=`expr $count + 1`
			key_size=${cmdargs[count]}

			# "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
			retVal=`/fabos/cliexec/config get fips.mode 2`
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
	    		if [ $retVal -eq 1 ]; then
				if [ $key_size -lt 2048 ]; then
					echo "Key size less than 2048 is not allowed in FIPS Mode."
					exit 1
				fi
			fi
			;;
	    	"NULL" )
			break
			;;
	    	* )
			usage
			exit 1
			;;
	    	esac
	    	count=`expr $count + 1`
	done

	if [ $response == "no" ]; then
		echo "Generating a new key pair will automatically do the following:"
		echo "1. Delete all existing CSRs."
		echo "2. Delete all existing certificates."
		echo "3. Reset the certificate filename to none."
		echo "4. Disable secure protocols."
		echo

		echo -n "Continue (yes, y, no, n): [no] "
		read response

		if [ "$response" == "" ]; then
			response=no
		fi
	fi
	resp=`echo $response | tr "[:lower:]" "[:upper:]"`

	if [ "$resp" == "N" -o "$resp" == "NO" ]; then
		echo "Operation cancelled."
		exit 0
	fi

	if [ "$resp" != "Y" ] && [ "$resp" != "YES" ]; then
		echo "Invalid input. Exiting"
		exit 1
	fi

	#
	# Prompt for key type and size
	#
#	echo -n "Select key type [ rsa or dsa ]: "
#	read key_type

#	RK: FIX THIS  FIXT THIS   FIX THIS
#	Need to remove this hardwired rsa_key

	key_type="$RSA_KEY"

#	if [ "$key_type" != "$RSA_KEY" ] && [ "$key_type" != "$DSA_KEY" ]
#	then
#		echo Unknown key type: "$key_type"
#		exit 1
#	fi

	if [ "$key_size" == 0 ]; then
		echo -n "Select key size [1024 or 2048]: "
		read key_size
	fi	

    # "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
    retVal=`/fabos/cliexec/config get fips.mode 2`
    FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
    if [ $retVal -eq 1 ]; then
        if [ $key_size -lt 2048 ]; then
            echo "Key size less than 2048 is not allowed in FIPS Mode."
            exit 1
        fi
    fi

	if [ "$key_size" != 1024 ] && [ "$key_size" != 2048 ]
	then
		echo Unsupported key size: "$key_size"
		exit 1
	fi

	# Defect: 618564
	# User input is prompted and validated before truncating the certificate related files
	# to avoid rolling reboot caused by Process Init (Weblinker)

	# Defect: 250961 
	# HA limitation, if we give the folder name rather than file name
	# , and if we delete the file name in active it doesn't delete the 
	# files in the standby. it is a known limitation. Fix is to 
	# truncate the file to zero size.
	file=`$LS $CERT_DIR/*$CRT_SUFFIX $CERT_DIR/*$CER_SUFFIX \
		$CERT_DIR/*$PEM_SUFFIX $CERT_DIR/*$PSK_SUFFIX \
		$CERT_DIR/*$CSR_SUFFIX 2> /dev/null`
	if [ ! -z "$file" ]; then
	    for i in $file
	    do
		if [ -s "$i" ]; then
			check_for_removal $i $delall 2> /dev/null
			if [ $? -eq 0 ]; then
				cat /dev/null > $i
			fi
		fi
	    done
	fi

	if [ -e "$PVT_KEY_FILE" ]; then
		cat /dev/null > "$PVT_KEY_FILE"
	fi
	/fabos/cliexec/config save $CERT_DIR

	echo "Generating new $key_type public/private key pair"

	if [ "$key_type" == "$RSA_KEY" ]; then
		$OPENSSL_CMD genrsa -out "$PVT_KEY_FILE" $key_size 2> /dev/null
	else
		$OPENSSL_CMD dsaparam -genkey -out "$PVT_KEY_FILE" \
			-rand /usr/bin/openssl:/usr/bin/ssh \ 
			$DSA_PARAM_FILE 2> /dev/null
	fi
		/bin/chmod 400 $PVT_KEY_FILE	

	if [ $? -eq 0 ]; then
		getSwichId "logical"
		VID=$?

		if [ $VID != -1 ];then
			# This means VF is enabled.
			getSwichId "default"
			DEFAULT_VID=$?
			setcontext $DEFAULT_VID
		fi

		# reset config certificate name, disable secure protocols and
		# send notification 
		resetSSLState

		/fabos/cliexec/config save $CERT_DIR

		if [ $VID != -1 ];then
			setcontext $VID
		fi
		
		$AUDIT_NOTIFY "$CERT_GEN_KEY" "$PVT_KEY_FILE" "$key_type" "$key_size"
		echo "Done."
	else
		echo "Failed key generation."
	fi
;;

 "$CERT_DEL_KEY" )
 
	response="no"
	count=0;
	# unless "-all" option is specified, prevent truncation of encryption certs
	delall=0;

	if [[ -z $2 || ( -n $2 && $2 == "$DELKEYALL_OPT") ]]; then
		# delkey -all || delkey
		echo
		echo "Deleting the key pair will automatically do the following:"
		echo "1. Delete all existing CSRs."
		echo "2. Delete all existing certificates."
		echo "3. Reset the certificate filename to none."
		echo "4. Disable secure protocols."
		echo
 
		echo -n "Continue (yes, y, no, n): [no] "
		read response
	fi

	declare -a cmdargs

	for arg in "$@"
	do
		cmdargs[$count]=$arg
		count=`expr $count + 1`
	done
	cmdargs[$count]="NULL"
	count=1

	while [ $INFINITE_LOOP ]
	do
	    case ${cmdargs[count]} in
			"$NOWARN_OPT" )
			response="yes"
			;;

			"$DELKEYALL_OPT" )
			delall=1
			;;

	    	"NULL" )
			break
			;;

    		* )
			usage
			exit 1
			;;

	    esac
	    count=`expr $count + 1`
	done

	resp=`echo $response | tr "[:lower:]" "[:upper:]"`
 
	if [ "$resp" == "N" -o "$resp" == "NO" ]; then
	        echo "Operation cancelled."
                 exit 0
	fi
 
	if [ "$resp" != "Y" ] && [ "$resp" != "YES" ]; then
	        echo "Invalid input. Exiting"
	        exit 1
	fi
	# Defect: 250961 
	# HA limitation, if we give the folder name rather than file name
	# , if we delete the file name in active it doesn't delete the 
	# files in the standby. it is a known limitation. Fix is to 
	# truncate the file to zero size.

	cleanUpHTTPS
	/fabos/cliexec/config set $ROOTCERTCONFIG 5 none
	/fabos/cliexec/config set $CERTCONFIG 5 none

	/fabos/cliexec/config save $PVT_KEY_FILE
	/fabos/cliexec/config save $CERT_DIR	
 ;;

# Generate a CSR
"$CERT_GEN_CSR" )

	# verify input arguments before processing
	if [ $# -gt 21 ]; then
	    usage
	    exit 1
	fi

	#
	# Check if the public/private key pair exist
	#
	if [ ! -s "$PVT_KEY_FILE" ]; then
		echo "public/private keys does not exist. Use genkey option to generate them."
		exit 1
	fi

	#
	# Either Ipv4 or Ipv6 file can exist 
	#
    csr_count=`ls $CERT_DIR/. | grep $CSR_SUFFIX | wc -l`
	if [ $csr_count -ge 1 ]; then
        for csr_file in `ls -1 $CERT_DIR/*$CSR_SUFFIX`; do
	    	if [ -s $csr_file ]; then 
				echo "CSR file already exists. Use delcsr option to delete it."
				exit 1
			fi
		done
	fi

	declare -a cmdargs
	count=0
	for arg in "$@"
	do
		cmdargs[$count]=$arg
		count=`expr $count + 1`
	done
	cmdargs[$count]="NULL"
	count=1
	while [ $INFINITE_LOOP ]
	do
	    case ${cmdargs[count]} in
            "-hash" )
            count=`expr $count + 1`
            hash=${cmdargs[count]}
            ;;

	    	"-country" )
			count=`expr $count + 1`
			country=${cmdargs[count]}
			country=`echo $country | tr "[:upper:]" "[:lower:]"`
			;;

	    	"-state" )
			count=`expr $count + 1`
			state=${cmdargs[count]}
			;;

	    	"-locality" )
			count=`expr $count + 1`
			locality=${cmdargs[count]}
			;;

	    	"-org" )
			count=`expr $count + 1`
			company=${cmdargs[count]}
			;;

	    	"-orgunit" )
			count=`expr $count + 1`
			unit=${cmdargs[count]}
			;;

	    	"-cn" )
			count=`expr $count + 1`
			cn=${cmdargs[count]}
			;;

			"-host" )
 			count=`expr $count + 1`
			host=${cmdargs[count]}
			;; 

			"-domain" )
  			count=`expr $count + 1`
			domain=${cmdargs[count]}
			;;

			"-switchip" )
			count=`expr $count + 1`
			switchIP=${cmdargs[count]}
			;;

	    	"NULL" )
			break
			;;

	    	* )
			echo "print ${cmdargs[count]}"
			usage
			exit 1
			;;
	    esac
	   	count=`expr $count + 1`
	done

    if [ -z "$hash" ]; then
		echo -n "Input hash type (sha1 or sha256): "
		read hash
    fi

	if [ "$hash" != "sha1" ] && [ "$hash" != "sha256" ]; then
		echo "Hashtype $hash not supported or invalid."
		exit 1
	fi

		# create the temporary file
	if [ -e "$CSR_GEN_INFO" ]; then
		rm -f $CSR_GEN_INFO > /dev/null
	else
		touch $CSR_GEN_INFO
		if [ $? != 0 ]; then
			echo "Unable to generate CSR"
			exit 1
		fi
	fi
	#
	# if we are here, the temp file is created, prompt the user for data
	#
	promptCSRInfo

	echo "Generating CSR, file name is: $switchIp$CSR_SUFFIX"
	$OPENSSL_CMD req -$hash -new -key $PVT_KEY_FILE \
		-out $CERT_DIR/$switchIp$CSR_SUFFIX  \
		-config $CSR_GEN_INFO 2> /dev/null

	#
	# Tell PDM to synchronize
	#
	if [ $? -eq 0 ]; then
		config save $CERT_DIR
		$AUDIT_NOTIFY "$CERT_GEN_CSR" "$switchIp$CSR_SUFFIX"
		fqdn_set
		echo Done.
	else
		echo
		echo "CSR Generation failed".
	fi

	if [ -e "$CSR_GEN_INFO" ]; then
		rm -f $CSR_GEN_INFO > /dev/null
	fi
;;

$CERT_DEL_CSR )
    csr_count=0
    csr_deleted=0
	
    csr_count=`ls $CERT_DIR/. | grep $CSR_SUFFIX | wc -l`
	if [ $csr_count -ge 1 ]; then
		#Assign if nowarn is provided	
		if [ "$2" == "-nowarn" ]; then
			response="yes"
		elif [ -n "$2" ]; then
			usage
			exit 1
		fi

		#Loop through files
        for csr_files in `ls $CERT_DIR/*$CSR_SUFFIX`; do
			if [ -s $csr_files ]; then 
				confirmDelete $CSR_FILE $csr_files
				deleteStatus=$?
				if [ $deleteStatus -eq 0 ]; then
					$AUDIT_NOTIFY "$CERT_DEL_CSR" "$csr_files"
				fi
				csr_deleted=1
			fi
		done

		#if no file is deleted, then all csr's are of size zero.
		if [ $csr_deleted -eq 0 ]; then
			echo "CSR does not exist."
		fi
	else
		echo "CSR does not exist."
	fi
;;

$CERT_EXPORT )
	if [ $# -gt 14 ]
	then
		usage
		exit 1
	fi

	declare -a cmdargs

	ldapCaCert=0
	syslogCaCert=0
	count=0
 	fcapCaCert=0
	fcapSwCert=0
	fcapSwCsr=0
    optflag=0
    fileoptflag=0
	commonSwCsr=0
	commonCaCert=0
	commonSwCert=0
	
	for arg in "$@"
	do
		cmdargs[$count]=$arg
		count=`expr $count + 1`
	done
	cmdargs[$count]="NULL"
	count=1

	while [ $INFINITE_LOOP ]
	do
	    case ${cmdargs[count]} in
			"$LDAPCACERT_OPT" )
			if [ "$optflag" -eq 0 ] ; then
				ldapCaCert=1
				optflag=1
			else
				usage
				exit 1
			fi
			;;
 
            "$SYSLOGCACERT_OPT" )
            if [ "$optflag" -eq 0 ] ; then
                syslogCaCert=1
                optflag=1
            else
                usage
                exit 1
            fi
            ;;

  			"$FCAPCACERT_OPT" )
			if [ "$optflag" -eq 0 ]; then
				fcapCaCert=1
				optflag=1
			else
				usage
				exit 1
			fi	
			;;
  
  			"$FCAPSWCERT_OPT" )
			if [ "$optflag" -eq 0 ] ; then
				fcapSwCert=1
				optflag=1
			else	
				usage
				exit 1
			fi	
			;;
        		
   			"$FCAPSWCSR_OPT" )
			if [ "$optflag" -eq 0 ] ; then
				fcapSwCsr=1
				optflag=1
			else
				usage
				exit 1
			fi	
			;;
 
   			"$COMMONCERT_CA_CRT" )
			if [ "$optflag" -eq 0 ]; then
				fcapCaCert=1
				commonCaCert=1
				optflag=1
			else
				usage
				exit 1
			fi	
			;;
  
  			"$COMMONCERT_SW_CRT" )
			if [ "$optflag" -eq 0 ] ; then
				fcapSwCert=1
				commonSwCert=1
				optflag=1
			else	
				usage
				exit 1
			fi	
			;;
        		
   			"$COMMONCERT_SW_CSR" )
			if [ "$optflag" -eq 0 ] ; then
				fcapSwCsr=1
				commonSwCsr=1
				optflag=1
			else
				usage
				exit 1
			fi	
			;; 

			"-ipaddr" )
			count=`expr $count + 1`
			ipAddr=${cmdargs[count]}
			;;

			"-remotedir" )
			count=`expr $count + 1`
			remoteDir=${cmdargs[count]}
			;;

			"-certname" )
			count=`expr $count + 1`
			certFileName=${cmdargs[count]}
			;;

			"-login" )
			count=`expr $count + 1`
			userName=${cmdargs[count]}
			;;

			"-password" )
			count=`expr $count + 1`
			password1=${cmdargs[count]}
			;;

			"-protocol" )
			count=`expr $count + 1`
			protocol=${cmdargs[count]}
			protocol=`echo $protocol | tr "[:upper:]" "[:lower:]"`
			;;

	    	"NULL" )
			break
			;;

	    	* )
			usage
			exit 1
			;;

	    esac
	    count=`expr $count + 1`
	done

	if [ $commonCaCert -eq 1 ] || [ $commonSwCert -eq 1 ] || [ $commonSwCsr -eq 1 ];then
		fipsCheck
		if [ $? -eq 0 ]; then
			echo "Common Cert related operations are not allowed in FIPS Mode."
		exit 1
		fi
	fi
 
  	if [ "$protocol" == "$PROT_FTP" ] && [ ! -z "$secure_mode" ] && [ $secure_mode -eq 0 ]; then
		echo "Secure communication is enabled. FTP is disabled. Use SCP for file transfer..."
		exit 1
	fi
	if [ "$protocol" == "$PROT_SCP" ] && [ -n "$password1" ]; then
		echo "Don't enter the password in command line for SCP"
		exit 1
	fi

  	if [ $fcapCaCert -eq 1 ] && [ -n "$certFileName" ]; then
		fileoptflag=1
 	elif [ $fcapSwCert -eq 1 ] && [ -n "$certFileName" ]; then
		fileoptflag=1
  	elif [ $fcapSwCsr -eq 1 ] && [ -n "$certFileName" ]; then
		fileoptflag=1
	fi
	
	if [ $fileoptflag -eq 1 ]; then
		echo "certname option can be used only with ldapcacert."
		exit 1
	fi
    if ([ "$syslogCaCert" -eq 1 ] || [ "$ldapCaCert" -eq 1 ] ) && [ -n "$certFileName" ]; then
		echo "$certFileName" | grep '/' >/dev/null 2>&1
		if [ "$?" -eq 0 ]; then
			echo "Filename cannot be provided with path"
			exit 1
		fi
	fi
 	if [ "$fcapCaCert" -eq 1 ]; then 
		if [ ! -f $FCAP_DIR/$FCAP_CACERT_FILE ]; then
			if [ "$commonCaCert" == 1 ]; then
 				echo "Common CA certificate file does not exist. Operation cancelled."    			
			else
				echo "FCAP CA certificate file does not exist. Operation cancelled."
			fi
 			exit 1
		elif [ ! -s $FCAP_DIR/$FCAP_CACERT_FILE ]; then
 			echo "File is empty and cannot be exported. Operation cancelled."					
			exit 1
		fi
	elif [ $fcapSwCert -eq 1 ]; then
		if [ ! -f $FCAP_DIR/$FCAP_SWCERT_FILE ]; then
 			if [ "$commonSwCert" == 1 ]; then
  		   		echo "Common SW certificate file does not exist. Operation cancelled." 
			else 
 		   		echo "FCAP SW certificate file does not exist. Operation cancelled."
			fi
			exit 1
 		elif [ ! -s $FCAP_DIR/$FCAP_SWCERT_FILE ]; then
 			echo " File is empty and cannot be exported. Operation cancelled."					
			exit 1
		fi
 	elif [ $fcapSwCsr -eq 1 ]; then 
		if [ ! -f $FCAP_DIR/$FCAP_SWCSR_FILE ]; then
  			if [ "$commonSwCsr" == 1 ]; then
  		   		echo "Common SW CSR file does not exist. Operation cancelled." 
			else  
 		   		echo "FCAP SW CSR file does not exist. Operation cancelled."
			fi
			exit 1
 		elif [ ! -s $FCAP_DIR/$FCAP_SWCSR_FILE ]; then
 			echo "File is empty and cannot be exported. Operation cancelled."					
			exit 1
		fi
	fi

	promptHostInfo $CERT_EXPORT
;;

$CERT_IMPORT )
	# verify input arguments before processing
	if [ $# -gt 19 ]
	then
	    usage
	    exit 1
	fi

	declare -a cmdargs

	count=0
	for arg in "$@"
	do
		cmdargs[$count]=$arg
		count=`expr $count + 1`
	done
	cmdargs[$count]="NULL"
	count=1
	certConfig=0
	enableHttps=0
	swCert=0
	caCert=0
	ldapCaCert=0
    syslogCaCert=0
	nowarn=0
 	fcapSwCert=0
	fcapCaCert=0
	commonSwCert=0
	commonCaCert=0
	certFileOnly=0
    cli_fcapSwCert=0
	`$CONFIGSHOW_CMD | /bin/grep 'security.policymode' | /bin/grep -qE '1'`
	highSecurityModeFlag=`echo $? `
	while [ $INFINITE_LOOP ]
	do
	    case ${cmdargs[count]} in
	   	 "-config" )
 			if [ $ldapCaCert == 0 ] && [ $fcapCaCert == 0 ] && [ $fcapSwCert == 0 ]; then
 		       		count=`expr $count + 1`
				certConfig=1
				if [ "${cmdargs[count]}" == "swcert" ];	then
					swCert=1
				elif [ "${cmdargs[count]}" == "cacert" ]; then
					caCert=1
				else
				   	usage
					exit 1
				fi
 			else 
				echo "config option cannnot be used with 'ldapcacert' or 'fcapswcert' or 'fcapcacert' or 'commoncacert' " 
				usage
				exit 1
			fi
        		;;

		"-nowarn" )
			nowarn=1
			;;

    	"-enable" )
 	       		if [ $fcapCaCert == 0 ] && [ $fcapSwCert == 0 ]; then
			if [ $caCert -eq 1 ]; then
				echo "Enable option can not be used with 'cacert'"
				usage
				exit 1
			fi

			count=`expr $count + 1`
			if [ "${cmdargs[count]}" == "https" ]; then
			    	enableHttps=1
			else
			    	usage
			    	exit 1
			fi
         		else
				echo "Enable option can not be used with 'fcapswcert' or 'fcapcacert'"
        			usage
				exit 1
        		fi
        		;;

		"$LDAPCACERT_OPT" )
				ldapCaCert=1
			;;

        "$SYSLOGCACERT_OPT" )
                syslogCaCert=1
            ;;

   		"$FCAPCACERT_OPT" )
      			fcapCaCert=1
      		;;

		"$FCAPSWCERT_OPT" )
				fcapSwCert=1
			;;
			
       	"$COMMONCERT_CA_CRT" )
      			fcapCaCert=1
				commonCaCert=1
      		;;

		"$COMMONCERT_SW_CRT" )
			 	cli_fcapSwCert=1
				commonSwCert=1
			;; 

       	"-protocol" )
				count=`expr $count + 1`
				protocol=${cmdargs[count]}
				protocol=`echo $protocol | tr "[:upper:]" "[:lower:]"`
			;;

			"-ipaddr" )
				count=`expr $count + 1`
				ipAddr=${cmdargs[count]}
			;;

			"-remotedir" )
				count=`expr $count + 1`
				remoteDir=${cmdargs[count]}
			;;

			"-certname" )
				count=`expr $count + 1`
				certFileName=${cmdargs[count]}
				certFileOnly=1
			;;

			"-login" )
				count=`expr $count + 1`
				userName=${cmdargs[count]}
			;;

			"-password" )
				count=`expr $count + 1`
				password1=${cmdargs[count]}
			;;

			"-file" )
				count=`expr $count + 1`
				cmmCertFile=${cmdargs[count]}
			;;

	    	"NULL" )
			break
			;;

	    	* )
			usage
			exit 1
			;;

	    esac
	    count=`expr $count + 1`
	done

	if [ $commonCaCert -eq 1 ] || [ $commonSwCert -eq 1 ];then
		fipsCheck
		if [ $? -eq 0 ]; then
			echo "Common Cert related operations are not allowed in FIPS Mode."
		exit 1
		fi
	fi

	echo "$certFileName" | grep '/' >/dev/null 2>&1
	if [ "$?" -eq 0 ]; then
		echo "Filename cannot be provided with path"
		exit 1
	fi
	if [ $certConfig -ne 1 ]
	then
	    if [ $enableHttps -eq 1 ]
	    then
		echo
		echo "Secure protocol can not be enabled without configuring"
		echo "certificate. Please use \"-config\" option with" \
		    "\"-enable\""
		usage
		exit 1
	    fi
	fi
  	if [ "$protocol" == "$PROT_FTP" ] && [ ! -z "$secure_mode" ] && [ $secure_mode -eq 0 ]; then
		echo "Secure communication is enabled. FTP is disabled. Use SCP for file transfer.."
		exit 1
	fi

	if [ "$protocol" == "$PROT_SCP" ] && [ -n "$password1" ]; then
		echo "Don't enter the password in command line for SCP"
		exit 1
	fi
  
	if [ $cli_fcapSwCert -eq 1 ]; then
		fcapSwCert=1
	fi

	if [ -n "$cmmCertFile" ]; then
		addCMMSentCerts $CERT_IMPORT $cmmCertFile
	else
		promptHostInfo $CERT_IMPORT
	fi

	# set configuration as per options
	if [ $certConfig -eq 1 ]
	then
		if [ $swCert -eq 1 ]; then
			configToUpdate=$CERTCONFIG
		elif [ $caCert -eq 1 ]; then
			configToUpdate=$ROOTCERTCONFIG	
		fi
		config set $configToUpdate 5 $certFileName
		echo "Certificate file in configuration has been updated."
	fi

	if [ $enableHttps -eq 1 ]
	then
	    config set http.ssl.enabled 1 1
	    $WEBDHANDLER $HTTPCONFIG:1
	    echo "Secure http has been enabled."
	fi

 	if [ $fcapCaCert -eq 0 ] && [ $fcapSwCert -eq 0 ]; then 
        if [ $ldapCaCert -eq 1 ]; then
            /fabos/cliexec/config save $LDAP_DIR

        elif [ $syslogCaCert -eq 1 ]; then
            /fabos/cliexec/config save $SYSLOGCA_DIR
        else
            config update

        fi
	fi

	if [ $commonCaCert -eq 1 ]; then
   		cp $FCAP_DIR/$FCAP_CACERT_FILE $CERT_DIR/$COMMONCERT_CA_FILE
		config save $CERT_DIR
		fqdn_set
	fi

	if [ $commonSwCert -eq 1 ]; then
		if [ -f $FCAP_DIR/$FCAP_CERT_CONF_FILE ]; then
       		 #Now we parse the file to look for switch certificate name.
			IFS_=${IFS}; IFS=$'\n'
			for LINE in `cat $FCAP_DIR/$FCAP_CERT_CONF_FILE`; do
			    validate_string=`echo "$LINE" | awk -F':' ' { print $1 } '`

			    if [ $validate_string == "SWITCH_CERT_NAME" ] ; then
				    certFileName=`echo "$LINE" | awk -F':' ' { print $2 } '`
			    fi		
			done
			IFS=${IFS_} 
		fi   
      	cat $FCAP_DIR/$FCAP_TOUCH_FILE > $CERT_DIR/$certFileName
 		config save $CERT_DIR 
		rm -rf $FCAP_DIR/$certFileName
		fqdn_set
	fi
  

;;

$CERT_SHOW_CSR )
	if [ "$2" == "$FCAPSWCSR_OPT" ]; then
		CSR_FILE_PATH=$FCAP_DIR/$FCAP_SWCSR_FILE
		if [ ! -s "$CSR_FILE_PATH" ]; then
			echo "CSR does not exist. Use 'generate -fcapall' option to create it."
			exit 1
		fi
	elif [ "$2" == "$SWCSR_OPT" ] || [ "$2" == "" ];then
		CSR_FILE_PATH=$CERT_DIR/$switchIp$CSR_SUFFIX
		if [ ! -s "$CSR_FILE_PATH" ]; then
		echo "CSR does not exist. Use gencsr option to create it."
		exit 1
	fi
	else
		usage
		exit 1	
	fi

	$OPENSSL_CMD req -in $CSR_FILE_PATH \
		 -text -verify -noout -config $CONFIG_FILE
	if [ $? != 0 ]; then
		echo "$CSR_FILE_PATH: Is a unknown CSR format."
		exit 1
	fi

	echo
	echo "CSR contents in base64 format"
	echo
	cat "$CSR_FILE_PATH"
	echo
;;

$CERT_SHOW )
	ldapCaCert=0
    syslogCaCert=0
	fcap=0
	VID=-1

	if [ -z $2 ]; then
		showFiles $CERT_FILE
		echo
	elif [ "$2" == "$LDAPCACERT_OPT" ];then
		ldapCaCert=1
		showFiles "$LDAP_CERT_FILE"
		echo
    elif [ "$2" == "$SYSLOGCACERT_OPT" ];then
        syslogCaCert=1
 	if [ ! -z "$3" ] && [ "$3" != NULL ] ;then
		if [ -f $SYSLOGCA_DIR/$3 ]; then
		/bin/cat $SYSLOGCA_DIR/$3 
		else 
		echo "Syslog CA certificate $3 does not exist."
		fi
	else	
        	showFiles "$SYSLOG_CERT_FILE"
        	echo
	fi
	elif [ "$2" == "$FCAPSWCERT_OPT" ];then

		if [ ! -s $FCAP_DIR/$FCAP_TOUCH_FILE ]; then
			echo "The switch certificate file is empty. Please import the switch certificate."
			exit 1
        else
			echo "Displaying contents of switch certificate "
			cat $FCAP_DIR/$FCAP_TOUCH_FILE
		fi
		echo
 	elif [ "$2" == "$COMMONCERTALL" ]; then

		if [ ! -z "$3" ]; then
			usage
			exit 1
		fi

        #Check for FIPS
        fipsCheck
		if [ $? -eq 0 ]; then
			echo "Common Cert related operations are not allowed in FIPS Mode."
			exit 1
		fi

        #Show FCAP
		fcap=1
		showFiles "common certificate"

       #Show HTTPS
		getSwichId "logical"
		VID=$?

		if [ $VID != -1 ];then
			# This means VF is enabled.
			getSwichId "default"
			DEFAULT_VID=$?
			setcontext $DEFAULT_VID
    	fi
	
		cacert=`config get $ROOTCERTCONFIG 5 2> /dev/null`
		if [ "$DEFAULTROOTCERTCONFIG" == "$cacert" ]; then
			echo "CA              : Empty"
		elif [ -z "$cacert" ]; then
			echo "CA              : Empty"
		else
			echo "CA              : Exist"
		fi	

		httpSEnabled=`config get $HTTPCONFIG 1`
		if [ "$httpSEnabled" == 1 ]; then
			echo "HTTPS           : Exist"
		fi

		if [ $VID != -1 ];then
			setcontext $VID
		fi
		echo
 	elif [ "$2" == "$FCAP" ]; then
		if [ ! -z "$3" ]; then
                	usage
			exit 1
		fi
		fcap=1
		showFiles "$FCAP_ALL"
		echo
    elif [ -s "$CERT_DIR/$2" ]; then
		echo "Displaying contents of $2"
		cLen=`expr length $2`
		let dotIndex="$cLen"-3
		fileSuffix=`expr substr $2 $dotIndex $cLen`
		if [ "$fileSuffix" == "$CER_SUFFIX" ] || \
		[ "$fileSuffix" == "$CRT_SUFFIX" ]; then
			$OPENSSL_CMD x509 -in $CERT_DIR/$2 -inform DER \
			 -outform PEM -out $CERT_DIR/$TEMP_CACRT
			echo
				$OPENSSL_CMD x509 -in $CERT_DIR/$TEMP_CACRT \
				 -text -noout | more
				$RM -rf $CERT_DIR/$TEMP_CACRT
		elif [ "$fileSuffix" == "$PSK_SUFFIX" ]; then
			cat $CERT_DIR/$2 | more
		else
			$OPENSSL_CMD x509 -in $CERT_DIR/$2 -text -noout | more
		fi
		if [ $? != 0 ]; then
			echo "$2: Is a unknown x509 format."
		fi
	elif [ "$2" == "$ALL" ]; then
		if [ $curLogin != "root" ]; then
			echo "Permission denied to perform this operation."
			exit 1
		fi
		echo "                    "
		echo "ssh private key: "
		if [ -f $PRIVKEY_DIR/$PRIVKEY_FILE ] || \
			[ -f $PRIVKEY_DIR/$PRIVKEY_FILE_OLD ]; then
			echo "   Exists"
		else
			echo "   Does not Exist"
		fi	
		echo "                    "
		echo "ssh public keys available for users: "
		pub_file=`$LL $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.* 2> /dev/null`
		if [ -z "$pub_file" ]; then
			echo "   None"
		else
			for users in `$LS $IMPORT_PUBKEY_DIR/$IMPORT_PUBKEY_FILE.* 2> /dev/null` 
		 	do 	
				userval=`echo $users | $CUT -d " " -f 24 | $CUT -d "." -f 3 2> /dev/null`
        		echo "   $userval"
			done
		fi
		echo "                    "
		echo "Certificate Files:"
		echo -n "------------------------------------------------------------------------"
		echo "--------------------------------------------"
		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "Protocol" "CA" "SW" "Location" \
				 "CSR" "PVT Key" "Passphrase"
		echo -n "------------------------------------------------------------------------"
		echo "--------------------------------------------"
		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "FCAP" $FCAP_CACERT_FILE \
			$FCAP_SWCERT_FILE $FCAP_DIR \
			`/fabos/cliexec/pkishow --fcap | grep CSR | $CUT -d ":" -f 2` \
			`/fabos/cliexec/pkishow --fcap | grep "Private Key" | $CUT -d ":" -f 2` \
			`/fabos/cliexec/pkishow --fcap | grep "Passphrase" | $CUT -d ":" -f 2`
		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "LDAP" $LDAP_CACERT_FILE "NA" \
			$LDAP_DIR "NA" "NA" "NA"
		if [ -f $SYSLOGCA_DIR/*.pem ]; then
			syslogcaCert="Exist"
		else
			syslogcaCert="Empty"
		fi
		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "SYSLOG" "$syslogcaCert" "NA" \
			$SYSLOGCA_DIR "NA" "NA" "NA"
		httpSEnabled=`config get $HTTPCONFIG 1`
		if [ "$httpSEnabled" == 1 ]; then
			httpsCert=`config get $CERTCONFIG 5`
		else
			httpsCert="Empty"
		fi
		# Truncate the long file names
		if [ `echo ${#httpsCert}` -gt 20 ]; then
			httpsCert=$(echo $httpsCert | $CUT -c1-20)
		fi

		if [ -s $PVT_KEY_FILE ]; then
			pvtKey="Exist"
		else
			pvtKey="Empty"
		fi

		if [ -s "$CERT_DIR/$switchIp$CSR_SUFFIX" ]; then
			csrFile="Exist"
		else
			csrFile="Empty"
		fi
		
		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "HTTPS" "NA" $httpsCert \
				$CERT_DIR $csrFile $pvtKey "NA"
		cacert=`config get $ROOTCERTCONFIG 5 2> /dev/null`
		if [ $? != 0 ]; then
			cacert="Empty"
		fi	
		if [ `echo ${#cacert}` -gt 20 ]; then
			cacert=$(echo $cacert | $CUT -c1-20)
		fi
		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "cacert" $cacert "NA" $CERT_DIR \
				$csrFile $pvtKey "NA"
		for certFile in $CERT_DIR/*
		do
			# extract the file name from full dir path
			certFile=`echo $certFile | $CUT -d "/" -f 6`
			# Quit, if no cert available
			if [ "$certFile" == "*" ]; then
				break
			fi
			# Skip the already displayed certs and NULL cert files
			if [ "`echo $certFile | $CUT -d "." -f 5`" == "csr" ] || \
			[ "$certFile" == "pvt_key" ] || [ "$certFile" == "$httpsCert" ] || \
			[ "$certFile" == "$cacert" ] || [ ! -s $certFile ]; then
				continue
			fi
			if [ `echo ${#certFile}` -gt 20 ]; then
				certFile=$(echo $certFile | $CUT -c1-20)
			fi
			printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "Others" $certFile "NA" \
				$CERT_DIR "NA" "NA" "NA"
		done
	elif [ -e "$LDAP_DIR/$2" ]; then
		echo "Displaying contents of $2"
		cLen=`expr length $2`
		let dotIndex="$cLen"-3
		fileSuffix=`expr substr $2 $dotIndex $cLen`
		if [ "$fileSuffix" == "$CER_SUFFIX" ] || \
		[ "$fileSuffix" == "$CRT_SUFFIX" ]; then
			$OPENSSL_CMD x509 -in $LDAP_DIR/$2 -inform DER \
			 -outform PEM -out $LDAP_DIR/$TEMP_CACRT
			echo
				$OPENSSL_CMD x509 -in $LDAP_DIR/$TEMP_CACRT \
				 -text -noout | more
				$RM -rf $LDAP_DIR/$TEMP_CACRT
		else
			$OPENSSL_CMD x509 -in $LDAP_DIR/$2 -text -noout | more
		fi
		if [ $? != 0 ]; then
			echo "$2: Is a unknown x509 format."
		fi

	else
		echo "$2: file does not exist"
	fi
;;

$CERT_DELE )
	# verify input arguments before processing
	if [ $# -gt 5 ]
	then
	    usage
	    exit 1
	fi
	ldapCaCert=0
    syslogCaCert=0
 	fcapCaCert=0
	fcapSwCert=0
	fcap=0
	commoncert=0
 
	declare -a cmdargs
	cmdargs=($2 $3 $4 $5 "NULL")
	response=
	file=NULL
	flag=0
	count=0

	while [ $INFINITE_LOOP ]
	do
		case ${cmdargs[count]} in
		"-nowarn" )
			response="yes"
			;;

		"$LDAPCACERT_OPT" )
			ldapCaCert=1
			;;

        "$SYSLOGCACERT_OPT" )
            syslogCaCert=1
            ;;

 		"$FCAPSWCERT_OPT" )
			fcapSwCert=1
			;;

		"$FCAPCACERT_OPT" )
			fcapCaCert=1
			;;

		"$FCAP" )
			fcap=1
			;;

		"$COMMONCERTALL" )
			commoncert=1
			;;

		"NULL" )
			break
			;;

		* )
			file=${cmdargs[count]}
			;;

		esac
	    count=`expr $count + 1`
	done

	if [ $commoncert -eq 1 ];then
		fipsCheck
		if [ $? -eq 0 ]; then
			echo "Common Cert related operations are not allowed in FIPS Mode."
		exit 1
		fi
	fi

	echo "$file" | grep '/' >/dev/null 2>&1
	if [ "$?" -eq 0 ]; then
		echo "Filename cannot be provided with path"
		exit 1
	fi

	if [ "$file" = "$switchIp$CSR_SUFFIX" ]; then
		echo "Use delcsr option to delete CSR."
		exit 1
	fi
	if [ "$file" = "$PVT_KEY" ]; then
		echo "Use delkey option to delete pvt_key."
		exit 1
	fi
	if [ $fcapSwCert -eq 1 ] || [ $fcapCaCert -eq 1 ] || [ $fcap -eq 1 ]; then 
		if [ "$file" != NULL ]; then
			usage
			exit 1
		fi
	fi

	if [ $ldapCaCert -eq 1 ]; then
		if [ -z "$file" ] || [ "$file" = NULL ] ; then
                        file="$LDAP_CACERT_FILE"
		fi

		if [ -e "$LDAP_DIR/$file" ];then
			confirmDelete $CERT_FILE $file
		else
			echo "Specified LDAP certificate does not exist"
			exit 1
		fi

    elif [ $syslogCaCert -eq 1 ]; then
        if [ -z "$file" ] || [ "$file" = NULL ] ; then
            usage
            exit 1
        fi

        if [ -e "$SYSLOGCA_DIR/$file" ] || [ "$file" = "-all" ];then
            confirmDelete $CERT_FILE $file
        else
            echo "Specified Syslog CA certificate does not exist"
            exit 1
        fi

 	elif [ $fcap -eq 1 ]; then
		file="All FCAP Files"
		confirmDelete $FCAP_ALL_FILE $file

	elif [ $fcapSwCert -eq 1 ]; then 
		file="$FCAP_SWCERT_FILE"
		confirmDelete $FCAP_SW_CERT_FILE $file

	elif [ $fcapCaCert -eq 1 ]; then
		file="$FCAP_CACERT_FILE"
		confirmDelete $FCAP_CA_CERT_FILE $file

	elif [ $commoncert -eq 1 ]; then
        file="All FCAP Files"
		confirmDelete $FCAP_ALL_FILE $file
		cleanUpHTTPS
		config set $ROOTCERTCONFIG 5 none
	else
		if [ -z "$file" -o "$file" = NULL ]; then
			usage
			exit 1
	#Defect:329258-check to verify the file being deleted is 
	#available or not in the certs/sw0 directory.	
		elif [ ! -e "$CERT_DIR/$file" ] || [ ! -s "$CERT_DIR/$file" ]; then
			echo "$file: Certificate not found"
			exit 1
		fi

		check_secure_protocols "$file"
		confirmDelete $CERT_FILE $file
	fi

	if [ $? -eq 0 ]; then
		$AUDIT_NOTIFY "$CERT_DELE" "$file"
	fi
;;
 
$CERT_GEN )
	# verify input arguments before processing
 	declare -a cmdargs
	fcap=0
	cmdargs=($2 $3 $4 $5 "NULL")
	response="no"
	file=
	key_size=0
	flag=0
	count=0
	commoncert=0

	while [ $INFINITE_LOOP ]
	do
		case ${cmdargs[count]} in
		"-nowarn" )
			response="yes"
			;;

		"$FCAP" )
			fcap=1
			;;

		"$COMMONCERTALL" )
			commoncert=1
			;;
			
		"-keysize" )
			count=`expr $count + 1`
			key_size=${cmdargs[count]}
			;;

		"NULL" )
			break
			;;

		* )
 			usage
			exit 1
			;;
	    esac
	    count=`expr $count + 1`
	done
	
 	if [ $commoncert -eq 1 ];then
		fipsCheck
		if [ $? -eq 0 ]; then
			echo "Common Cert related operations are not allowed in FIPS Mode."
		exit 1
		fi
	fi

	if [ $fcap -eq 0 ] && [ $commoncert -eq 0 ]; then
		usage
		exit 1
	fi
 
 	if [ $response == "no" ]; then
		echo "Generating a new key pair will automatically do the following:"
		if [ $commoncert -eq 1 ]; then
 			echo "1. Delete all existing CSRs for HTTPS and FCAP."
			echo "2. Delete existing switch certificate for HTTPS and FCAP."
			echo "3. Reset the certificate filename to none." 
		else
			echo "1. Delete all existing CSRs."
			echo "2. Delete existing switch certificate."
			echo "3. Reset the certificate filename to none."
		fi
		echo
		echo -n "Continue (yes, y, no, n): [no] "
		read response

		if [ "$response" == "" ]; then
			response=no
		fi

		resp=`echo $response | tr "[:lower:]" "[:upper:]"`

		if [ "$resp" = "N" -o "$resp" = "NO" ]; then
			echo "Operation cancelled."
			exit 0
		fi

		if [ "$resp" != "Y" -a "$resp" != "YES" ]; then
			echo "Invalid input. Exiting"
			exit 1
		fi
	fi

 	if [ "$key_size" == 0 ]; then
		echo -n "Select key size [1024 or 2048]: "
		read key_size
	fi	

	# "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
    retVal=`/fabos/cliexec/config get fips.mode 2`
	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
    if [ $retVal -eq 1 ]; then
    	if [ $key_size -lt 2048 ]; then
        	echo "Key size less than 2048 is not allowed in FIPS Mode."
            exit 1
	    fi
    fi
	
	if [ "$key_size" != 1024 ] && [ "$key_size" != 2048 ]; then
		echo Unsupported key size: "$key_size"
		exit 1
	fi

	cleanUpFCAP
	if [ $? != 0 ] ; then
		echo "Operation Failed."
		exit 1
	fi

	syncUpFCAP
 	if [ $? != 0 ] ; then
		echo "Operation Failed."
		exit 1
	fi

    if [ "$commoncert" == 1 ]; then
       cleanUpHTTPS
       config set $ROOTCERTCONFIG 5 none
    fi
 
	if [ "$fcap" == 1 ] || [ "$commoncert" == 1 ]; then
		confirmGenerate $key_size       
		if [ $? -eq 0 ]; then
			syncUpFCAP
			if [ $? != 0 ] ; then
				echo "Operation Failed."
				exit 1
			fi
			$AUDIT_NOTIFY "$CERT_GEN" "$FCAP_SWPRVKEY_FILE (keysize:$key_size), $FCAP_SWCSR_FILE"
		fi
		fqdn_set
	else
		usage
		exit 1
	fi

	if [ "$fcap" == 1 ]; then
		if [ -e $FCAP_DIR/$COMMONCERT_PRVT_KEY ]; then
			$RM -rf $FCAP_DIR/$COMMONCERT_PRVT_KEY
		fi
	elif [ "$commoncert" == 1 ]; then
		if [ ! -e $FCAP_DIR/$COMMONCERT_PRVT_KEY ]; then
            echo "Unable to generate common cert files."

			cleanUpFCAP
			if [ $? != 0 ] ; then
				echo "Operation Failed."
				exit 1
			fi

			syncUpFCAP
			if [ $? != 0 ] ; then
				echo "Operation Failed."
				exit 1
			fi 
			exit 1
		else
			mv $FCAP_DIR/$COMMONCERT_PRVT_KEY $PVT_KEY_FILE
			/bin/chmod 400 $PVT_KEY_FILE 
			cp $FCAP_DIR/$FCAP_SWCSR_FILE $CERT_DIR/$switchIp$CSR_SUFFIX
			config save $CERT_DIR

		fi
	fi

;;
 
$CERT_FIPS_COMPL )
	fips_compl_ret=0
	# check for ldap ca certificate compliance
	if [ -e "$LDAP_DIR/$LDAP_CACERT_FILE" ]; then
		caCertComplTest "$LDAP_DIR/$LDAP_CACERT_FILE" \
			"LDAP CA certificate"
		temp=$?
		if [ $temp -ne 0 ];then
			fips_compl_ret=$temp
		fi
	fi

	# check for switch ca certificate compliance
	cacert=`config get $ROOTCERTCONFIG 5 2> /dev/null`
	if [ "$DEFAULTROOTCERTCONFIG" != "$cacert" ] &&
		[ ! -z "$cacert" ]; then
		caCertComplTest "$CERT_DIR/$cacert" "Switch CA certificate"
		temp=$?
		if [ $temp -ne 0 ];then
			fips_compl_ret=$temp
		fi
	fi

	# check for HTTPS certificate compliance
	httpSEnabled=`config get $HTTPCONFIG 1`
	if [ "$httpSEnabled" == 1 ]; then
		httpsCert=`config get $CERTCONFIG 5`
		caCertComplTest "$CERT_DIR/$httpsCert" "HTTPS certificate"
		temp=$?
		if [ $temp -ne 0 ];then
			fips_compl_ret=$temp
		fi
	fi

	# check for fcap certificate compliance
	if [ -e "$FCAP_DIR/$FCAP_SWCERT_FILE" ]; then
		caCertComplTest "$FCAP_DIR/$FCAP_SWCERT_FILE" \
			"FCAP certificate"
		temp=$?
		if [ $temp -ne 0 ];then
			fips_compl_ret=$temp
		fi
	fi

	# check for fcap ca certificate compliance
	if [ -e "$FCAP_DIR/$FCAP_CACERT_FILE" ]; then
		caCertComplTest "$FCAP_DIR/$FCAP_CACERT_FILE" \
			"FCAP CA certificate"
		temp=$?
		if [ $temp -ne 0 ];then
			fips_compl_ret=$temp
		fi
	fi

	exit $fips_compl_ret
;;

$CERT_HELP )
	usage
;;

* )
	usage
	exit 1
;; 
esac

exit 0

