#!/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
MV="/bin/mv"
MKDIR="/bin/mkdir"
TOUCH="/bin/touch"
CP="/bin/cp"
RM=/bin/rm
LS=/bin/ls
LL="/bin/ls -l"
CUT="/usr/bin/cut"
EXPR="/fabos/bin/expr"
HOSTNAME="/bin/hostname"
WWN="/fabos/bin/wwn"
SED="/bin/sed"
GREP=/bin/grep
CAT=/bin/cat
ECHO=/bin/echo
AWK=/bin/awk
WC=/usr/bin/wc
OPENSSL_CMD=/usr/bin/openssl
# OPENSSL_CMD_NO_FIPS is required as OPENSSL_CMD changes to fipsopenssl in FIPS mode.
FIPSOPENSSL_CMD="/usr/bin/fipsopenssl"
EMBEDDED_OPENSSL_CONF="/etc/fabos/embedded_openssl.cnf"
OPENSSL_CMD_NO_FIPS=/usr/bin/openssl
CONFIGSHOW_CMD="/fabos/cliexec/configshow -chassis"
SSHUTIL_NOTIFY=/fabos/libexec/sshutil_notify
SECCERT_GENERATE="/fabos/sbin/secgenerate"
SECCERTUTIL="/fabos/sbin/seccertutil"
GEN_AUTH=/fabos/libexec/gen_auth
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
DSA_PARAMS_FILE=dsaparam.pem

# 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"
SYSLOG_CACERT_FILE="ca.pem"
SYSLOG_LINK_HASH="syslog_link_hash"
TEMP_SYSLOG_LINK_HASH="temp_syslog_link_hash"

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

TEMP_CERTGEN_PATH="/tmp/certgen/"
BACKUP_CERTS="backup_certs"
CA_PRIVATE_KEY="cakey.pem"
CA_CERT="cacert.pem"
SWITCH_CERT="servercert.pem"
DEFAULTCSR="switchip.csr"
HTTPS="-https"
FCAPS="-fcap"
COMMONCERT="-commoncert"
CASOURCE="-ca"
KEYTYPE="-type"
KEYSIZE="-keysize"
HASHTYPE="-hash"
YEARS="-years"

COUNTRY="US"
STATE="California"
LOCALITY="San Jose"
ORGANIZATION="Brocade"
ORGANIZATION_UNIT="Eng"
COMMON_NAME="Brocade"
CA_POLICY="policy_anything"
MESSAGE_DIGEST="sha256"
# To be changed based on what password to use or to read from file
# instead of stdin
RANDOM_NUMBER=`$OPENSSL_CMD rand -base64 16`

# 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
	        $RM /fabos/link_sbin/lscfg_test
	fi
	
	return $VID
}

setDefaultContext() {
    getSwichId "logical"
    VID=$?

    if [ $VID != -1 ];then
        # This means VF is enabled.
        getSwichId "default"
        DEFAULT_VID=$?
        setcontext $DEFAULT_VID
    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
}

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

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

}

#
# 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() {
	httpsSwCert=`config get $CERTCONFIG 5`
	httpsCaCert=`config get $ROOTCERTCONFIG 5`

 	file=`$LS $CERT_DIR/*$CRT_SUFFIX $CERT_DIR/*$CER_SUFFIX \
		$CERT_DIR/*$PEM_SUFFIX $CERT_DIR/*$PSK_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
				certname=`/bin/basename $i`
				certKey=""

				if [ "$httpsSwCert" == "$certname" ]; then
					certKey="BRCD_HTTPS_SW"
				elif [ "$httpsCaCert" == "$certname" ]; then
					certKey="BRCD_HTTPS_CA"
				fi

				$AUDIT_NOTIFY "$CERT_DELE" "$certname" "$certKey"
			fi
		fi
	    done
	fi

	file=`$LS $CERT_DIR/*$CSR_SUFFIX 2> /dev/null`
	if [ ! -z "$file" ]; then
		if [ -s "$file" ]; then
			$CAT /dev/null > $file
		fi
	fi

	if [ -e "$PVT_KEY_FILE" ]; then
			size=`/bin/ls -la $PVT_KEY_FILE | $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

    setDefaultContext
    VID=$?

	# 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`
	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" ]; then
		certpkey="BRCD_HTTPS_SW"
	elif [ "$1" == "$caCert" ]; then
		certpkey="BRCD_HTTPS_CA"
	else
		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() {
	certPresent=0
	caPresent=0
	certIndex=1
	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 | $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 | $AWK ' { print $5 } '`
                        	   /bin/dd if=/dev/zero of=$i bs=1 count=$size 2> /dev/null
 				 done
				fi

				totalCerts=0
				if [ -f $SYSLOGCA_DIR/$SYSLOG_LINK_HASH ] && [ -s $SYSLOGCA_DIR/$SYSLOG_LINK_HASH ]; then
				  totalCerts=`$CAT $SYSLOGCA_DIR/$SYSLOG_LINK_HASH | $GREP $PEM_SUFFIX | $WC -l | tr -d ' '`
				  $CAT /dev/null > $SYSLOGCA_DIR/$SYSLOG_LINK_HASH
				  certPresent=1
				fi
				$RM -rf $SYSLOGCA_DIR/* > /dev/null
				if [ $? -ne 0 ];then
					$ECHO "Could not delete Syslog CA certificates"
					exit 1
				else
					/fabos/cliexec/config save $SYSLOGCA_DIR

					if [ $certPresent -eq 0 ]; then
						$ECHO "Syslog CA certificates does not exist"
						return 1
					else
						$ECHO "Deleted all Syslog CA certificates successfully"
                        certs=( $file )
                        while [ $totalCerts -gt 0 ]; do
                            certpkey="BRCD_SYSLOG_"$totalCerts
                            totalCerts=`expr $totalCerts - 1`
                            $AUDIT_NOTIFY "$CERT_DELE" "`/bin/basename ${certs[$totalCerts]}`" "$certpkey"
                        done

						exit 0
					fi
				fi
			else
#				certIndex=`$CAT $SYSLOGCA_DIR/$SYSLOG_LINK_HASH | $GREP -n $2 | $AWK -F':' ' { print $1 } '`
#				certpkey="BRCD_SYSLOG_"$certIndex
				certpkey="BRCD_SYSLOG_1"

				#Get the syslog link file
				SYSLOG_LINK=`$CAT $SYSLOGCA_DIR/$SYSLOG_LINK_HASH | $GREP "$2" | $AWK ' { print $2 }'`
				size=`/bin/ls -la $SYSLOGCA_DIR/$2 | $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 $SYSLOGCA_DIR/$SYSLOG_LINK_HASH 2> /dev/null
#					$RM -rf $SYSLOG_LINK > /dev/null
#					$SED "/$2/d" $SYSLOGCA_DIR/$SYSLOG_LINK_HASH > $SYSLOGCA_DIR/$TEMP_SYSLOG_LINK_HASH	
#					$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
					/fabos/cliexec/config save $SYSLOGCA_DIR
					/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

	    setDefaultContext
    	VID=$?
 
		# 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
        if [ -s $FCAP_DIR/$FCAP_SWCERT_FILE ]; then
            certPresent=1
        fi
		if [ -s $FCAP_DIR/$FCAP_CACERT_FILE ]; then
			caPresent=1
		fi

    	setDefaultContext
	    VID=$?

		# /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

		if [ $certPresent -eq 0 ] || [ $caPresent -eq 0 ]; then
			$ECHO "FCAP certificate(s) doesnt exist"
			if [ $certPresent -eq 1 ]; then
				$AUDIT_NOTIFY "$CERT_DELE" "$FCAP_SWCERT_FILE" "BRCD_FCAP_SW"
			fi
	        if [ $caPresent -eq 1 ]; then
				$AUDIT_NOTIFY "$CERT_DELE" "$FCAP_CACERT_FILE" "BRCD_FCAP_CA"
        	fi
			return 1;
		fi
	elif [ "$1" == "$FCAP_CA_CERT_FILE" ]; then
		if [ -s $FCAP_DIR/$FCAP_CACERT_FILE ]; then
			certPresent=1
		fi

		updateFCAPConfigFile "ROOT_CA_CERTIFICATES:0"
		$CAT /dev/null > $FCAP_DIR/$FCAP_CACERT_FILE
 		config save $FCAP_DIR/$FCAP_CACERT_FILE
		syncUpFCAP
        if [ $certPresent -eq 0 ]; then
			$ECHO "FCAP CA certificate doesnt exist"
            return 1;
        fi
	elif [ "$1" == "$FCAP_SW_CERT_FILE" ]; then
        if [ -s $FCAP_DIR/$FCAP_SWCERT_FILE ]; then
            certPresent=1
        fi
		$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
        if [ $certPresent -eq 0 ]; then
			$ECHO "FCAP Switch certificate doesnt exist"
            return 1;
        fi
	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 -hashtype $2
	return $?
}

confirmSelfSignedCertGenerate() {
	
    if [ "$response" == "no" ]; then
		$ECHO "Generating a new certificate will automatically do the following"
		$ECHO "1. Delete existing switch certificate(s)."
		$ECHO "2. Disable secure protocol HTTPS"
		$ECHO
		$ECHO "Warning: Certificate generation is CPU intensive and can cause high CPU usage"
		$ECHO
		$ECHO -n "ARE YOU SURE TO 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."
        return 1
    fi

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

	return 0
}

GenerateSelfSignedCerts() {

    confirmSelfSignedCertGenerate

    if [ $? != 0 ] ; then
        exit 1
    fi

    if [ "$key_size" != 1024 ] && [ "$key_size" != 2048 ]&& [ "$key_size" != 4096 ]&& [ "$key_size" != 8192 ]; then
        $ECHO Unsupported key size: "$key_size"
        exit 1
    fi

    if [ "$hashtype" != "sha1" ] && [ "$hashtype" != "sha256" ] && [ "$hashtype" != "sha512" ]; then
        $ECHO "Invalid hashtype value passed: $hashtype"
        exit 1
    fi

    days=`$EXPR $years \* 365`

    #Create backup directory
    $MKDIR -p $TEMP_CERTGEN_PATH/$BACKUP_CERTS

    #if set, bash allows patterns which match no files to expand to a null string, rather than themselves
    shopt -s nullglob

    files=($CERT_DIR/*.pem)
    if [ ${#files[@]} -gt 0 ]; then
        $CP $CERT_DIR/* $TEMP_CERTGEN_PATH/$BACKUP_CERTS/ 2> /dev/null
    fi
		
    shopt -u nullglob
    commonname=`$HOSTNAME -i`
    cleanUpHTTPS

    cd $TEMP_CERTGEN_PATH

    if [ "$keytype" == "rsa" ] || [ "$keytype" == "dsa" ]; then
    	if [ "$keytype" == "dsa" ]; then
 	    if [ "$hashtype" == "sha512" ]; then
		$ECHO "Unsupported hashtype passed: $hashtype, not supported by DSA"
		exit 1
	    fi
	    $OPENSSL_CMD dsaparam -out $DSA_PARAMS_FILE $key_size 2> /dev/null
	fi
    else
	$ECHO "Invalid/unsupported key type passed"
	exit 1
    fi

    #Generate key-pair and self-signed switch certificate
    $ECHO -n "Generating ... ..."
    if [ "$keytype" == "rsa" ]; then
        $OPENSSL_CMD req -nodes -x509 -config $EMBEDDED_OPENSSL_CONF -newkey rsa:$key_size -keyout $PVT_KEY_FILE -out $SWITCH_CERT -days $days -$hashtype -subj "/C=$COUNTRY/ST=$STATE/L=$LOCALITY/O=$ORGANIZATION/OU=$ORGANIZATION_UNIT/CN=$COMMON_NAME" 2> /dev/null
    else
        $OPENSSL_CMD req -nodes -x509 -config $EMBEDDED_OPENSSL_CONF -newkey dsa:$DSA_PARAMS_FILE -keyout $PVT_KEY_FILE -out $SWITCH_CERT -days $days -$hashtype -subj "/C=$COUNTRY/ST=$STATE/L=$LOCALITY/O=$ORGANIZATION/OU=$ORGANIZATION_UNIT/CN=$COMMON_NAME" 2> /dev/null
    fi

    chmod 400 $PVT_KEY_FILE

    $CP $SWITCH_CERT $CERT_DIR
    config save $CERT_DIR/$SWITCH_CERT
    config save $CERT_DIR
    config set $CERTCONFIG 5 $SWITCH_CERT
    config set $HTTPCONFIG 1 1
    config set http.ssl.enabled 1 1
    config update
    $WEBDHANDLER $HTTPCONFIG:1

    ret=$?
    if [ $ret -ne 1 ]; then
        cd /; $RM -rf $TEMP_CERTGEN_PATH 
    else
        $RM $CERT_DIR/*
		$CP $TEMP_CERTGEN_PATH/$BACKUP_CERTS/* $CERT_DIR  2> /dev/null
		$WEBDHANDLER $HTTPCONFIG:1
        cd /; $RM -rf $TEMP_CERTGEN_PATH
		$ECHO -n "HTTPS enable failed with self-signed cert, Reverting to old configuration"
        exit 1
    fi

    $AUDIT_NOTIFY "$CERT_GEN" "SW" "$certtype" "$key_size" "$keytype" "$hashtype" "$years"
	fqdn_set
    return 0
}

#
#
# 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"
	$ECHO "      genkey [-nowarn] [-keysize <1024|2048|4096|8192>]"
    $ECHO "      delkey [-nowarn] [-all]"
    $ECHO "      gencsr [-hash <sha1 | sha256>] [-country <2 letter country name>]"
	$ECHO "             [-state <state>] [-locality <locality>] [-org <organization>]"
	$ECHO "             [-orgunit <organization unit>] [-cn <common name>]"
    $ECHO "      delcsr [-nowarn]"
    $ECHO "      showcsr"
    $ECHO "      generate"
	$ECHO "              -fcap -keysize <1024|2048> -hash <sha1|sha256> [-nowarn]:  generate key & CSR"
	$ECHO "              -commoncert -keysize <1024|2048> -hash <sha1|sha256> [-nowarn]:  generate key & CSR"
	$ECHO "              -https -keysize <1024|2048|4096|8192> -hash <sha1|sha256|sha512>"
	$ECHO "              -type <rsa|dsa> -years <x>] [-nowarn]:  generate self-signed certificate"
    $ECHO "      delete [-ldapcacert [<certificate name>] | -syslogcacert [<certificate name>] |"
	$ECHO "              -fcapcacert | -fcapswcert | -fcapall | -commoncertall |"
    $ECHO "              <certificate name>] [-nowarn]"
    $ECHO "      export [-ldapcacert [-certname <certificate name>] | -syslogcacert [-certname <certificate name>] |"
	$ECHO "              -fcapswcert | -fcapswcsr | -fcapcacert | -commonswcert | -commonswcsr | -commoncacert ]"
    $ECHO "             [-protocol  SCP] [-ipaddr <IP address>]"
    $ECHO "             [-remotedir <remote directory>] [-login <login name>] [-password <password>]"
    $ECHO "      import [-ldapcacert | -syslogcacert | -fcapswcert | -fcapcacert | -config <cacert |"
	$ECHO "              swcert [-enable https]> | -commonswcert | -commoncacert ]"
    $ECHO "              -protocol SCP] [-ipaddr <IP address>] [-remotedir <remote directory>]"
    $ECHO "             [-certname <certificate name>] [-login <login name>] [-password <password>]"
    $ECHO "      show   [-ldapcacert] |  [-syslogcacert] | [-fcapall] | [-fcapswcert] | [-commoncertall] | [<file name>]"
    $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 | $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 | $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	
}

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 1 ]; 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
}

printError() {
    IFS_=${IFS}; IFS=$':'
    for error in $output;do
        :
    done
    $ECHO "Error: $error" | $AWK '{gsub("OK", "");print}'
    IFS=${IFS}
}

#
# 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@,@@'`
	checkFipsMode
	fips_mode=$?
	`$CONFIGSHOW_CMD | $GREP 'cfgload.secure' | $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

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

		elif [ $syslogCaCert -eq 1 ];then
			certpkey="BRCD_SYSLOG_1"
 			if [ ! -e "$SYSLOGCA_DIR" ]; then
 	    		mkdir -p $SYSLOGCA_DIR
 			fi
 			cd $SYSLOGCA_DIR
#
#			Multiple syslog ca certificate in not supported
#
#			if [ ! -z "$ipAddr" ]; then
#				SYSLOG_CACERT_FILE="$ipAddr.pem"
#			fi
#			if [ -f $SYSLOGCA_DIR/$SYSLOG_LINK_HASH ] && [ -s $SYSLOGCA_DIR/$SYSLOG_LINK_HASH ]; then
#				certIndex=`$CAT $SYSLOGCA_DIR/$SYSLOG_LINK_HASH | $GREP $PEM_SUFFIX | $WC -l | tr -d ' '`
#				certIndex=`expr $certIndex + 1`
#			fi
#			certpkey="BRCD_SYSLOG_"$certIndex
		elif [ $fcapCaCert -eq 1 ];then
			if [ ! -e "$FCAP_DIR" ]; then
				mkdir -p $FCAP_DIR
			fi
			cd $FCAP_DIR
			certpkey="BRCD_FCAP_CA"

		elif [ $fcapSwCert -eq 1 ]; then 
			if [ ! -e "$FCAP_DIR" ]; then
				mkdir -p $FCAP_DIR
			fi
			cd $FCAP_DIR
			CertConfExist=0
			 certpkey="BRCD_FCAP_SW"
			# 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=`$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/$SYSLOG_CACERT_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/$SYSLOG_CACERT_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 [ ! -s $SYSLOGCA_DIR/$SYSLOG_CACERT_FILE ]; then
                    /usr/bin/scp -q -oStrictHostKeyChecking=no \
                        $userName@\[$ipAddr\]:$remoteDir/$certFileName $SYSLOGCA_DIR/$SYSLOG_CACERT_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 -f $LDAP_DIR/$userInput 2> /dev/null
				exit 1
				fi
				if [ -f $LDAP_DIR/$userInput.der ]; then
					$RM -f $LDAP_DIR/$userInput.der 2> /dev/null
				fi
				$CAT $LDAP_DIR/$userInput >  $LDAP_DIR/$TEMP_CACERT
			fi

            output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $LDAP_DIR/$TEMP_CACERT $LDAP_DIR/$TEMP_CACERT 2> /dev/null`
            check=`$ECHO "$output" | $AWK ' {print $2} '`
            if [ "$check" != "OK" ] ; then
    	        printError
				$RM -f $LDAP_DIR/$TEMP_CACERT 2> /dev/null
				if [ "$userInput" != "swLdapca.pem" ]; then
					$RM -f $LDAP_DIR/$userInput 2> /dev/null
				fi
				$ECHO "Import failed"
				exit 1
			fi

			# Certificate compliance with FIPs mode
			checkForFIPsCompl $LDAP_DIR/$TEMP_CACERT
			if [ $? != 0 ]; then
				$ECHO "Operation cancelled."
				$RM -f $LDAP_DIR/$TEMP_CACERT 2> /dev/null
				if [ "$userInput" != "swLdapca.pem" ]; then
					$RM -f $LDAP_DIR/$userInput 2> /dev/null
				fi
				exit 1
			fi
			$CAT $LDAP_DIR/$TEMP_CACERT >> $LDAP_DIR/$LDAP_CACERT_FILE
			$RM -f $LDAP_DIR/$TEMP_CACERT 2> /dev/null
			# 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 -f $LDAP_DIR/$userInput 2> /dev/null
			fi
			config save $LDAP_DIR/$LDAP_CACERT_FILE

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

        elif [ $syslogCaCert -eq 1 ]; then
            output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $SYSLOGCA_DIR/$SYSLOG_CACERT_FILE $SYSLOGCA_DIR/$SYSLOG_CACERT_FILE 2> /dev/null`
            check=`$ECHO "$output" | $AWK ' {print $2} '`
            if [ "$check" != "OK" ] ; then
                printError
				$RM -f $SYSLOGCA_DIR/$SYSLOG_CACERT_FILE 2> /dev/null
				$ECHO "Import failed"
				exit 1
			fi
            # User has imported Syslog CA certificate with .pem extension
            hashval=`$OPENSSL_CMD x509 -noout -hash -in $SYSLOG_CACERT_FILE`
            /bin/ln -sf  $SYSLOGCA_DIR/$SYSLOG_CACERT_FILE $SYSLOGCA_DIR/$hashval.0
            $ECHO "$SYSLOGCA_DIR/$SYSLOG_CACERT_FILE $SYSLOGCA_DIR/$hashval.0" >> $SYSLOGCA_DIR/$SYSLOG_LINK_HASH
            /fabos/cliexec/config save $SYSLOGCA_DIR/$SYSLOG_CACERT_FILE
            /fabos/cliexec/config save $SYSLOGCA_DIR/$SYSLOGCA_DIR/$SYSLOG_LINK_HASH
			/fabos/cliexec/config save $SYSLOGCA_DIR
            $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 [ -s $FCAP_DIR/$FCAP_CACERT_FILE ]; 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
								printError
								$RM $FCAP_DIR/$userInput
								$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE
								$ECHO "Import failed"
								exit 1
							fi
						else
							printError
							$RM $FCAP_DIR/$userInput
							$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE
							$ECHO "Import failed"
							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"

		    setDefaultContext
		    VID=$?

			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.
			if [ ! -s $FCAP_DIR/$FCAP_CACERT_FILE ]; then
                $ECHO "Please import CA certificate before importing switch certificate."
				$ECHO
                $RM $FCAP_DIR/$userInput
                exit 1
			fi

 			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
                printError
                $ECHO "Please import CA certificate or check the validity before importing switch certificate."
				$ECHO
				$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
		

		    setDefaultContext
		    VID=$?
	
			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

			if [ $certConfig -eq 1 ]; then
				if [ $swCert -eq 1 ]; then
		            setDefaultContext
        		    VID=$?

                    httpsCaCert=`config get $ROOTCERTCONFIG 5`

		            if [ $VID != -1 ];then
        		        setcontext $VID
		            fi

                    if [ "$httpsCaCert" == "none" ] || [ ! -s $CERT_DIR/$httpsCaCert ]; then
                        $ECHO "Please import CA certificate before importing switch certificate."
                        $RM $CERT_DIR/$userInput
                        exit 1
                    else
                        output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $CERT_DIR/$httpsCaCert $CERT_DIR/$userInput 2> /dev/null`
                        check=`$ECHO "$output" | $AWK ' {print $2} '`
                        if [ "$check" != "OK" ]; then
                            printError
                            $RM $CERT_DIR/$userInput
							$ECHO "Import failed"
                            exit 1
                        fi
                    fi
				else
                    output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $CERT_DIR/$userInput $CERT_DIR/$userInput 2> /dev/null`
                    check=`$ECHO "$output" | $AWK ' {print $2} '`
                    if [ "$check" != "OK" ]; then
                        printError
                        $RM $CERT_DIR/$userInput
						$ECHO "Import failed"
                        exit 1
                    fi
				fi
                # Certificate compliance wimh FIPs mode
                checkForFIPsCompl $CERT_DIR/$userInput
                if [ $? != 0 ]; then
                    $ECHO "Operation cancelled."
                    $RM $CERT_DIR/$userInput
                    exit 1
                fi
			fi

			#Used for configuring HTTPS
			httpsCertName="$userInput"

		    setDefaultContext
		    VID=$?

			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" "$certpkey"

	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=$SYSLOG_CACERT_FILE
            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

		    setDefaultContext
		    VID=$?

			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 DCHPv6 IP
        if [ $switchType == $chassisName ] ; then
            ipv6addr=`$ipAddrShowCmd | $SED -n -e 's/chassis\(.*\)dhcpv6 //p'`
        else
            ipv6addr=`$ipAddrShowCmd | $SED -n -e 's/\(.*\)dhcpv6 //p'`
        fi

        # If we can't get DHCPv6, get the stateless IPv6 address
        if [ "$ipv6addr" == "" ] ; then # get stateless ipv6
            if [ $switchType == $chassisName ] ; then
                ipv6addr=`$ipAddrShowCmd | $SED -n -e 's/chassis\(.*\)stateless //p'`
            else
                ipv6addr=`$ipAddrShowCmd | $SED -n -e 's/\(.*\)stateless //p'`
            fi
        fi # get stateless ipv6

        # 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
echo "secCertUtil CLI is deprecated. Use secCertMgmt for Certificate related operations."
exit 0
# 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"
			checkFipsMode
			retVal=$?
	    		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 "Warning: Key-pair generation is CPU intensive and can cause high CPU usage"
		$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

	# 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
	    httpsSwCert=`config get $CERTCONFIG 5`
    	httpsCaCert=`config get $ROOTCERTCONFIG 5`

	    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
				certname=`/bin/basename $i`
				certKey=""

                if [ "$httpsSwCert" == "$certname" ]; then
                    certKey="BRCD_HTTPS_SW"
                elif [ "$httpsCaCert" == "$certname" ]; then
                    certKey="BRCD_HTTPS_CA"
                fi

                $AUDIT_NOTIFY "$CERT_DELE" "$certname" "$certKey"
			fi
		fi
	    done
	fi

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

	#
	# 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 or 4096 or 8192]: "
		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"
	checkFipsMode
	retVal=$?
	if [ "$retVal" == 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 ] && [ "$key_size" != 4096 ] && [ "$key_size" != 8192 ]
	then
		$ECHO Unsupported key size: "$key_size"
		exit 1
	fi

	$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
		if [ $? -ne 0 ]; then
			$RM -f $PVT_KEY_FILE 2> /dev/null
			$ECHO "Failed to generate key pair."
			exit 1
		fi	
	else
		$OPENSSL_CMD dsaparam -genkey -out "$PVT_KEY_FILE" \
			-rand /usr/bin/openssl:/usr/bin/ssh \ 
			$DSA_PARAM_FILE 2> /dev/null
	fi
		chmod 400 $PVT_KEY_FILE	

	if [ $? -eq 0 ]; then

	    setDefaultContext
    	VID=$?

		# 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 -e "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
		checkFipsMode
		if [ $? -eq 1 ]; 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
	certpkey=""
	`$CONFIGSHOW_CMD | $GREP 'security.policymode' | $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
					certpkey="BRCD_HTTPS_SW"
				elif [ "${cmdargs[count]}" == "cacert" ]; then
					caCert=1
					certpkey="BRCD_HTTPS_CA"
				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
		checkFipsMode
		if [ $? -eq 1 ]; 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

 	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
		caCert=1
		certpkey=""
		httpsCertName="$CA_CERT"
   		cp $FCAP_DIR/$FCAP_CACERT_FILE $CERT_DIR/$CA_CERT
		config save $CERT_DIR
		$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr" "$certpkey"
		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
		swCert=1
		certpkey=""
		httpsCertName="$SWITCH_CERT"
      	$CAT $FCAP_DIR/$FCAP_TOUCH_FILE > $CERT_DIR/$SWITCH_CERT
 		config save $CERT_DIR 
		$RM -rf $FCAP_DIR/$certFileName
		$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr" "$certpkey"
		fqdn_set
	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
    	getSwichId "logical"
	    VID=$?
        config set $configToUpdate 5 $httpsCertName 
		config update
        if [ $VID != -1 ];then
			setcontext $VID
        fi
        $ECHO "Certificate file in configuration has been updated."
    fi

    if [ $enableHttps -eq 1 ]
    then
        getSwichId "logical"
        VID=$?
        config set http.ssl.enabled 1 1
		config update

        if [ $VID != -1 ];then
            setcontext $VID
        fi
        $WEBDHANDLER $HTTPCONFIG:1
        $ECHO "Secure http has been enabled."
    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
		$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
        checkFipsMode
		if [ $? -eq 1 ]; then
			$ECHO "Common Cert related operations are not allowed in FIPS Mode."
			exit 1
		fi

        #Show FCAP
		fcap=1
		showFiles "common certificate"

       #Show HTTPS
    	setDefaultContext
	    VID=$?
	
		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"

		#f set, bash allows patterns which match no files to expand to a null string, rather than themselves
		shopt -s nullglob
		files=($SYSLOGCA_DIR/*.pem)
		if [ ${#files[@]} -gt 0 ]; then
			syslogcaCert="Exist"
		else
			syslogcaCert="Empty"
		fi
		shopt -u nullglob    # reset

		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "SYSLOG" "$syslogcaCert" "NA" \
			$SYSLOGCA_DIR "NA" "NA" "NA"

	    setDefaultContext
    	VID=$?

		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

        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

		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" $cacert $httpsCert \
				$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

        if [ $VID != -1 ];then
            setcontext $VID
        fi
	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
	certpkey=""

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

		"$LDAPCACERT_OPT" )
			ldapCaCert=1
			certpkey="BRCD_LDAP_1"
			;;

        "$SYSLOGCACERT_OPT" )
            syslogCaCert=1
			certpkey="BRCD_SYSLOG_1"
            ;;

 		"$FCAPSWCERT_OPT" )
			fcapSwCert=1
			certpkey="BRCD_FCAP_SW"
			;;

		"$FCAPCACERT_OPT" )
			fcapCaCert=1
			certpkey="BRCD_FCAP_CA"
			;;

		"$FCAP" )
			fcap=1
			certpkey="FCAP"
			;;

		"$COMMONCERTALL" )
			commoncert=1
			;;

		"NULL" )
			break
			;;

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

		esac
	    count=`expr $count + 1`
	done

	if [ $commoncert -eq 1 ];then
		checkFipsMode
		if [ $? -eq 1 ]; 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
			file=$SYSLOG_CACERT_FILE
			if [ ! -s "$SYSLOGCA_DIR/$file" ]; then
				$ECHO "Syslog CA certificate does not exist"
				exit 1
			fi
        fi

#        if [ -e "$SYSLOGCA_DIR/$file" ] || [ "$file" = "-all" ];then
		if [ -s "$SYSLOGCA_DIR/$file" ]; 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"
		certpkey="FCAP"
		confirmDelete $FCAP_ALL_FILE $file
	    if [ $? -eq 0 ]; then
    	    $AUDIT_NOTIFY "$CERT_DELE" "$file" "$certpkey"
	    fi

		cleanUpHTTPS

		config set $ROOTCERTCONFIG 5 none

		exit 0
	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" "$certpkey"
	fi
;;
 
$CERT_GEN )
	# verify input arguments before processing
	fcap=0
	response="no"
	file=
	key_size=0
    keytype="no"
    hashtype="no"
    years=0
    flag=0
    count=0
    commoncert=0
    https=0
    genswcert=0
    allopt=0
    showusage=0
    certtype=""

    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" )
    	   	response="yes"
        	;;

        "$HTTPS" )
	        https=1
    	    certtype="https"
        	;;

        "$FCAPS" )
	        fcap=1
    	    certtype="fcap"
        	;;

        "$COMMONCERT" )
	        commoncert=1
    	    certtype="commoncert"
        	;;

        "$HASHTYPE" )
	        count=`expr $count + 1`
    	    hashtype=${cmdargs[count]}
        	;;

        "$KEYSIZE" )
			count=`expr $count + 1`
			key_size=${cmdargs[count]}
			;;

        "$KEYTYPE" )
	        count=`expr $count + 1`
    	    keytype=${cmdargs[count]}
        	;;

        "$YEARS" )
	        count=`expr $count + 1`
    	    years=${cmdargs[count]}
			if [ $years -lt 0 ] || [ $years -gt 50 ]; then
				$ECHO "Valid input for years is 1to50"
	            usage
	            exit 1
			fi
        	;;

		"NULL" )
			break
			;;

		* )
 			usage
			exit 1
			;;
	    esac
	    count=`expr $count + 1`
	done

    if [ "$keytype" != "no" ] || [ $years -ne 0 ]; then
    	genswcert=1
    fi

    if [ "$keytype" != "no" ] && [ "$hashtype" != "no" ] && [ $years -ne 0 ] && [ $key_size -ne 0 ]; then
        allopt=1
    fi
	
 	if [ $commoncert -eq 1 ];then
		checkFipsMode
		if [ $? -eq 1 ]; then
			$ECHO "Common Cert related operations are not allowed in FIPS Mode."
		exit 1
		fi
	fi

    if [ $fcap -eq 0 ] && [ $commoncert -eq 0 ] && [ $https -eq 0 ]; then
    	showusage=1
    elif [ $genswcert -eq 1 ] && [ $https -eq 0 ]; then
        showusage=1
    elif [ $https -eq 1 ] && [ $allopt -eq 0 ]; then
        showusage=1
    fi

    if [ $showusage -eq 1 ]; then
   		usage
	    exit 1
    fi

    if [ $genswcert -eq 1 ]; then
    	GenerateSelfSignedCerts
        if [ $? -eq 0 ]; then
            $ECHO "Generated self-signed $certtype certificate successfully."
		fi
    exit 0
	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 "Warning: Key-pair generation is CPU intensive and can cause high CPU usage"
		$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	

    if [ "$hashtype" == "no" ]; then
        $ECHO -n "Select the hashtype [sha1 or sha256]: "
        read hashtype
    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"
	checkFipsMode
    retVal=$?
    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 for $certtype: "$key_size"
		exit 1
	fi

	if [ "$hashtype" != "sha1" ] && [ "$hashtype" != "sha256" ]; then
		$ECHO Unsupported hashtype for $certtype: "$hashtype"
		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 $hashtype
		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 (hashtype:$hashtype)" "fcap"
		fi
	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
			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

