#!/bin/sh
#
#    Copyright (c) 2016 Brocade Communications Systems, Inc.
#    All rights reserved.
#
#    File name:   seccertmgmt
#    Module name: fabos/src/security/seccertmgmt.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"
DOMAINNAME="/bin/domainname"
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
MD5SUM=/usr/bin/md5sum
# OPENSSL_CMD_NO_FIPS is required as OPENSSL_CMD changes to fipsopenssl in FIPS mode.
FIPS_CONF_FILE=/etc/fabos/fabos.0.conf
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"
GEN_AUTH=/fabos/libexec/gen_auth
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
MGMT_DIR=$ROOT_DIR/certs/mgmt
TMP_DIR=/tmp
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_inf
REST_CSR_INPUT_INFO=/tmp/csr_gen_input_inf
DSA_PARAMS_FILE=dsaparam.pem

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

SWITCH_CERT_DESC_NAME="switch certificate"
SWITCH_CACERT_DESC_NAME="CA certificate"

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

# Sub-options for "delkey"
NOWARN_OPT="-f"

# 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
WEBLNOTIFY=/fabos/libexec/weblnotify
HTTPCONFIG=http.ssl.enabled
CERTCONFIG=ssl.certfile
ROOTCERTCONFIG=ssl.root.certfile
DEFAULTROOTCERTCONFIG="none"
HTTPFQDN="http.fqdn"
HTTPFQD="http.domn"
fqdnval=""

# LDAP definitions
TEMP_CACERT="tempca.pem"
LDAP_DIR=$ROOT_DIR/certs/ldap
LDAP_CERT_FILE="ldap ca certificate"
LDAP_CACERT_FILE="swLdapca.pem"
LDAP_CLIENT_CACERT_FILE="swLdapClntca.pem"
LDAP_SWCERT_FILE="swLdapcert.pem"
TEMP_CERT="tempcert.pem"
SW_CSR_SUFFIX=".csr"

RADIUS_DIR=$ROOT_DIR/certs/radius
RADIUS_CACERT_FILE="swRadca.pem"
RADIUS_CLIENT_CACERT_FILE="swRadClntca.pem"
RADIUS_SWCERT_FILE="swRadcert.pem"

# SYSLOG CA definitions
SYSLOG_DIR=/etc/syslog-ng/ca.d
SYSLOG_DIR_MNT=/mnt/etc/syslog-ng/ca.d
SYSLOG_CERT_FILE="Syslog CA certificate"
SYSLOG_CACERT_FILE="ca.pem"
SYSLOG_CLIENT_CACERT_FILE="Clntca.pem"
SYSLOG_SWCERT_FILE="syslogswcert.pem"
SYSLOG_LINK_HASH="syslog_link_hash"
TEMP_SYSLOG_LINK_HASH="temp_syslog_link_hash"

# ASC CA definitions
ASC="asc"
ASC_DIR=/etc/fabos/certs/asc
ASC_DIR_MNT=/mnt/etc/fabos/certs/asc
ASC_DIR_CACERT_CURL=/etc/fabos/certs/asc/curl
ASC_DIR_CACERT_CURL_MNT=/mnt/etc/fabos/certs/asc/curl
ASC_CERT_FILE="Asc CA certificate"
ASC_CACERT_FILE="cacert.pem"
ASC_CACERT_ACT_FILE="ca-active.pem"
TEMP_ASCCERT_FILE="temp_asc_cert.pem"

# KAFKA CA definitions
KAFKA_DIR=$ROOT_DIR/certs/kafka
KAFKA_CERT_FILE="Kafka CA certificate"
KAFKA_CACERT_FILE="swKafkaca.pem"

# Common cert definations
COMMONCERT_PRVT_KEY="pvt_key"
COMMONCERT_CA_FILE="commonCA.pem"
COMMON_SW_CSR_SUFFIX="commonSw.csr"
COMMONCERT_CA_SUFFIX="commonRootCA.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"
RADIUS="radius"
LDAP="ldap"
SYSLOG="syslog"
KAFKA="kafka"
EXTN="extn"
ASC="asc"
MGMT="mgmtip"
CASOURCE="-ca"
CLIENT="-client"
SERVER="-server"
CERTSOURCE="-cert"
CSRSOURCE="-csr"
KEYTYPE="-type"
KEYSIZE="-keysize"
HASHTYPE="-hash"
YEARS="-years"
TAG="-keypair_tag"


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`

# EXTN definitions
EXTN="extn"
ECDSA_KEY=ecdsa
EXTN_DIR=$ROOT_DIR/certs/extn
ALL_OPT="all"
CACERT_OPT="-ca"
CERT_OPT="-cert"
CSR_OPT="-csr"
CAfile_OPT="-cacert"
EXTNLOCALSWCERT="localswcert"
EXTNLOCALCACERT="localcacert"
EXTNLOCALSWCSR="localswcsr"
EXTNREMOTESWCERT="remoteswcert"
EXTNREMOTECACERT="remotecacert"
EXTNALLCERT="all"
EXTN_LOCAL_SWCERT_FILE_EXT="swcert.local"
EXTN_LOCAL_SWCSR_FILE_EXT="swcsr.local"
EXTN_REMOTE_SWCERT_FILE_EXT="swcert.remote"
EXTN_CACERT_FILE_EXT="cacert"
EXTN_ALL_FILE=EXTN-Files
EXTN_SW_CERT_FILE=EXTN-SW-Certificate
EXTN_CA_CERT_FILE=EXTN-CA-Certificate
EXTN_CSR_FILE=EXTN-CSR
ESMCMD=/fabos/cliexec/esmcmd
EXTN_V3EXT_FILE=/tmp/extfile
# Considering keypair per tunnel, max tunnels/slot is 20,
# max slots/chassis is 4, max tunnels=max_tunnels_per_Slot*max slots
# = 80, rounding to the nearest
EXTN_MAX_PVTKEYFILE=128

# FCAP definations
FCAP_ROOT_CER_SUFFIX=.rootcrt
FCAP_CERT_KEY_SUFFIX=.key
SWCSR_OPT="-swcsr"
ALL="-all"
HEX_DUMP="-hexdump"
DEFAULT="default"
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
X509_VALIDATION_KEY="X509v3.validation"
EXTRACTEDCA="/tmp/extractedCA"
restCaller=`echo $GEPS_APP_NAME`

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

#used this for audit
AUDIT_NOTIFY=/fabos/libexec/seccert_notify
deleteStatus=
delall="none"
commoncert=0

#Delete error codes
DELETE_SUCCESS=0
DEL_ERR_OP_FAILED=1
DEL_ERR_SYSLOG_SECURE=2
DEL_ERR_SYSLOG_FAILED=3
DEL_ERR_NO_CSR=4
DEL_ERR_NO_CERT=255


#Commoncert error codes
COMMONCERT_NO_SERVER=19
#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`
	if [[ ! -z $restCaller ]] && [[ "$SW_CONTEXT_RC" == -1 ]]; then
		if [ ! -e /fabos/link_sbin/lscfg_test ]
		then
			/bin/ln -s /fabos/cliexec/lscfg_util /fabos/link_sbin/lscfg_test 2> /dev/null        
		fi
	        eval $(lscfg_test --switch $1)
 		if [ -e /fabos/link_sbin/lscfg_test ]
		then
		        $RM /fabos/link_sbin/lscfg_test
		fi
	else
		eval $(lscfg_util --switch $1)
	fi
    else
        eval $(lscfg_util --chassis)
    fi
	export ROLE_ID=root
} 

secOpConfirm() {
	$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."
		return 1 
    fi

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

	return 0
}

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 CURRENT_VF | cut -d"=" -f2`
		fi
	fi
	
 	if [ -e /fabos/link_sbin/lscfg_test ]
	then
	        $RM /fabos/link_sbin/lscfg_test
	fi
	
	return $VID
}
# Check if the given file can be removed
# If the file is required by Encryption, then we don't
# want to remove it
# Args - <filename> <delflag>
check_for_removal()
{
	delflag=$2
	if [ $delflag -eq 1 ]; then
		# -all option specified, truncate encryption certs as well
		return 0;
	fi

	flname=$1

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

	if [[ "$delflag" == "noca" ]]; then
		httpsCaCert=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`
		ca_name=`/bin/basename $flname`
		if [ $httpsCaCert == $ca_name ]; then
			return 1
		fi
		return 0
	fi


	#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

	#Skip all soft links
	if [ -L $flname ]; then 
		return 1
	fi

	return 0
}

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

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

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

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

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

		if [ ! -e "./$userInput" ]; then
			$ECHO "Specified $inputtype $expreq 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
}

cleanUpRadius() {
	certpresent=0
	if [ ! -z $1 ]; then
		if [ -s $RADIUS_DIR/$RADIUS_CACERT_FILE ]; then
			deleteFiles 0 $RADIUS_DIR/$RADIUS_CACERT_FILE
#			$AUDIT_NOTIFY "$CERT_DELE" "$RADIUS_CACERT_FILE" "BRCD_RADIUS_CA"
			$AUDIT_NOTIFY "$CERT_DELE" "$RADIUS_CACERT_FILE" ""
		fi
        if [ -s $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE ]; then
            deleteFiles 0 $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE
#           $AUDIT_NOTIFY "$CERT_DELE" "$RADIUS_CLIENT_CACERT_FILE" "BRCD_RADIUS_CA"
            $AUDIT_NOTIFY "$CERT_DELE" "$RADIUS_CLIENT_CACERT_FILE" ""
        fi
	fi
	
	if [ -s $RADIUS_DIR/$RADIUS_SWCERT_FILE ]; then
		certpresent=1
	fi
	deleteFiles 0 $RADIUS_DIR/$PVT_KEY $RADIUS_DIR/$switchIp$SW_CSR_SUFFIX $RADIUS_DIR/$RADIUS_SWCERT_FILE
	/fabos/cliexec/config save $RADIUS_DIR
	if [ $certpresent -eq 1 ]; then
#		$AUDIT_NOTIFY "$CERT_DELE" "$RADIUS_SWCERT_FILE" "BRCD_RADIUS_SW"
		$AUDIT_NOTIFY "$CERT_DELE" "$RADIUS_SWCERT_FILE" ""
	fi
}

cleanUpLDAP() {
	certpresent=0
    if [ ! -z $1 ]; then
        if [ -s $LDAP_DIR/$LDAP_CACERT_FILE ]; then
            deleteFiles 0 $LDAP_DIR/$LDAP_CACERT_FILE
			$AUDIT_NOTIFY "$CERT_DELE" "$LDAP_CACERT_FILE" "BRCD_LDAP_CA"
        fi
        if [ -s $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE ]; then
            deleteFiles 0 $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE
            $AUDIT_NOTIFY "$CERT_DELE" "$LDAP_CLIENT_CACERT_FILE" ""
        fi
    fi

    if [ -s $LDAP_DIR/$LDAP_SWCERT_FILE ]; then
        certpresent=1
    fi
	deleteFiles 0 $LDAP_DIR/$PVT_KEY $LDAP_DIR/$switchIp$SW_CSR_SUFFIX $LDAP_DIR/$LDAP_SWCERT_FILE
	/fabos/cliexec/config save $LDAP_DIR
    if [ $certpresent -eq 1 ]; then
#		$AUDIT_NOTIFY "$CERT_DELE" "$LDAP_SWCERT_FILE" "BRCD_LDAP_SW"
		$AUDIT_NOTIFY "$CERT_DELE" "$LDAP_SWCERT_FILE" ""
    fi
}

cleanUpSyslog() {
	capresent=0
	certpresent=0
	if [ ! -z $1 ]; then
		if [ -s $SYSLOG_DIR/$SYSLOG_CACERT_FILE ]; then
			capresent=1
			SYSLOG_LINK=`$CAT $SYSLOG_DIR/$SYSLOG_LINK_HASH | $GREP "$2" | $AWK ' { print $2 }'`
            		deleteFiles 0 $SYSLOG_DIR/$SYSLOG_CACERT_FILE
            		# Cleanup the SYSLOGCA_DIR from stale symbolic links
            		$RM -rf $SYSLOG_LINK $SYSLOG_DIR/$SYSLOG_LINK_HASH 2> /dev/null
            		/fabos/cliexec/config save $SYSLOG_LINK
            		/fabos/cliexec/config save $SYSLOG_DIR/$SYSLOG_LINK_HASH
            		$AUDIT_NOTIFY "$CERT_DELE" "$SYSLOG_CACERT_FILE" "BRCD_SYSLOG_CA"
        	fi
		if [ -s $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE ]; then
			deleteFiles 0 $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE
			$AUDIT_NOTIFY "$CERT_DELE" "$SYSLOG_CLIENT_CACERT_FILE" ""
		fi
	fi

	if [ -s $SYSLOG_DIR/$SYSLOG_SWCERT_FILE ]; then
        	certpresent=1
	fi

	deleteFiles 0  $SYSLOG_DIR/$PVT_KEY $SYSLOG_DIR/$switchIp$SW_CSR_SUFFIX $SYSLOG_DIR/$SYSLOG_SWCERT_FILE

	#To delete additional Ca certificates present or the softlink refrences in active or mnt partition, which are imported previously using seccertutil CLI
	# defect FOS-802456
	if [ ! -z $1 ]; then
		#files=`$LS $SYSLOG_DIR/* 2> /dev/null`
		#for i in $files
		#do
			#$RM -f $i 2> /dev/null
			#/fabos/cliexec/config save $i
		#done
		$RM -rf $SYSLOG_DIR/* 2> /dev/null
		$RM -rf $SYSLOG_DIR_MNT/* 2> /dev/null
		
	fi

	/fabos/cliexec/config save $SYSLOG_DIR

	if [ $certpresent -eq 1 ]; then
#		$AUDIT_NOTIFY "$CERT_DELE" "$SYSLOG_SWCERT_FILE" "BRCD_SYSLOG_SW"
		$AUDIT_NOTIFY "$CERT_DELE" "$SYSLOG_SWCERT_FILE" ""
		return 0
	fi

	if [ $capresent -eq 1 ]; then
		return 0
	fi

	return 1
}

cleanUpFCAP() {
	switch_cert_name="NONE"
	zeroizeFiles $FCAP_DIR/$FCAP_SWCSR_FILE $FCAP_DIR/$FCAP_SWCERT_FILE $FCAP_DIR/$FCAP_SWPRVKEY_FILE $FCAP_DIR/$FCAP_SWPPH_FILE $FCAP_DIR/$FCAP_TOUCH_FILE
	updateFCAPConfigFile "SWITCH_CERT_NAME:$switch_cert_name"
	/fabos/cliexec/config save $FCAP_DIR/$FCAP_CERT_CONF_FILE
	/fabos/cliexec/config save $FCAP_DIR
	return 0
}

cleanUpHTTPS() {
    setDefaultContext
    VID=$?

	httpsSwCert=`/fabos/cliexec/config get $CERTCONFIG 5`
	httpsCaCert=`/fabos/cliexec/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
                                if [[ ! -z $restCaller ]] && [[ "$1" == "deletehttps" ]]; then
					# Exit for REST alone.
					# HTTPS cert creation not supported, if already 
					# a cert exists
					exit 19
				fi
				deleteFiles 0 $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
		for i in $file
		do
		if [ -s "$i" ]; then
			check_for_removal $i $delall 2> /dev/null
			if [ $? -eq 0 ]; then
				deleteFiles 0 $i
				filename=`/bin/basename $i`
				$AUDIT_NOTIFY "$CERT_DEL_CSR" "$filename"
			fi
		fi
		done
	fi

	if [ -s "$PVT_KEY_FILE" ]; then
		deleteFiles 0 $PVT_KEY_FILE
		$AUDIT_NOTIFY "$CERT_DEL_KEY" "$file"
	fi

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

	resetSSLState
	/fabos/cliexec/config save $CERT_DIR

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

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

generateCsrExtn() {
	
	pvtkeyfile="${EXTN_DIR}/${keypair}.${PVT_KEY}"
   csrfile="${EXTN_DIR}/${keypair}${CSR_SUFFIX}"

	if [ "$key_size" == "P384" ]; then
		curve=secp384r1
	else
		$ECHO "Unsupported/invalid curve for $certtype: $key_size"
		exit 1
	fi

	num_pvtkeyfile=`find ${EXTN_DIR} -name "*.${PVT_KEY}" | wc -l 2> /dev/null`
	if  [ $num_pvtkeyfile -gt $EXTN_MAX_PVTKEYFILE ]; then
		$ECHO "Maximum limit of extn keypair : $EXTN_MAX_PVTKEYFILE"
		exit 1
	fi

	if [ -f "$pvtkeyfile" ]; then
		$ECHO "Keypair $keypair already exists, please delete and retry."
		exit 1
	fi

 	$OPENSSL_CMD ecparam -genkey -name $curve -out "$pvtkeyfile" > /dev/null
	if [ $? != 0 ] ; then
		$ECHO "Key generation failed."
		deleteFiles 0 "$pvtkeyfile"
		exit 1
	else
		$ECHO "Key generation success."
	fi

	# create the temporary config 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"
			$ECHO "Deleting key `basename $pvtkeyfile`"
			deleteFiles 0 "$pvtkeyfile"
			exit 1
		fi
	fi

	$ECHO "Input CSR details:"

	trap 'cleanupOnTrap' 2 3

	#Prompt for required fields for generating a CSR.
	promptCSRInfo

	if [ $? != 0 ]; then
		$ECHO "CSR Generation failed".
		$ECHO "Deleting key `basename $pvtkeyfile`"	
		deleteFiles 0 "$pvtkeyfile"
		exit 1
	fi

	$ECHO "Generating CSR, file name is: `basename $csrfile`"
	$OPENSSL_CMD req -$hashtype -new -key "$pvtkeyfile" \
		-out "$csrfile"  \
		-config $CSR_GEN_INFO 2> /dev/null

	#
	# Tell PDM to synchronize
	#
	if [ $? -eq 0 ]; then
		chmod 400 "$pvtkeyfile" 2> /dev/null
		/fabos/cliexec/config save $EXTN_DIR		
		$AUDIT_NOTIFY "$CERT_GEN" "`basename $pvtkeyfile` (keysize:$key_size), `basename $csrfile` (hashtype:$hashtype) (keypair_tag:$keypair)" "$certtype"
		$ECHO Done.
	else
		$ECHO "CSR Generation failed".
		$ECHO "Deleting key `basename $pvtkeyfile`"
		deleteFiles 0 "$pvtkeyfile"
	fi

	#Delete config file
	if [ -e "$CSR_GEN_INFO" ]; then
  		$RM -f $CSR_GEN_INFO > /dev/null
	fi

 	return 0
}

cleanupOnTrap() {
	if [ -f $CSR_GEN_INFO ]; then
		rm $CSR_GEN_INFO 2> /dev/null
	fi

	if [ $extn -eq 1 ]; then
		$ECHO
		$ECHO "Deleting key `basename $pvtkeyfile`"
		deleteFiles 0 "$pvtkeyfile"	
	elif [ "$certtype" != "$FCAPS" ]; then
		if [ -f $curdir/$certkey ]; then
			zeroizeFiles "$curdir/$certkey"
		fi
	fi

	trap 2 3
	exit 1
}
# This function extracts individual CA cert from CA chain
# and checks for Basic constraints.  Returns 0 on success
checkBasicConstraints()
{
	caTrue=0
	awk 'BEGIN {c=0;} /BEGIN CERT/{c++;} { print > "/tmp/extractedCA." c ".pem"; ;} ' < $1
        list=`$LS $EXTRACTEDCA*$PEM_SUFFIX 2> /dev/null`
        if [ ! -z "$list" ]; then
            for caCert in $list
            do
                if [ -s "$caCert" ]; then
			$OPENSSL_CMD_NO_FIPS x509 -in  $caCert -text -noout | $GREP -i CA:true > /dev/null 2>&1
			if [ $? -ne 0 ]; then
				caTrue=1
			fi
                        $RM $caCert
                fi
            done
        fi
	return $caTrue
}

generateCsrClient() {
	csrfile="$switchIp$SW_CSR_SUFFIX"
	certkey="$PVT_KEY"
	curdir=""

    case $certtype in
	"$FCAPS" )

		certkey="$FCAP_SWPRVKEY_FILE"
		csrfile="$FCAP_SWCSR_FILE"
		curdir=$FCAP_DIR
		cleanUpFCAP
		syncUpFCAP

		if [ $commoncert -eq 1 ]; then
			delall="noca"
			cleanUpHTTPS
		fi
		;;

	"$RADIUS" )
            if [ ! -e "$RADIUS_DIR" ]; then
                mkdir -p $RADIUS_DIR
            fi
			curdir=$RADIUS_DIR

			cleanUpRadius
			;;

		"$LDAP" )
			curdir=$LDAP_DIR
			cleanUpLDAP
			;;

		"$SYSLOG" )
			curdir=$SYSLOG_DIR
			cleanUpSyslog
			;;

        "$HTTPS" )
			curdir=$CERT_DIR
			delall="noca"
            cleanUpHTTPS

		    setDefaultContext
		    VID=$?

            /fabos/cliexec/config set $ROOTCERTCONFIG 5 none
			/fabos/cliexec/config update

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

		"$EXTN" )
			cd $EXTN_DIR
			cleanUpExtn
		    if [ $? != 0 ] ; then
				$ECHO "Operation Failed."
				return 1
			fi
			;;
	esac

	if [ "$certtype" != "$FCAPS" ]; then
		# Generate Key-pair
	    if [ "$keytype" == "$RSA_KEY" ]; then
    	    $OPENSSL_CMD genrsa -out "$curdir/$certkey" $key_size 2> /dev/null
	    else
			$OPENSSL_CMD dsaparam -out $DSA_PARAMS_FILE $key_size 2> /dev/null
        	$OPENSSL_CMD gendsa -out "$curdir/$certkey" -rand /usr/bin/openssl:/usr/bin/ssh \
            	$DSA_PARAMS_FILE 2> /dev/null
			$RM $DSA_PARAMS_FILE 2> /dev/null
	    fi

    	if [ $? != 0 ]; then
        	if [ "$keytype" == "$RSA_KEY" ]; then
        		$RM -f $curdir/$certkey 2> /dev/null
        	fi
        	$ECHO "CSR generate failed"
	        exit 1
    	fi
	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
			if [ "$certtype" != "$FCAPS" ]; then
				zeroizeFiles "$curdir/$certkey"
			fi
			$ECHO "CSR generate failed"
            exit 1
        fi
    fi

	trap 'cleanupOnTrap' 2 3

    #
    # if we are here, the temp file is created, prompt the user for data
    #
	    promptCSRInfo

    if [ $? != 0 ]; then
		if [ "$certtype" != "$FCAPS" ]; then
			zeroizeFiles "$curdir/$certkey"
		fi
        $ECHO "CSR generate failed"
        exit 1
    fi

	if [ "$certtype" != "$FCAPS" ]; then
	    $ECHO "Generating CSR, file name is: $csrfile"
    	$OPENSSL_CMD req -$hashtype -new -key "$curdir/$certkey" \
        	-out "$curdir/$csrfile" -config $CSR_GEN_INFO 2> /dev/null

	    if [ $? != 0 ]; then
			zeroizeFiles "$curdir/$certkey"
			$RM -f $CSR_GEN_INFO > /dev/null
			$ECHO "CSR generate failed"
	        exit 1
    	fi
    	chmod 400 $curdir/$certkey 2> /dev/null
	    /fabos/cliexec/config save $curdir/$certkey
    	/fabos/cliexec/config save $curdir/$csrfile
	    /fabos/cliexec/config save $curdir
	if [ "$certtype" == "$HTTPS" ]; then
		fqdn_set
	fi
	else
		confirmGenerate $key_size $hashtype
        if [ $? -eq 0 ]; then
		 	syncUpFCAP
			if [ $? != 0 ] ; then
        		$RM -f $CSR_GEN_INFO > /dev/null
           		$ECHO "Operation Failed."
            	exit 1
        	fi
		fi
        if [ $commoncert -eq 0 ] && [ -e $curdir/$COMMONCERT_PRVT_KEY ]; then
            $RM -rf $curdir/$COMMONCERT_PRVT_KEY
        fi
	fi

    if [ -e "$CSR_GEN_INFO" ]; then
        $RM -f $CSR_GEN_INFO > /dev/null
	fi
    if [ $commoncert -eq 1 ]; then
        mv $curdir/$COMMONCERT_PRVT_KEY $PVT_KEY_FILE
        cp $curdir/$csrfile $CERT_DIR/$switchIp$CSR_SUFFIX
        chmod 400 $PVT_KEY_FILE 2> /dev/null
        /fabos/cliexec/config save $PVT_KEY_FILE
        /fabos/cliexec/config save $CERT_DIR/$switchIp$CSR_SUFFIX
        /fabos/cliexec/config save $CERT_DIR
        $AUDIT_NOTIFY "$CERT_GEN" "$certkey (keysize:$key_size), $csrfile (hashtype:$hashtype)" "commoncert"
		fqdn_set
    else
        $AUDIT_NOTIFY "$CERT_GEN" "$certkey (keysize:$key_size), $csrfile (hashtype:$hashtype)" "$certtype"
    fi
    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	
}

csrNameValidate() {
	
	userInput=$1
	cLen=`expr length $userInput`
	if  [ "$cLen" -lt 5 ]; then
		$ECHO "Invalid name: CSR file name must have" \
			".csr suffix"
		exit 1
	fi

	let dotIndex="$cLen"-3
	fileSuffix=`expr substr $userInput $dotIndex $cLen`
	if [ "$fileSuffix" != "$CSR_SUFFIX" ]; then
		$ECHO "Invalid name: CSR file name must have" \
			".csr suffix"
		exit 1
	fi

	no_of_dots=`echo $userInput | $AWK -F '.' '{ print NF }'`
	if [ "$no_of_dots" -gt 2 ]; then
		$ECHO "Invalid name: CSR file name must not have" \
		"multiple dots"
		exit 1
	fi	

	$ECHO $userInput | $GREP -v "[^a-zA-Z0-9~@%_+:.-]" > /dev/null 2>&1
	if [ ! $? -eq 0 ]; then
		$ECHO "Invalid name: CSR file name must not have" \
		"unsupported characters, supported characters are [a-zA-Z0-9~@%_+:-]"
		exit 1
	fi

}

certNameValidate() {

	# put global certificate file name
	userInput=$1
	cLen=`expr length $userInput`
	if  [ "$cLen" -lt 5 ]; then
		if [ "$inputtype" == "$FCAPS" ] || [[ "$inputtype" == "$HTTPS" && "$impreq" == "CA" ]]; 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 [ "$inputtype" == "$FCAPS" ] || [[ "$inputtype" == "$HTTPS" && "$impreq" == "CA" ]]; 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 [ "$inputtype" == "$EXTN" ]; then
			no_of_dots=`echo $userInput | $AWK -F '.' '{ print NF }'`
			if [ "$no_of_dots" -gt 2 ]; then
				$ECHO "Invalid name: Certificate file name must not have" \
				"multiple dots"
				exit 1
			fi	
			$ECHO $userInput | $GREP -v "[^a-zA-Z0-9~@%_+:.-]" > /dev/null 2>&1
			if [ ! $? -eq 0 ]; then
				$ECHO "Invalid name: Certificate file name must not have" \
				"unsupported characters, supported characters are [a-zA-Z0-9~@%_+:-]"
				exit 1
			fi
		fi
	fi
}

compare_fcap_https_checksum() {
		fcap_file=$1
		inputfile=$2
		if [ -s $fcap_file ]; then
			fcapchksum=`$OPENSSL_CMD_NO_FIPS x509 -in $fcap_file | $OPENSSL_CMD_NO_FIPS md5`
		else
			$ECHO "$COMMONCERT $filetag doesnot exist";$ECHO
			if [[ ! -z $restCaller ]]; then
				exit $DEL_ERR_NO_CERT
			fi
			exit 0
		fi
		if [ -s $CERT_DIR/$inputfile ]; then
			httpschksum=`$OPENSSL_CMD_NO_FIPS x509 -in  $CERT_DIR/$inputfile | $OPENSSL_CMD_NO_FIPS md5`
		else
			$ECHO "$COMMONCERT $filetag doesnot exist";$ECHO
			if [[ ! -z $restCaller ]]; then
 				exit $DEL_ERR_NO_CERT
			fi
			exit 0
		fi

		if [ "$fcapchksum" != "$httpschksum" ]; then
			$ECHO "$COMMONCERT $filetag doesnot exist";$ECHO
			if [[ ! -z $restCaller ]]; then
				exit $DEL_ERR_NO_CERT
			fi
			exit 0
		fi
}

##Check if commoncert exists or not
check_delete_commoncert() {
		delreq=$1
		if [ "$delreq" == "CA" -o "$delreq" == "ALL" ]; then
			filetag="$SWITCH_CACERT_DESC_NAME"
			fcap_file=$FCAP_DIR/$FCAP_CACERT_FILE
			setDefaultContext
			VID=$?
			inputfile=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`
			# Change the VF back to current context.
			if [ $VID != -1 ];then
				setcontext $VID
			fi
			compare_fcap_https_checksum $fcap_file $inputfile
		fi
		if [ "$delreq" == "CERT" -o "$delreq" == "ALL" ]; then
			filetag="$SWITCH_CERT_DESC_NAME"
			fcap_file=$FCAP_DIR/$FCAP_SWCERT_FILE
			setDefaultContext
			VID=$?
			inputfile=`/fabos/cliexec/config get $CERTCONFIG 5`
			# Change the VF back to current context.
			if [ $VID != -1 ];then
				setcontext $VID
			fi
			compare_fcap_https_checksum $fcap_file $inputfile
		fi
		if [ "$delreq" == "CSR" -o "$delreq" == "ALL" ]; then
			filetag="csr"
			inputfile=$switchIp$CSR_SUFFIX

			if [ -s $FCAP_DIR/$FCAP_SWCSR_FILE ] && [ -s $CERT_DIR/$inputfile ]; then
				fcapchksum=`$OPENSSL_CMD_NO_FIPS req -in $FCAP_DIR/$FCAP_SWCSR_FILE | $OPENSSL_CMD_NO_FIPS md5`
				httpschksum=`$OPENSSL_CMD_NO_FIPS req -in $CERT_DIR/$inputfile | $OPENSSL_CMD_NO_FIPS md5`
			else
				$ECHO "$COMMONCERT $filetag does not exist";$ECHO
				if [[ ! -z $restCaller ]]; then
					exit $DEL_ERR_NO_CSR
				fi
				exit 0
			fi

			if [ "$fcapchksum" != "$httpschksum" ]; then
				$ECHO "$COMMONCERT $filetag does not exist";$ECHO
				if [[ ! -z $restCaller ]]; then
					exit $DEL_ERR_NO_CSR
				fi
				exit 0
			fi
		fi
}

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

#
# is_extn_platform
#
# Check if extension feature is supported on this
# platform (supported on Skybolt, Harpoon, Allegiance
# and Awing)
#
is_extn_platform()
{
	# Determine the system platform identifier.
	SWBD=$(sin | swbd 2> /dev/null)
	case ${SWBD##SWBD} in

		'148' | '178' | '165' | '166' )
			return 0
			;;
		*)
			return 1
			;;

	esac
}

# function to check if the next input argument is a key or a value
# Input parameters:
#  $1 - Type of command (import, export, show or delete, etc,)
#  $2 - The next argument to be processed by the calling function
# Return value:
#  1 - if the input argument ($2) is a key
#  0 - if the input argument ($2) is a value
isArgToken() {
	if [ "$1" == "$CERT_IMPORT" ]; then
		if [ "$2" == "$CERTSOURCE" ] || [ "$2" == "$CASOURCE" ]\
			|| [ "$2" == "$TAG" ] || [ "$2" == "-protocol" ] || [ "$2" == "-ipaddr" ]\
			|| [ "$2" == "-remotedir" ] || [ "$2" == "-certname" ]\
			|| [ "$2" == "-login" ] || [ "$2" == "-password" ]\
			|| [ "$2" == "$CAfile_OPT" ]; then
			return 1
		fi
	elif [ "$1" == "$CERT_EXPORT" ]; then
		if [ "$2" == "$CERTSOURCE" ] || [ "$2" == "$CASOURCE" ] || [ "$2" == "$CSRSOURCE" ]\
			|| [ "$2" == "$TAG" ] || [ "$2" == "-protocol" ] || [ "$2" == "-ipaddr" ]\
			|| [ "$2" == "-remotedir" ] || [ "$2" == "-certname" ]\
			|| [ "$2" == "-login" ] || [ "$2" == "-password" ]; then
			return 1
		fi
	elif [ "$1" == "$CERT_SHOW" ]; then
		if [ "$2" == "$CERTSOURCE" ] || [ "$2" == "$CASOURCE" ] || [ "$2" == "$CSRSOURCE" ]\
			|| [ "$2" == "$TAG" ] || [ "$2" == "$ALL" ]; then
			return 1
		fi
	elif [ "$1" == "$CERT_DELE" ]; then
		if [ "$2" == "$CERTSOURCE" ] || [ "$2" == "$CASOURCE" ] ||\
			[ "$2" == "$CSRSOURCE" ] || [ "$2" == "$ALL" ] ||\
			[ "$2" == "$HTTP" ] || [ "$2" == "$FCAPS" ] || \
			[ "$2" == "$COMMONCERT" ] || [ "$2" == "$RADIUS" ] ||\
			[ "$2" == "$LDAP" ] || [ "$2" == "$SYSLOG" ] || [ "$2" == "$EXTN" ]\
			|| [ "$2" == "$TAG" ] || [ "$2" == "$ALL_OPT" ] ||\
			[ "$2" == "$DEFAULT" ] || [ "$2" == "$NOWARN_OPT" ]; then
			return 1
		fi
	elif [ "$1" == "$CERT_GEN" ]; then
		if [ "$2" == "$CERTSOURCE" ] || [ "$2" == "$CSRSOURCE" ]\
			|| [ "$2" == "$KEYTYPE" ] || [ "$2" == "$KEYSIZE" ]\
			|| [ "$2" == "$HASHTYPE" ] || [ "$2" == "$TAG" ]; then
			return 1
		fi
	fi
	return 0
}

# routine to validate a certificate being imported against the private key of the switch.
certPvtKeyValidate() {
	invalSwCert=0
	pvtkey=$PVT_KEY
	csrFile=$switchIp$CSR_SUFFIX

	if [ "$inputtype" == "$FCAPS" ]; then
		pvtkey="$FCAP_SWPRVKEY_FILE"
		csrFile=$FCAP_SWCSR_FILE
	elif [ "$inputtype" == "$EXTN" ]; then
		pvtkey="${keypair}.${PVT_KEY}"
		csrFile="${keypair}${CSR_SUFFIX}"		
	fi

	if [ "$inputtype" == "$EXTN" ]; then
        if [ ! -f $pvtkey ]; then
            $ECHO "Private key file corresponding to keypair_tag $keypair does not exist on the switch. Please generate private key.Aborting $1 operation.."
            if [ -e ${EXTN_DIR}/${certpkey} ]; then
                $RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
            fi
            exit 1
        fi
    else
		if [ ! -f $pvtkey ]; then
			$ECHO "The $inputtype key does not exist on the switch. Please generate $inputtype key and csr.Aborting $1 operation.."
        	if [ -e ./$userInput ]; then
	            	$RM ./$userInput
		        fi
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit 11
			fi
		fi
	fi

	if [ $commoncert -eq 1 ]; then
		if [ ! -f $PVT_KEY_FILE ]; then
			$ECHO "The $inputtype key does not exist on the switch. Please generate $inputtype keys and csr.Aborting $1 operation.."
			if [ -e $CERT_DIR/$userInput ]; then
				$RM $CERT_DIR/$userInput
			fi
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit 11
			fi
		fi	
	fi

	if [ "$inputtype" == "$FCAPS" ]; then
			$OPENSSL_CMD x509 -in ./$userInput -inform PEM -outform DER -out ./$userInput.der > /dev/null 2>&1
			if [ $? != 0 ]; then
				$ECHO "Bad format certificate. Exiting.."
				$RM ./$userInput
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit 12
				fi
			fi
			if [ -f ./$userInput.der ]; then
				$RM ./$userInput.der
			fi
			certificate=./$userInput
	elif [ "$inputtype" == "$EXTN" ]; then
        #validate the file format
        $OPENSSL_CMD x509 -in ${EXTN_DIR}/${certpkey} > /dev/null 2>&1
        if [ $? != 0 ]; then
            $ECHO "Bad format certificate ${EXTN_DIR}/${certpkey}. Exiting.."
            $RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
            exit 1
        fi
        certificate="${EXTN_DIR}/${certpkey}"
	else
		if [ "$fileSuffix" == "$CER_SUFFIX" ] || [ "$fileSuffix" == "$CRT_SUFFIX" ]; then
			$OPENSSL_CMD x509 -in $userInput -inform DER -outform PEM -out ./$userInput.pem > /dev/null 2>&1
			if [ $? != 0 ]; then
				$ECHO "Bad format certificate. Exiting.."
				$RM ./$userInput
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit 12
				fi
			fi
			certificate=./$userInput.pem
		else
			#validate the file format
			$OPENSSL_CMD x509 -in $userInput -inform PEM -outform DER -out ./$userInput.der > /dev/null 2>&1
			if [ $? != 0 ]; then
				$ECHO "Bad format certificate. Exiting.."
				$RM ./$userInput
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit 12
				fi
			fi
			if [ -f ./$userInput.der ]; then
				$RM ./$userInput.der
			fi
			certificate=./$userInput
		fi
	fi

	if [ "$inputtype" == "$EXTN" ]; then
        if [ ! -f "$csrFile" ]; then
            $ECHO "CSR corresponding to $keypair does not exist on the switch. Please generate CSR. Aborting $1 operation.."
            if [ -e ${EXTN_DIR}/${certpkey} ]; then
                $RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
            fi
            exit 1
        fi
    elif [ "$inputtype" != "$FCAPS" ]; then
		rsakey=`$GREP -c "BEGIN RSA PRIVATE KEY" $pvtkey`
		if [ $rsakey -gt 0 ]; then
			pvt_key_type="rsa"
		else
			pvt_key_type="dsa"
		fi
		pvtkeyhash=`$OPENSSL_CMD $pvt_key_type -noout -modulus -in $pvtkey  2> /dev/null | $CUT -d "=" -f 2 | \
						$OPENSSL_CMD_NO_FIPS md5`
	fi

	certkeyhash=`$OPENSSL_CMD x509 -noout -modulus -in $certificate  2> /dev/null  | $CUT -d "=" -f 2 | $OPENSSL_CMD_NO_FIPS md5`

	# delete the temporary .pem created for validating .cer/.crt certificates
	if [ -f ./$userInput.pem ]; then
		$RM ./$userInput.pem
		certificate=./$userInput
	fi

	# Comparicon against pvt key is needed for swcert
	if [ "$inputtype" == "$EXTN" ]; then
        pub_from_cert=`$OPENSSL_CMD x509 -in $certificate -pubkey -noout`
        pub_from_priv=`$OPENSSL_CMD_NO_FIPS pkey -in ${EXTN_DIR}/${pvtkey} -pubout`
        if [ "$pub_from_cert" != "$pub_from_priv" ]; then
            invalSwCert=1
        fi
    elif [ "$inputtype" != "$FCAPS" ] && [ "$certkeyhash" != "$pvtkeyhash" ]; then
		invalSwCert=1
	fi

	if [ $invalSwCert -eq 1 ]; then
		$ECHO "Invalid switch certificate.Exiting"
		$RM $certificate
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit 13
		fi
	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() {
    setDefaultContext
    VID=$?

	configCert=`/fabos/cliexec/config get $CERTCONFIG 5`
	caCert=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`

	if [ "$1" == "$configCert" ]; then
		certpkey="BRCD_HTTPS_SW"
	elif [ "$1" == "$caCert" ]; then
		certpkey="BRCD_HTTPS_CA"
	else
		if [ $VID != -1 ]; then
			setcontext $VID
		fi
		return 0
	fi

	httpSEnabled=`/fabos/cliexec/config get $HTTPCONFIG 1`

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

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

	return 0
}

extn_cert_del_prepare() {

	extn_delete_prompt="\nWARNING!!!\n"

	if [ "$inputtype" == "$EXTN" ]; then
		if [ "$delreq" == "CA" ]; then
			extn_files_to_delete=${EXTN_DIR}/${filename}.${EXTN_CACERT_FILE_EXT}${PEM_SUFFIX}
			if [ ! -e $extn_files_to_delete ]; then
				$ECHO "CA Cert ${filename} does not exist"
				exit 1
			fi
			$ECHO -e "${extn_delete_prompt}Deletion of CA certificate will fail the runtime validation of its signed switch certificates if any," \
				"and this will cause the authentication failure of the associated IKE sessions."
			extn_delete_prompt="About to delete CA certificate $filename"
			#Should we delete the hash file for CA Certs too?
			extn_files_to_delete="$extn_files_to_delete ${EXTN_DIR}/${filename}.${EXTN_CACERT_FILE_EXT}${PEM_SUFFIX}.hash"
			extn_audit_notify_arg2=$filename
		elif [ "$delreq" == "CERT" ]; then
			if [ "$filename" != "" ]; then
				#User has provided a switch certificate name
				#find out if thats a local switch certificate or a remote switch certificate
				#first check if this is a remote certificate
				extn_remote_sw_cert=`$LS ${EXTN_DIR}/${filename}.nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
				extn_local_sw_cert=`$LS ${EXTN_DIR}/${filename}.*.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
				if [ "$extn_remote_sw_cert" != "" ] ; then
					if [ "$extn_local_sw_cert" != "" ] ; then
						#there is a local-sw cert & a remot-sw-cert with the same name.
						#Throw an error so that user doesn't accidently delete a wrong cert
						#get the keypair_tag value
						keypair=`$ECHO $extn_local_sw_cert | awk -F '.' ' { print $(NF-3) }'`
						$ECHO -e "\nALERT! Two certificates exist with the same name $filename."
						$ECHO "The local switch certificate exists with keypair_tag ${keypair}"
						$ECHO "To delete the local switch certificate, use the \"-keypair_tag\" option."
						$ECHO ""
						if [ "$response" == "no" ]; then	
							$ECHO "Do you want to delete the remote switch certificate ${filename}:"
							secOpConfirm
							if [ $? -ne 0 ]; then
								exit 1
							fi
						else
							$ECHO "Deleting the remote switch certificate ${filename}"
						fi
					fi
					#Deleting the remote switch certificate
					$ESMCMD op validate remote cert $extn_remote_sw_cert | grep "Object in use" > /dev/null 2>&1
					if [ $? -eq 0 ]; then
						$ECHO "${filename} is in use by extension ipsec_policy"
						exit 1
					fi
					extn_files_to_delete="$extn_remote_sw_cert ${extn_remote_sw_cert}.hash"
					extn_delete_prompt="${extn_delete_prompt}About to delete switch certificate $filename"
					extn_audit_notify_arg2=$filename
				else
					if [ "$extn_local_sw_cert" == "" ]; then
						$ECHO "Extension switch certificate $filename does not exist."
						exit 1
					fi

					#Delete local switch certificate
					keypair=`$ECHO $extn_local_sw_cert | awk -F '.' ' { print $(NF-3) }'`
					extn_csr_file=$EXTN_DIR/${keypair}${CSR_SUFFIX}
					extn_pvt_key_file=$EXTN_DIR/${keypair}.${PVT_KEY}
					$ESMCMD op validate local cert $extn_local_sw_cert | grep "Object in use" > /dev/null 2>&1
					if [ $? -eq 0 ]; then
						$ECHO "${filename} is in use by extension ipsec_policy"
						exit 1
					fi
					extn_files_to_delete="$extn_local_sw_cert ${extn_local_sw_cert}.hash $extn_csr_file $extn_pvt_key_file"
					extn_delete_prompt="${extn_delete_prompt}About to delete switch certificate ${filename} associated with keypair_tag ${keypair} and associated CSR file if any"
					extn_audit_notify_arg2=$filename
					extn_audit_notify_arg3=$keypair
				fi
			else
				#User provided keypair-tag option. Hence this is a local sw cert
				extn_local_sw_cert=`$LS ${EXTN_DIR}/*.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
				if [ "$extn_local_sw_cert" == "" ]; then
					$ECHO "Switch certificate for keypair-tag ${keypair} does not exist."
					exit 1
				fi

				#Check if this certificate is in use by ipsec_policy
				$ESMCMD op validate local cert $extn_local_sw_cert | grep "Object in use" > /dev/null 2>&1
				if [ $? -ne 1 ]; then
					$ECHO "${keypair} is in use by extension ipsec_policy"
					exit 1
				fi

				#delete pvt_key file too
				extn_csr_file=$EXTN_DIR/${keypair}${CSR_SUFFIX}
				extn_pvt_key_file=${EXTN_DIR}/${keypair}.${PVT_KEY}
				filename=`basename $extn_local_sw_cert | sed -e "s/".${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}"//"`
				extn_files_to_delete="$extn_local_sw_cert ${extn_local_sw_cert}.hash $extn_csr_file $extn_pvt_key_file"
				extn_delete_prompt="${extn_delete_prompt}About to delete switch certificate $filename associated with keypair_tag-${keypair} and associated CSR file if any"
				extn_audit_notify_arg2=$filename
				extn_audit_notify_arg3=$keypair
			fi

		elif [ "$delreq" == "CSR" ]; then
			extn_files_to_delete=${EXTN_DIR}/${keypair}${CSR_SUFFIX}
			if [ ! -e $extn_files_to_delete ]; then
				$ECHO "CSR for the keypair-tag ${keypair} does not exist"
				exit 1
			fi
			#if a certificate does not exist for this keypair, then delete the
			#private key file too.
			extn_tmp_file=`$LS ${EXTN_DIR}/*.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
			if [ "$extn_tmp_file" == "" ]; then
				#Switch cert for this keypair does not exist. Hence delete
				#pvt_key file too
				extn_pvt_key_file=${EXTN_DIR}/${keypair}.${PVT_KEY}
				if [ -e $extn_pvt_key_file ]; then
					extn_files_to_delete="$extn_files_to_delete $extn_pvt_key_file"
				fi
			fi
			extn_delete_prompt="${extn_delete_prompt}About to delete CSR for keypair_tag-{$keypair}"
			extn_audit_notify_arg2=${keypair}${CSR_SUFFIX}
		elif [ "$delreq" == "ALL" ] ; then
			extn_remote_sw_cert=`$LS ${EXTN_DIR}/*.nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
			extn_local_sw_cert=`$LS ${EXTN_DIR}/*.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
			for i in $extn_local_sw_cert ; do
				#Check if this certificate is in use by ipsec_policy
				$ESMCMD op validate local cert $i | grep "Object in use" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					keypair=`$ECHO $i | awk -F '.' ' { print $(NF-3) }'`
					filename=`basename $i | sed -e "s/".${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}"//"`
					$ECHO "Extension Switch certificate ${filename} is in use by extension ipsec_policy"
					$ECHO "Aborting..."
					exit 1
				fi
			done
			for i in $extn_remote_sw_cert ; do
				#Check if this certificate is in use by ipsec_policy
				$ESMCMD op validate remote cert $i | grep "Object in use" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					filename=`basename $i | sed -e "s/".nohash.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}"//"`
					$ECHO "Extension Switch certificate ${filename} is in use by extension ipsec_policy"
					$ECHO "Aborting..."
					exit 1
				fi
			done
			extn_files_to_delete=`$LS ${EXTN_DIR}/* 2> /dev/null`
			extn_delete_prompt="${extn_delete_prompt}About to delete ALL Extension switch certificates, CA certificates & CSR"
			extn_audit_notify_arg2="EXTN_ALL"
		fi
	elif [ "$inputtype" == "$ALL_OPT" ];then
		if [ "$delreq" == "CA" ]; then
			extn_files_to_delete=`$LS ${EXTN_DIR}/*.${EXTN_CACERT_FILE_EXT}${PEM_SUFFIX} ${EXTN_DIR}/*.${EXTN_CACERT_FILE_EXT}${PEM_SUFFIX}.hash 2> /dev/null`
		elif [ "$delreq" == "CERT" ]; then
			extn_remote_sw_cert=`$LS ${EXTN_DIR}/*.nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
			extn_local_sw_cert=`$LS ${EXTN_DIR}/*.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
			for i in $extn_local_sw_cert ; do
				#Check if this certificate is in use by ipsec_policy
				$ESMCMD op validate local cert $i | grep "Object in use" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					keypair=`$ECHO $i | awk -F '.' ' { print $(NF-3) }'`
					filename=`basename $i | sed -e "s/".${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}"//"`
					$ECHO "Extension Switch certificate ${filename} is in use by extension ipsec_policy"
					$ECHO "Aborting..."
					exit 1
				fi
				extn_csr_file="${extn_csr_file} $EXTN_DIR/${keypair}${CSR_SUFFIX}"
				extn_pvt_key_file="${extn_pvt_key_file} ${EXTN_DIR}/${keypair}.${PVT_KEY}"
			done
			for i in $extn_remote_sw_cert ; do
				#Check if this certificate is in use by ipsec_policy
				$ESMCMD op validate remote cert $i | grep "Object in use" > /dev/null 2>&1
				if [ $? -eq 0 ]; then
					filename=`basename $i | sed -e "s/".nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}"//"`
					$ECHO "Extension Switch certificate ${filename} is in use by extension ipsec_policy"
					$ECHO "Aborting..."
					exit 1
				fi
			done
			extn_hash_files=`$LS ${EXTN_DIR}/*.nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}.hash ${EXTN_DIR}/*.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}.hash 2> /dev/null`
			extn_files_to_delete="$extn_remote_sw_cert $extn_local_sw_cert $extn_csr_file $extn_pvt_key_file $extn_hash_files"
		elif [ "$delreq" == "CSR" ]; then
			extn_csr_file=$EXTN_DIR/*${CSR_SUFFIX}
			for i in $extn_csr_file ; do
				#For all the CSR files in the system, delete the private_key file only if
				#the switch certificate is not present
				keypair=`basename $i | sed -e "s/"${CSR_SUFFIX}"//"`
				extn_tmp_file=`$LS ${EXTN_DIR}/*.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
				if [ "$extn_tmp_file" == "" ]; then
					#Switch cert for this keypair does not exist. Hence delete
					#pvt_key file too
					extn_pvt_key_file=${EXTN_DIR}/${keypair}.${PVT_KEY}
					if [ -e $extn_pvt_key_file ]; then
						extn_files_to_delete="$extn_files_to_delete $extn_pvt_key_file"
					fi
				fi
			done
				extn_files_to_delete="$extn_files_to_delete $extn_csr_file"
		fi
	fi
}

deleteExtensionCerts() {
	delreq=$1
	inputtype=$2

	extn_files_to_delete=""
	extn_cert_del_prepare
	
	$ECHO "Deleting Extension related files..."
	deleteFiles 0 $extn_files_to_delete
	#The caller of this function will do AUDIT_NOTIFY
}

zeroizeFiles() {
    for i in $* ; do
        if [ -e $i ]; then
            size=`/bin/ls -la $i | $AWK ' { print $5 } '`
            /bin/dd if=/dev/zero of=$i bs=1 count=$size 2> /dev/null
			$CAT /dev/null > $i
			/fabos/cliexec/config save $i
		fi
	done
}

#
# Zeroize & delete the files. Based on the input ($1), 
# do a read back after zeroize (before deleting
# arguments:
# arg1:
#	0 - don't read back the file before delete.
#	1 - Readback the file after zeroize & then delete.
#
# arg2: list of all the files to be deleted (separated by space).
#		The file names should be with absolute path
#
deleteFiles() {
	readback=$1

	shift
	if [ $readback -eq 0 ]; then
		#no need to read back
		for i in $* ; do
			if [ -e "$i" ]; then
				size=`/bin/ls -la $i | $AWK ' { print $5 } '`
				/bin/dd if=/dev/zero of=$i bs=1 count=$size 2> /dev/null
				$RM -rf $i > /dev/null
				/fabos/cliexec/config save $i
			fi
		done
	else
		for i in $* ; do
			size=`/bin/ls -la $i | $AWK ' { print $5 } '`
			/bin/dd if=/dev/zero of=$i bs=1 count=$size 2> /dev/null
			#TODO: Read back the file before delete
			$RM -rf $i > /dev/null
			/fabos/cliexec/config save $i
		done
	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
	syslogsecure=0

	if [ "$response" == "no" ]; then
    	$ECHO "WARNING!!!"
	    $ECHO
		if [ "$delreq" == "CA" ] || [ "$delreq" == "CERT" ]; then
			$ECHO "About to delete $inputtype $optag file(s)"
		    if [ $commoncert -eq 1 ]; then
        		$ECHO "This will disable secure protocols such as HTTPS and"
	        	$ECHO "ISLs may be segmented during next E-port(s) bring-up"
			fi
		elif [ "$delreq" == "ALL" ]; then
			if [ "$inputtype" == "$DEFAULT" ]; then
				$ECHO "About to delete all certificate files and configurations"
			else
				$ECHO "About to delete all $inputtype certificate files and configurations"
				if [ "$inputtype" == "$HTTPS" ]; then
					$ECHO "This will disable secure protocol HTTPS"
				elif [ "$inputtype" == "$FCAPS" ]; then
					$ECHO "The ISLs may be segmented during next E-port(s) bring-up"
				elif [ $commoncert -eq 1 ]; then
    	            $ECHO "This will disable secure protocols such as HTTPS and"
	                $ECHO "ISLs may be segmented during next E-port(s) bring-up"
				fi
            fi
		fi

	    secOpConfirm

	    if [ $? -eq 1 ]; then
    	    exit $DEL_ERR_OP_FAILED
	    fi
	fi

	if [ "$1" == "$FCAPS" ]; then
		if [ "$delreq" == "CA" ]; then
	        if [ ! -s $FCAP_DIR/$FCAP_CACERT_FILE ]; then
                $ECHO "FCAP CA certificate doesnt exist"
                return 1;
    	    fi

        	updateFCAPConfigFile "ROOT_CA_CERTIFICATES:0"
			zeroizeFiles $FCAP_DIR/$FCAP_CACERT_FILE
			/fabos/cliexec/config save $FCAP_DIR/$FCAP_CERT_CONF_FILE
			/fabos/cliexec/config save $FCAP_DIR
			$AUDIT_NOTIFY "$CERT_DELE" "$FCAP_CACERT_FILE" "BRCD_FCAP_CA"
			isDeleteOk=$DELETE_SUCCESS
		elif [ "$delreq" == "CERT" ]; then
	        if [ ! -s $FCAP_DIR/$FCAP_SWCERT_FILE ]; then
				$ECHO "FCAP switch certificate doesnt exist"
				return 1
	        fi
			zeroizeFiles $FCAP_DIR/$FCAP_SWCERT_FILE $FCAP_DIR/$FCAP_TOUCH_FILE
        	updateFCAPConfigFile "SWITCH_CERT_NAME:None"
	        /fabos/cliexec/config save $FCAP_DIR/$FCAP_CERT_CONF_FILE
			/fabos/cliexec/config save $FCAP_DIR
			$AUDIT_NOTIFY "$CERT_DELE" "$FCAP_SWCERT_FILE" "BRCD_FCAP_SW"
		else
			if [ $debug -eq 1 ]; then
				$ECHO "Removing All FCAP Keys/Certificates"
			fi
	        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
    	    updateFCAPConfigFile "ROOT_CA_CERTIFICATES:0"
        	zeroizeFiles $FCAP_DIR/$FCAP_TOUCH_FILE
    	    syncUpFCAP
        	if [ $VID != -1 ];then
	            setcontext $VID
    	    fi

        	if [ $? != 0 ] ; then
	            $ECHO "Operation Failed."
    	        exit $DEL_ERR_OP_FAILED
        	fi
			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
		fi
		isDeleteOk=$DELETE_SUCCESS
	elif [ "$1" == "$RADIUS" ]; then
        if [ "$delreq" == "CA" ]; then
			if [ "$CAFlag" == "server" ]; then
				inputFile=$RADIUS_CACERT_FILE
			else
				inputFile=$RADIUS_CLIENT_CACERT_FILE
			fi

            if [ ! -s $RADIUS_DIR/$inputFile ]; then
                $ECHO "RADIUS $CAFlag CA certificate doesnt exist"
                return 1;
            fi
            # zeroize before delete
			deleteFiles 0 "$RADIUS_DIR/$inputFile"
			/fabos/cliexec/config save $RADIUS_DIR
#			$AUDIT_NOTIFY "$CERT_DELE" "$inputFile" "BRCD_RADIUS_CA"
			$AUDIT_NOTIFY "$CERT_DELE" "$inputFile" ""
			isDeleteOk=$DELETE_SUCCESS
            return 0
        elif [ "$delreq" == "CERT" ]; then
            if [ ! -s $RADIUS_DIR/$RADIUS_SWCERT_FILE ]; then
                $ECHO "RADIUS switch certificate doesnt exist"
                return 1;
            fi

            # zeroize before delete
			deleteFiles 0 "$RADIUS_DIR/$RADIUS_SWCERT_FILE"
			/fabos/cliexec/config save $RADIUS_DIR
#			$AUDIT_NOTIFY "$CERT_DELE" "$RADIUS_SWCERT_FILE" "BRCD_RADIUS_SW"
			$AUDIT_NOTIFY "$CERT_DELE" "$RADIUS_SWCERT_FILE" ""
			isDeleteOk=$DELETE_SUCCESS
            return 0
        else
			if [ $debug -eq 1 ]; then
				$ECHO "Removing all Radius Keys/Certificates"
			fi
			cleanUpRadius "all"
        fi
	elif [ "$1" == "$LDAP" ]; then
        if [ "$delreq" == "CA" ]; then
			if [ "$CAFlag" == "server" ]; then
				inputFile=$LDAP_CACERT_FILE
			else
				inputFile=$LDAP_CLIENT_CACERT_FILE
			fi

            if [ ! -s $LDAP_DIR/$inputFile ]; then
                $ECHO "LDAP $CAFlag CA certificate doesnt exist"
                return 1;
            fi
            # zeroize before delete
			deleteFiles 0 "$LDAP_DIR/$inputFile"
			/fabos/cliexec/config save $LDAP_DIR
			$AUDIT_NOTIFY "$CERT_DELE" "$inputFile" "BRCD_LDAP_CA"
			isDeleteOk=$DELETE_SUCCESS
            return 0
        elif [ "$delreq" == "CERT" ]; then
            if [ ! -s $LDAP_DIR/$LDAP_SWCERT_FILE ]; then
                $ECHO "LDAP switch certificate doesnt exist"
                return 1;
            fi

            # zeroize before delete
			deleteFiles 0 "$LDAP_DIR/$LDAP_SWCERT_FILE"
			/fabos/cliexec/config save $LDAP_DIR
#			$AUDIT_NOTIFY "$CERT_DELE" "$LDAP_SWCERT_FILE" "BRCD_LDAP_SW"
			$AUDIT_NOTIFY "$CERT_DELE" "$LDAP_SWCERT_FILE" ""
			isDeleteOk=$DELETE_SUCCESS
            return 0
        else
			if [ $debug -eq 1 ]; then
				$ECHO "Removing all LDAP Keys/Certificates"
			fi
			cleanUpLDAP "all"
        fi
	elif [ "$1" == "$SYSLOG" ]; then
        if [ "$delreq" == "CA" ]; then
			if [ "$CAFlag" == "server" ]; then
				syslogsecure=`$CONFIGSHOW_CMD | $GREP 'syslog.IP.secure' | $GREP -c ':1'`
				if [ $syslogsecure -ge 1 ]; then
					$ECHO "Syslog is configured in secure mode, so certificate cannot be deleted. Please remove secure mode configuration for Syslog and try again."
					isDeleteOk=$DEL_ERR_SYSLOG_SECURE
					return 1
				fi
	            		certpkey="BRCD_SYSLOG_1"
				inputFile=$SYSLOG_CACERT_FILE
			else
				inputFile=$SYSLOG_CLIENT_CACERT_FILE
			fi
			if [ ! -s $SYSLOG_DIR/$inputFile ]; then
				$ECHO "Syslog $CAFlag CA certificate does not exist"
				return 1
			fi

			if [ "$CAFlag" != "server" ]; then
				deleteFiles 0 $SYSLOG_DIR/$inputFile
				/fabos/cliexec/config save $SYSLOG_DIR
				$AUDIT_NOTIFY "$CERT_DELE" "$inputFile" "$certpkey"
				isDeleteOk=$DELETE_SUCCESS
				return 0
			else
			    #Get the syslog link file
            	SYSLOG_LINK=`$CAT $SYSLOG_DIR/$SYSLOG_LINK_HASH | $GREP "$2" | $AWK ' { print $2 }'`
				deleteFiles 0 $SYSLOG_DIR/$inputFile
	            # Cleanup the SYSLOGCA_DIR from stale symbolic links
    	        $RM -rf $SYSLOG_LINK $SYSLOG_DIR/$SYSLOG_LINK_HASH 2> /dev/null

        	    if [ $? -ne 0 ];then
            	    	$ECHO "Could not delete Syslog $CAFlag CA certificate"
			isDeleteOk=$DEL_ERR_SYSLOG_FAILED
                	return 1
	            else
    	            /fabos/cliexec/config save $SYSLOG_DIR/$SYSLOG_CACERT_FILE
        	        /fabos/cliexec/config save $SYSLOG_LINK
            	    /fabos/cliexec/config save $SYSLOG_DIR/$SYSLOG_LINK_HASH
					/fabos/cliexec/config save $SYSLOG_DIR
	                /usr/bin/killall -q -s SIGHUP syslog-ng >> /var/log/syslog.log 2>&1
					$AUDIT_NOTIFY "$CERT_DELE" "$inputFile" "$certpkey"
					isDeleteOk=$DELETE_SUCCESS
        	    	return 0
				fi
			fi
        elif [ "$delreq" == "CERT" ]; then
            if [ ! -s $SYSLOG_DIR/$SYSLOG_SWCERT_FILE ]; then
                $ECHO "Syslog switch certificate does not exist"
                return 1
			fi

            # zeroize before delete
			deleteFiles 0 "$SYSLOG_DIR/$SYSLOG_SWCERT_FILE"
			/fabos/cliexec/config save $SYSLOG_DIR
			/usr/bin/killall -q -s SIGHUP syslog-ng >> /var/log/syslog.log 2>&1
#			$AUDIT_NOTIFY "$CERT_DELE" "$SYSLOG_SWCERT_FILE" "BRCD_SYSLOG_SW"
			$AUDIT_NOTIFY "$CERT_DELE" "$SYSLOG_SWCERT_FILE" ""
			isDeleteOk=$DELETE_SUCCESS
            return 0
        else
			if [ $debug -eq 1 ]; then
				$ECHO "Removing all Syslog-ng Keys/Certificates"
			fi
			cleanUpSyslog "all"
			if [ $? -eq 0 ]; then
	            /usr/bin/killall -q -s SIGHUP syslog-ng >> /var/log/syslog.log 2>&1
				return 0
            fi
        fi
	elif [ "$1" == "$HTTPS" ]; then
        if [ "$delreq" == "CA" ]; then
	        setDefaultContext
	        VID=$?
			file=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`
			if [ "$file" == "none" ]; then
				$ECHO "HTTPS CA certificate does not exist"
				return 1
			fi
			deleteFiles 0 $CERT_DIR/$file
			/fabos/cliexec/config set $ROOTCERTCONFIG 5 none
			/fabos/cliexec/config save $CERT_DIR
			/fabos/cliexec/config update
	        # Change the VF back to current context.
        	if [ $VID != -1 ];then
    	        setcontext $VID
	        fi
			$AUDIT_NOTIFY "$CERT_DELE" "$file" "BRCD_HTTPS_CA"
			isDeleteOk=$DELETE_SUCCESS
        elif [ "$delreq" == "CERT" ]; then
            setDefaultContext
            VID=$?
			file=`/fabos/cliexec/config get $CERTCONFIG 5`
            if [ "$file" == "none" ]; then
                $ECHO "HTTPS switch certificate does not exist"
                return 1
            fi
			deleteFiles 0 $CERT_DIR/$file
			delall="noca"
			resetSSLState
            /fabos/cliexec/config save $CERT_DIR
            /fabos/cliexec/config update
            # Change the VF back to current context.
            if [ $VID != -1 ];then
                setcontext $VID
            fi
			$AUDIT_NOTIFY "$CERT_DELE" "$file" "BRCD_HTTPS_SW"
			isDeleteOk=$DELETE_SUCCESS
		else
			if [ $debug -eq 1 ]; then
				$ECHO "Removing all HTTPS Keys/Certificates"
				delall=1
			fi
			cleanUpHTTPS
		fi
	elif [ "$1" == "$MGMT" ]; then
		if [ "$delreq" == "CERT" ]; then
	        if [ -z "$filename" ]; then
    	        readInput "Enter certificate name (must have \".crt\" or \".cer\"  \".pem\" or \".psk\" suffix): "
        	    inputfile=$userInput
            	$ECHO "$inputfile" | $GREP '/' >/dev/null 2>&1
	            if [ "$?" -eq 0 ]; then
    	            $ECHO "Filename cannot be provided with path"
					return 1
    	        fi
        	else
            	inputfile=$filename
       		 fi

        	if [ ! -s $MGMT_DIR/$inputfile ]; then
			if [ ! -s $CERT_DIR/$inputfile ]; then
				$ECHO "Certificate $inputfile does not exist"
    	        $ECHO
				return 1
			fi
	        fi

			#Remove the soft link iin CERT_DIR
			if [ -L $CERT_DIR/$inputfile ]; then
				$RM -rf $CERT_DIR/$inputfile 2> /dev/null
				/fabos/cliexec/config save $CERT_DIR/$inputfile
				/fabos/cliexec/config save $CERT_DIR
			fi

			check_https_files $inputfile
                        https_exist=$?

                        if [ $https_exist -eq 0 ]; then
                                deleteFiles 0 $CERT_DIR/$inputfile
                                /fabos/cliexec/config save $CERT_DIR
                        else
                                $ECHO "Certificate $inputfile does not exist"
                                return 1
                        fi

			deleteFiles 0 $MGMT_DIR/$inputfile
			/fabos/cliexec/config save $MGMT_DIR
			$AUDIT_NOTIFY "$CERT_DELE" "$inputfile" ""
		else
            if [ $debug -eq 1 ]; then
                $ECHO "Removing all Management IP Certificates"
            fi

		    file=`$LS $MGMT_DIR/*$CRT_SUFFIX $MGMT_DIR/*$CER_SUFFIX \
        		$MGMT_DIR/*$PEM_SUFFIX $MGMT_DIR/*$PSK_SUFFIX 2> /dev/null`
		    if [ ! -z "$file" ]; then
	        	for i in $file
		        do
    		    if [ -s "$i" ]; then
               		deleteFiles 0 $i
	                certname=`/bin/basename $i`
					#remove the soft links in CERT_DIR
					if [ -L $CERT_DIR/$certname ]; then
						$RM -rf $CERT_DIR/$certname 2> /dev/null
						/fabos/cliexec/config save $CERT_DIR/$certname
						/fabos/cliexec/config save $CERT_DIR
					fi
       	    	    $AUDIT_NOTIFY "$CERT_DELE" "$certname" ""
	    	    fi
    	    	done
	    	fi
		### Check for certs imported via seccertutil present in CERTDIR/
                 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
                                        certname=`/bin/basename $i`
                                        check_https_files $certname
                                        https_exist=$?

					if [ $https_exist -eq 0 ]; then
                                                deleteFiles 0 $i
                                                $AUDIT_NOTIFY "$CERT_DELE" "$certname" ""
                                        fi
                                fi
                        done
                fi

			/fabos/cliexec/config save $MGMT_DIR
			/fabos/cliexec/config save $CERT_DIR
		fi
	elif [ "$1" == "$KAFKA" ]; then
        #The below function will prepare for delete
		#It will exit on any error
					
		if [ ! -s $KAFKA_DIR/$KAFKA_CACERT_FILE ]; then
	        $ECHO "KAFKA $CAFlag CA certificate doesn't exist"
	        return 1;
	    fi
	        
	    $ECHO "About to delete $inputtype $KAFKA_CACERT_FILE file(s)"
	            
		# zeroize before delete
		deleteFiles 0 "$KAFKA_DIR/$KAFKA_CACERT_FILE"
				
		/fabos/cliexec/config save $KAFKA_DIR
		$AUDIT_NOTIFY "$CERT_DELE" "$KAFKA_CACERT_FILE" ""
		isDeleteOk=$DELETE_SUCCESS
		return 0

	elif [ "$1" == "$ASC" ]; then
		#The below function will prepare for delete
		#It will exit on any error

		if [ ! -s $ASC_DIR/$ASC_CACERT_FILE ]; then
			$ECHO "ASC $CAFlag CA certificate doesn't exist"
			return 1;
		fi

		$ECHO "About to delete $inputtype $ASC_CACERT_FILE file(s)"

		# zeroize before delete
		deleteFiles 0 "$ASC_DIR/$ASC_CACERT_FILE"
		deleteFiles 0 "$ASC_DIR_CACERT_CURL/$ASC_CACERT_ACT_FILE"
		deleteFiles 0 "$ASC_DIR_CACERT_CURL_MNT/$ASC_CACERT_ACT_FILE"


		/fabos/cliexec/config save $ASC_DIR
		/fabos/cliexec/config save $ASC_DIR_CACERT_CURL
		/fabos/cliexec/config update

		$WEBLNOTIFY $ASC:$CERT_DELE
		isDeleteOk=$DELETE_SUCCESS
		return 0

	elif [ "$1" == "$EXTN" ]; then
		if [ ! -e $EXTN_DIR ]; then
			return 1
		fi
		if [ $debug -eq 1 ]; then
			$ECHO "Removing all IP-extension Keys/Certificates"
		fi
	    file=`$LS $EXTN_DIR/*  2> /dev/null`
        if [ ! -z "$file" ]; then
    	    for i in $file
            do
				deleteFiles 0 $file
            done
        fi
	fi
	

	return 0
}

check_https_files() {

        setDefaultContext
        VID=$?
        filename=$1
        https_exist=1

        httpsSwCert=`/fabos/cliexec/config get $CERTCONFIG 5`
        httpsCaCert=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`
        httpskeyfile=`/fabos/cliexec/config get ssl.keyfile 5`

        if [[ "$httpsSwCert" != "$filename" && "$httpsCaCert" != "$filename" && "$httpskeyfile" != "$filename" ]]; then
                https_exist=0
        fi

        ### check for csr
        csr_extn=$(echo $filename |awk -F . '{if (NF>1) {print $NF}}')
        if [[ $csr_extn == csr ]]; then
                https_exist=1
        fi
        if [ $VID != -1 ];then
                setcontext $VID
        fi
        return $https_exist
}

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

		secOpConfirm

        if [ $? -eq 1 ]; then
            exit 1
        fi
	fi
}

GenerateSelfSignedCertsExtn() {

	#Generate keypair and CSR
	generateCsrExtn $key_size $hashtype $keytype $keypair

	certname="${keypair}${PEM_SUFFIX}"
	certname_path="${EXTN_DIR}/${certname}.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}"

	#create the temporary file to request for extensions, needed for v3 cert.
	if [ -e "$EXTN_V3EXT_FILE" ]; then
		$RM -f $EXTN_V3EXT_FILE > /dev/null
	else
		touch $EXTN_V3EXT_FILE
		if [ $? != 0 ]; then
			$ECHO "Unable to generate extension file"
			$ECHO "Deleting key `basename $pvtkeyfile`"
			deleteFiles 0 "$pvtkeyfile"
			$ECHO "Deleting CSR `basename $csrfile`"
			deleteFiles 0 "$csrfile"
			exit 1
		fi
	fi

	#Request for SKI and AKI as per RFC 5759.
	$ECHO "subjectKeyIdentifier=hash" >> $EXTN_V3EXT_FILE
	$ECHO "authorityKeyIdentifier=keyid:always,issuer" >> $EXTN_V3EXT_FILE

	days=`$EXPR $years \* 365`

	$ECHO "Generating self signed switch certificate $certname"
	$OPENSSL_CMD x509 -req -days $days -in "${csrfile}" -signkey "${pvtkeyfile}"\
		-out "${certname_path}"\
		-extfile "$EXTN_V3EXT_FILE" -$hashtype 2> /dev/null
	
   if [ $? -eq 0 ]; then
		#Store hash of the file in new file filename.hash
		hash=`$OPENSSL_CMD_NO_FIPS dgst -r -sha1 "${certname_path}" 2> /dev/null`
		if [ $? -eq 0 ]; then
			$ECHO $hash | cut -d ' ' -f 1 > "${certname_path}.hash" 2> /dev/null
		else
         $ECHO "Self signed certificate generation failed because hash calculation failed."
         $ECHO "Deleting key `basename $pvtkeyfile`"
         deleteFiles 0 "$pvtkeyfile"
         $ECHO "Deleting CSR `basename $csrfile`"
         deleteFiles 0 "$csrfile"
         $ECHO "Deleting certificate ${certname}"
         $RM -f $certname_path 2> /dev/null
			#Delete v3ext file
			$RM -f $EXTN_V3EXT_FILE 2> /dev/null
			exit 1
      fi
	else 
		$ECHO "Unable to generate certificate"
		$ECHO "Deleting key `basename $pvtkeyfile`"
		deleteFiles 0 "$pvtkeyfile"
		$ECHO "Deleting CSR `basename $csrfile`"
		deleteFiles 0 "$csrfile"
		#Delete v3ext file
		$RM -f $EXTN_V3EXT_FILE 2> /dev/null
		exit 1	
	fi
	
   #
   # Tell PDM to synchronize
   #
	chmod 400 "${pvtkeyfile}" 2> /dev/null
	/fabos/cliexec/config save $EXTN_DIR
	$AUDIT_NOTIFY "$CERT_GEN" "$certname (keypair_tag:$keypair, keytype:$keytype, keysize:$key_size, hashtype:$hashtype, years:$years)" "$certtype self-signed certificate"

	#Delete v3ext file
	if [ -e "$EXTN_V3EXT_FILE" ]; then	
		$RM -f $EXTN_V3EXT_FILE 2> /dev/null
	fi	

	return 0
}

GenerateSelfSignedCerts() {

    confirmSelfSignedCertGenerate

    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
    if [[ -z $restCaller ]]; then
	cleanUpHTTPS
    else
	cleanUpHTTPS "deletehttps"
    fi
    cd $TEMP_CERTGEN_PATH

    if [ "$keytype" == "dsa" ]; then
	    $OPENSSL_CMD dsaparam -out $DSA_PARAMS_FILE $key_size 2> /dev/null
	fi

	if [ $switchIPv6 != 0 ]; then
		commonname="$switchIPv6"
	else
		commonname="$switchIp"
	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 -extensions server_cert -days $days -$hashtype -subj "/C=$COUNTRY/ST=$STATE/L=$LOCALITY/O=$ORGANIZATION/OU=$ORGANIZATION_UNIT/CN="$commonname"" 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 -extensions server_cert -days $days -$hashtype -subj "/C=$COUNTRY/ST=$STATE/L=$LOCALITY/O=$ORGANIZATION/OU=$ORGANIZATION_UNIT/CN="$commonname"" 2> /dev/null
    fi

    chmod 400 $PVT_KEY_FILE 2> /dev/null

    $CP $SWITCH_CERT $CERT_DIR 2> /dev/null

    setDefaultContext
    VID=$?

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


    /fabos/cliexec/config set $CERTCONFIG 5 $SWITCH_CERT
    /fabos/cliexec/config set $HTTPCONFIG 1 1
    /fabos/cliexec/config set http.ssl.enabled 1 1
    /fabos/cliexec/config update

	# avoid HTTPS restart, if called from REST
	if [[ -z $restCaller ]]; then
	    $WEBDHANDLER $HTTPCONFIG:1
	fi

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

    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
		# avoid HTTPS restart, if called from REST
		if [[ -z $restCaller ]]; then
			$WEBDHANDLER $HTTPCONFIG:1
		fi
        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"
    return 0
}

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

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

	return $VID
}

showFilesExtn() {

	file_summary=0
	filename_path=""
	file_LocalSwCert=""
	file_RemoteSwCert=""
	file_CaCert=""
	file_LocalSwCsr=""
	file_LocalSwCert_same_name=""

	# Display file list
	if [ "$input" == "ALL" ]; then
		extnLocalSwCert=1
		extnRemoteSwCert=1
		extnCaCert=1
		extnLocalSwCsr=1
	fi
	
	#Display file summary
	if [ ! -z "$filename" ]; then
		file_summary=1
	fi


	if [ $extnLocalSwCert -eq 1 ]; then
		if [ ! -z "$filename" ]; then
			filename_path=`$LS ${EXTN_DIR}/${filename}.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
		else
			if [ ! -z "$keypair" ]; then
				file_LocalSwCert=`$LS ${EXTN_DIR}/*.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
			else
				file_LocalSwCert=`$LS ${EXTN_DIR}/*.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
			fi
		fi
	fi

	if [ $extnRemoteSwCert -eq 1 ]; then
		if [ ! -z "$filename" ]; then
			filename_path=`$LS ${EXTN_DIR}/${filename}.nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
			# Provide info to the user to display a local cert with same name (if it exists).
			file_LocalSwCert_same_name=`$LS ${EXTN_DIR}/${filename}.*.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
		else
			file_RemoteSwCert=`$LS ${EXTN_DIR}/*.nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
		fi
	fi

	if [ $extnCaCert -eq 1 ]; then
		if [ ! -z "$filename" ]; then
			filename_path=`$LS $EXTN_DIR/${filename}.${EXTN_CACERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
		else
			file_CaCert=`$LS $EXTN_DIR/*.${EXTN_CACERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
		fi
	fi

	if [ $extnLocalSwCsr -eq 1 ]; then
		if [ ! -z "$filename" ]; then
			filename_path=`$LS ${EXTN_DIR}/${filename}  2> /dev/null`
		else
			if [ ! -z "$keypair" ]; then
				file_LocalSwCsr=`$LS ${EXTN_DIR}/${keypair}${CSR_SUFFIX}  2> /dev/null`
			else
				file_LocalSwCsr=`$LS ${EXTN_DIR}/*${CSR_SUFFIX}  2> /dev/null`
			fi
		fi
	fi

	if [ ! -z "$filename_path" ] || [ ! -z "$file_LocalSwCert" ] || [ ! -z "$file_RemoteSwCert" ] \
		|| [ ! -z "$file_CaCert" ] || [ ! -z "$file_LocalSwCsr" ]; then

		if [ $file_summary -eq 1 ]; then
			if [ $extnLocalSwCert -eq 1 ]; then
				$ECHO "Displaying contents of local $showreq $filename"
			elif [ $extnRemoteSwCert -eq 1 ]; then 
				$ECHO "Displaying contents of remote $showreq $filename"
				if [ ! -z "$file_LocalSwCert_same_name" ]; then
					$ECHO	"(Use certificate name with \"-keypair_tag <keypair_name>\" to display summary of local certificate.)"
				fi
			else
				$ECHO "Displaying contents of $showreq $filename"
			fi

			if [ $extnLocalSwCsr -eq 1 ]; then
				$ECHO ""
				$OPENSSL_CMD req -in "$filename_path" -noout -text -custom \
					-nameopt multiline -config $CONFIG_FILE 2> /dev/null
				if [ $? != 0 ]; then
					$ECHO "$filename: Is an unknown CSR format."
					exit 1
				fi
			else
				if [ $hexdump -eq 1 ]; then
					$ECHO ""
					$CAT "$filename_path" | more		
					$ECHO ""
				else
					$ECHO ""
					$OPENSSL_CMD x509 -in "$filename_path" -noout -custom \
						-nameopt multiline -subject -issuer -dates -fingerprint -custom 2> /dev/null
					if [ $? -eq 0 ]; then
						dgst=`$OPENSSL_CMD_NO_FIPS dgst -r -sha1 "$filename_path" 2> /dev/null`
						if [ $? -eq 0 ] ; then
							hash=`$ECHO $dgst | cut -d ' ' -f 1`
							if [ -f "$filename_path.hash" ]; then
								import_hash=`$CAT $filename_path.hash | cut -d ' ' -f 1 2> /dev/null`
								if [ "$hash" == "$import_hash" ]; then
									$ECHO "File-Hash		$hash"
								else
									$ECHO "File-Hash Mismatch"
									$ECHO "	Current File-Hash	$hash"
									$ECHO "	Import File-Hash 	$import_hash"	
								fi
								$ECHO ""
							else
								$ECHO "File-Hash Mismatch"
								$ECHO "	Current File-Hash	$hash"
								$ECHO "	Import File-Hash 	Import Hash file is not found"	
								$ECHO ""
							fi
						fi 
					else
						$ECHO "$filename: Is an unknown x509 format."
					fi
				fi	
			fi
			exit 1
		fi

		$ECHO "List of extn files:"
		if [ $extnLocalSwCert -eq 1 -o $extnRemoteSwCert -eq 1 ] && [ "$input" != "ALL" ]; then
			$ECHO "Certificate Files:"
			$ECHO -n "------------------------------------------------------------------------"
			$ECHO "--------------------------------------------------------"
			if [ $extn -eq 1 ]; then
				printf "%-10s %-25s %-25s %-7s %-7s %-7s %-7s\n" "Protocol" "CA" "SW" \
					"CSR" "PVT Key" "Passphrase" "Keypair Tag"
			fi
			$ECHO -n "------------------------------------------------------------------------"
			$ECHO "-------------------------------------------------------"
		fi

		if [ $extnLocalSwCert -eq 1 ]; then	
			$ECHO "List of local CERT files"
			for i in $file_LocalSwCert
			do
				pvt_key="Empty"
				csr="Empty"

				if [  -s "$i" ]; then
					keypair=`$ECHO $i | awk -F '.' ' { print $(NF-3) }'`
					filename=`basename $i | sed -e "s/".${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}"//"`
					if [ -s "${EXTN_DIR}/${keypair}.${PVT_KEY}" ]; then
						pvt_key="Exist"
					fi
					if [ -s "${EXTN_DIR}/${keypair}${CSR_SUFFIX}" ]; then
						csr="Exist"
					fi

					if [ $extn -eq 1 ]; then
						printf "%-10s %-25s %-25s %-7s %-7s %-10s %-31s\n" "EXTN" "NA" "$filename" \
							"$csr" "$pvt_key" "NA" "$keypair"
					else
						printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "EXTN" "NA" "NA" "$filename" \
							"$csr" "$pvt_key" "NA"
					fi
				fi
			done
		fi

		if [ $extnRemoteSwCert -eq 1 ]; then
			$ECHO "List of remote CERT files"
			for i in $file_RemoteSwCert
			do
				if [  -s "$i" ]; then
					filename=`basename $i | sed -e "s/".nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}"//"`
					if [ $extn -eq 1 ]; then
						printf "%-10s %-25s %-25s %-7s %-7s %-10s %-31s\n" "EXTN" "NA" "$filename" \
							"NA" "NA" "NA" "NA"
					else
						printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "EXTN" "NA" "NA" "$filename" \
							"NA" "NA" "NA"
					fi
				fi
			done
		fi

		if [ $extnCaCert -eq 1 ]; then
			$ECHO "List of CA files"
			for i in $file_CaCert
			do
				if [  -s "$i" ]; then
					$ECHO `basename $i | sed -e "s/".${EXTN_CACERT_FILE_EXT}${PEM_SUFFIX}"//"`
				fi
			done
		fi

		if [ $extnLocalSwCsr -eq 1 ]; then
			$ECHO "List of CSR files"
			for i in $file_LocalSwCsr
			do
				if [  -s "$i" ]; then
					$ECHO `basename $i`
				fi
			done
		fi

	else
		if [ "$input" == "ALL" ]; then
			printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "EXTN" "NA" "NA" \
				"Empty" "Empty" "Empty" "NA"
		elif [ $file_summary -eq 1 ]; then 
			if [ $extnLocalSwCert -eq 1 ] ; then
				$ECHO "No local $showreq $filename found."
			elif [ $extnRemoteSwCert -eq 1 ] ; then
				$ECHO "No remote $showreq $filename found."
				if [ ! -z "$file_LocalSwCert_same_name" ]; then
					$ECHO ""
					$ECHO "Use certificate name with \"-keypair_tag <keypair_name>\" to display summary of local switch certificate."
					$ECHO ""
				fi
			else
				$ECHO "No $showreq $filename found."
			fi
		else
			# Do not change the below line as preinstall script depends on 
			# this line for downgrade related check.	
			$ECHO "No $filename $showreq found."
		fi
	fi
}

#
#
# A function to list the certificates or the CSRs
#
showFiles() {
	isCertExist=0;
	VID=-1;

	filetag=""
	
	if [ "$showreq" == "CERT" ]; then
		filetag="$SWITCH_CERT_DESC_NAME"
		if [ "$inputtype" == "$COMMONCERT" ]; then
            if [ -s $FCAP_DIR/$FCAP_SWCERT_FILE ]; then
		fcapchksum=`$OPENSSL_CMD_NO_FIPS x509 -in $FCAP_DIR/$FCAP_SWCERT_FILE | $OPENSSL_CMD_NO_FIPS md5`
            else
                $ECHO "No $COMMONCERT $filetag found";$ECHO
		exit 0
            fi
            setDefaultContext
            VID=$?
            inputfile=`/fabos/cliexec/config get $CERTCONFIG 5`
            # Change the VF back to current context.
            if [ $VID != -1 ];then
                setcontext $VID
            fi
            if [ -s $CERT_DIR/$inputfile ]; then
		httpschksum=`$OPENSSL_CMD_NO_FIPS x509 -in $CERT_DIR/$inputfile | $OPENSSL_CMD_NO_FIPS md5`
            else
                $ECHO "No $COMMONCERT $filetag found";$ECHO
		exit 0
            fi

		if [ "$fcapchksum" != "$httpschksum" ]; then
			$ECHO "No $COMMONCERT $filetag found";$ECHO
			exit 0
		fi
		cd $FCAP_DIR
		inputfile=$FCAP_SWCERT_FILE

		elif [ "$inputtype" == "$FCAPS" ]; then
			cd $FCAP_DIR
			$ECHO
			if [ -s $FCAP_SWCERT_FILE ]; then
				inputfile=$FCAP_SWCERT_FILE
			else
				$ECHO "No $inputtype $filetag found"
				$ECHO
				exit 0
			fi

		elif [ "$inputtype" == "$HTTPS" ]; then
			cd $CERT_DIR
       	    setDefaultContext
   	        VID=$?
            inputfile=`/fabos/cliexec/config get $CERTCONFIG 5`
		    # Change the VF back to current context.
		    if [ $VID != -1 ];then
		        setcontext $VID
		    fi
			$ECHO
			if [ ! -s $inputfile ]; then
				$ECHO "No $inputtype $filetag found"
				$ECHO
				exit 0
			fi

		elif [ "$inputtype" == "$RADIUS" ]; then
			if [ -e $RADIUS_DIR ]; then
				cd $RADIUS_DIR
			fi
			$ECHO
            if [ -s $RADIUS_SWCERT_FILE ]; then
				inputfile=$RADIUS_SWCERT_FILE
            else
                $ECHO "No $inputtype $filetag found"
				$ECHO
				exit 0
            fi
			$ECHO

		elif [ "$inputtype" == "$LDAP" ]; then
			cd $LDAP_DIR
			$ECHO
            if [ -s $LDAP_SWCERT_FILE ]; then
				inputfile=$LDAP_SWCERT_FILE
            else
                $ECHO "No $inputtype $filetag found"
				$ECHO
				exit 0
            fi
			$ECHO

        elif [ "$inputtype" == "$SYSLOG" ]; then
			cd $SYSLOG_DIR
			$ECHO
            if [ -s $SYSLOG_SWCERT_FILE ]; then
				inputfile=$SYSLOG_SWCERT_FILE
            else
                $ECHO "No $inputtype $filetag found"
				$ECHO
				exit 0
            fi
			$ECHO
		elif [ "$inputtype" == "$MGMT" ]; then
			cd $MGMT_DIR
            if [ -z "$filename" ]; then
                readInput "Enter certificate name (must have \".crt\" or \".cer\"  \".pem\" or \".psk\" suffix): "
                inputfile=$userInput
                $ECHO "$inputfile" | $GREP '/' >/dev/null 2>&1
                if [ "$?" -eq 0 ]; then
                    $ECHO "Filename cannot be provided with path"
                    exit 1
                fi
            else
				inputfile=$filename
			fi

			if [ ! -s $inputfile ]; then
				if [ ! -s $CERT_DIR/$inputfile ]; then
                			$ECHO "Certificate $inputfile does not exist"
     				        $ECHO
					exit 0
				fi
			fi
		else
			showUsage
			exit 1
		fi
	elif [ "$showreq" == "CA" ]; then
		filetag="$SWITCH_CACERT_DESC_NAME"
        if [ "$inputtype" == "$COMMONCERT" ]; then
            if [ -s $FCAP_DIR/$FCAP_CACERT_FILE ]; then
		fcapchksum=`$OPENSSL_CMD_NO_FIPS x509 -in $FCAP_DIR/$FCAP_CACERT_FILE | $OPENSSL_CMD_NO_FIPS md5`
            else
                $ECHO "No $COMMONCERT $filetag found";$ECHO
		exit 0
            fi
            setDefaultContext
            VID=$?
            inputfile=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`
            # Change the VF back to current context.
            if [ $VID != -1 ];then
                setcontext $VID
            fi
            if [ -s $CERT_DIR/$inputfile ]; then
		httpschksum=`$OPENSSL_CMD_NO_FIPS x509 -in  $CERT_DIR/$inputfile | $OPENSSL_CMD_NO_FIPS md5`
            else
                $ECHO "No $COMMONCERT $filetag found";$ECHO
		exit 0
            fi

		if [ "$fcapchksum" != "$httpschksum" ]; then
			$ECHO "No $COMMONCERT $filetag found";$ECHO
			exit 0
		fi
		cd $FCAP_DIR
		inputfile=$FCAP_CACERT_FILE

        elif [ "$inputtype" == "$FCAPS" ]; then
            cd $FCAP_DIR
			$ECHO
            if [ -s $FCAP_CACERT_FILE ]; then
				inputfile=$FCAP_CACERT_FILE
            else
                $ECHO "No $inputtype $filetag found"
				$ECHO
				exit 0
            fi

        elif [ "$inputtype" == "$HTTPS" ]; then
			cd $CERT_DIR
       	    setDefaultContext
   	        VID=$?
            inputfile=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`
		    # Change the VF back to current context.
		    if [ $VID != -1 ];then
    	    	setcontext $VID
	    	fi
			$ECHO
            if [ ! -s $inputfile ]; then
                $ECHO "No $inputtype $filetag found"
				$ECHO
				exit 0
            fi

        elif [ "$inputtype" == "$RADIUS" ]; then
            if [ -e $RADIUS_DIR ]; then
                cd $RADIUS_DIR
            fi
			$ECHO

			if [ "$CAFlag" == "server" ]; then
	            if [ -s $RADIUS_CACERT_FILE ]; then
					inputfile=$RADIUS_CACERT_FILE
        	    else
            	    $ECHO "No $inputtype $filetag found"
					$ECHO
					exit 0
				fi
            else
                if [ -s $RADIUS_CLIENT_CACERT_FILE ]; then
                    inputfile=$RADIUS_CLIENT_CACERT_FILE
                else
                    $ECHO "No $inputtype $filetag found"
					$ECHO
                    exit 0
                fi

			fi

        elif [ "$inputtype" == "$LDAP" ]; then
            cd $LDAP_DIR
			$ECHO
			if [ "$CAFlag" == "server" ]; then
	            if [ -s $LDAP_CACERT_FILE ]; then
					inputfile=$LDAP_CACERT_FILE
        	    else
            	    $ECHO "No $inputtype $filetag found"
					$ECHO
					exit 0
	            fi
			else
                if [ -s $LDAP_CLIENT_CACERT_FILE ]; then
                    inputfile=$LDAP_CLIENT_CACERT_FILE
                else
                    $ECHO "No $inputtype $filetag found"
					$ECHO
                    exit 0
                fi
			fi

		elif [ "$inputtype" == "$ASC" ]; then
			cd $ASC_DIR
			$ECHO
			if [ "$CAFlag" == "server" ]; then
				if [ -s $ASC_CACERT_FILE ]; then
					inputfile=$ASC_CACERT_FILE
				else
					$ECHO "No $inputtype $filetag found"
					$ECHO
					exit 0
				fi
			fi

		elif [ "$inputtype" == "$SYSLOG" ]; then
            cd $SYSLOG_DIR
			$ECHO
			if [ "$CAFlag" == "server" ]; then
	            if [ -s $SYSLOG_CACERT_FILE ]; then
					inputfile=$SYSLOG_CACERT_FILE
        	    else
            	    $ECHO "No $inputtype $filetag found"
					$ECHO
					exit 0
	            fi
			else
                if [ -s $SYSLOG_CLIENT_CACERT_FILE ]; then
                    inputfile=$SYSLOG_CLIENT_CACERT_FILE
                else
                    $ECHO "No $inputtype $filetag found"
					$ECHO
                    exit 0
                fi
			fi
        else
            showUsage
            exit 1
        fi
	elif [ "$showreq" == "CSR" ]; then
		filetag="csr"
		inputfile=$switchIp$CSR_SUFFIX

	if [ "$inputtype" == "$COMMONCERT" ]; then
		if [ -s $FCAP_DIR/$FCAP_SWCSR_FILE ] && [ -s $CERT_DIR/$inputfile ]; then
			fcapchksum=`$OPENSSL_CMD_NO_FIPS req -in $FCAP_DIR/$FCAP_SWCSR_FILE | $OPENSSL_CMD_NO_FIPS md5`
			httpschksum=`$OPENSSL_CMD_NO_FIPS req -in $CERT_DIR/$inputfile | $OPENSSL_CMD_NO_FIPS md5`
		else
			$ECHO "The $inputtype $filetag does not exist";$ECHO
			exit 0
		fi

		if [ "$fcapchksum" != "$httpschksum" ]; then
			$ECHO "The $inputtype $filetag does not exist";$ECHO
			exit 0
		fi
		cd $FCAP_DIR
		inputfile=$FCAP_SWCSR_FILE

        elif [ "$inputtype" == "$FCAPS" ]; then
            cd $FCAP_DIR
			inputfile=$FCAP_SWCSR_FILE

        elif [ "$inputtype" == "$HTTPS" ]; then
			cd $CERT_DIR
        elif [ "$inputtype" == "$RADIUS" ]; then
            cd $RADIUS_DIR

        elif [ "$inputtype" == "$LDAP" ]; then
            cd $LDAP_DIR
        
		elif [ "$inputtype" == "$SYSLOG" ]; then
            cd $SYSLOG_DIR

        else
            showUsage
            exit 1
        fi

	    if [ ! -s "$inputfile" ]; then
    	    $ECHO "The $inputtype $filetag does not exist"
			$ECHO
        	exit 0
	    fi
	else
		showUsage
		exit 1
	fi

	if [ "$showreq" == "CERT" ] || [ "$showreq" == "CA" ]; then
        cLen=`expr length $inputfile`
        let dotIndex="$cLen"-3
        fileSuffix=`expr substr $inputfile $dotIndex $cLen`
        if [ "$fileSuffix" == "$PSK_SUFFIX" ] || [ "$inputtype" == "$MGMT" ]; then
		if [ -s $inputfile ]; then
                        $CAT ./$inputfile
                        $ECHO
                elif [ -s $CERT_DIR/$inputfile ]; then
			check_https_files $CERT_DIR/$inputfile
                        https_exist=$?
                        if [ $https_exist -eq 0 ]; then
                        	$CAT $CERT_DIR/$inputfile
                    	    	$ECHO
			fi
                fi
		else	
	        if [ "$fileSuffix" == "$CER_SUFFIX" ] || [ "$fileSuffix" == "$CRT_SUFFIX" ]; then
				$OPENSSL_CMD x509 -in ./$inputfile \
	            	-outform PEM -out ./$TEMP_CERT
				$ECHO
				if [ $hexdump -eq 1 ]; then
					$OPENSSL_CMD x509 -in ./$TEMP_CERT
				else
					$OPENSSL_CMD x509 -in ./$TEMP_CERT -noout -custom \
						-nameopt multiline -subject -issuer -dates -fingerprint -custom
					if [[ ! -z $restCaller ]]; then
						$OPENSSL_CMD x509 -in ./$TEMP_CERT
					fi
				fi
				ret=$?
            	$RM -rf ./$TEMP_CERT 2> /dev/null
	        else
				if [ $hexdump -eq 1 ]; then
					$OPENSSL_CMD x509 -in ./$inputfile	
				else
					$OPENSSL_CMD x509 -in ./$inputfile -noout -custom \
						-nameopt multiline -subject -issuer -dates -fingerprint -custom
					if [[ ! -z $restCaller ]]; then
						$OPENSSL_CMD x509 -in ./$inputfile	
					fi
				fi
				ret=$?
	        fi

        	if [ $ret != 0 ]; then
            	$ECHO "$inputfile: Is an unknown x509 format."
				$ECHO
				exit 1
			fi
        fi
	else
		if [ $hexdump -eq 1 ]; then
			$ECHO
			$OPENSSL_CMD req -in ./$inputfile
			ret=$?
			$ECHO
		else
			$OPENSSL_CMD req -in ./$inputfile -noout -text -custom \
				-nameopt multiline -config $CONFIG_FILE
			ret=$?
        		if [ $ret == 0 ]; then
				if [[ ! -z $restCaller ]]; then
					$ECHO
					$OPENSSL_CMD req -in ./$inputfile
					ret=$?
					$ECHO
				fi
			fi
		fi

        if [ $ret != 0 ]; then
           	$ECHO "$inputfile: Is an unknown CSR format."
			$ECHO
       		exit 1
        fi
	fi
	$ECHO
}

#
# Print the usage of this utility
#
usage() {
    $ECHO
    $ECHO "Usage:"
    $ECHO "seccertmgmt"
    $ECHO "      generate - Generate keypairs and CSR or Certificate"
    $ECHO "      delete   - Delete Certificates and associated Keypair"
    $ECHO "      import   - Import Certificate"
	$ECHO "      export   - Export Certificate"
    $ECHO "      show     - List or Display Certificates"
    $ECHO "      help     - Shows the usage"
	$ECHO
}

generateUsage() {
	$ECHO
	$ECHO "Usage:"
	$ECHO "seccertmgmt generate"
	$ECHO "		-csr <fcap|commoncert|https|radius|ldap|syslog|extn>"
	$ECHO "		-cert <https|extn>"
	$ECHO "		[-type <rsa|dsa|ecdsa>]"
	$ECHO "		[-keysize <1024|2048|4096|8192|P384>]"
	$ECHO "		[-hash <sha1|sha256|sha384|sha512>]"
	$ECHO "		[-years <x>]"
	$ECHO "		-keypair_tag <keypair_name>"
	$ECHO "		[-f] - no warning"
	$ECHO 
}

deleteUsage() {
	$ECHO 
	$ECHO "Usage:"
	$ECHO "seccertmgmt delete"
	$ECHO "		-cert <fcap|commoncert|https|radius|ldap|syslog|extn (<certificate name> | -keypair_tag <keypair_tag>)|mgmtip <certificate name>|all>"
	$ECHO "		-ca -client|-server <fcap|commoncert|https|radius|ldap|syslog|extn <certificate name> |asc|all>"
	$ECHO "		-csr <fcap|commoncert|https|radius|ldap|syslog|extn -keypair_tag <keypair_tag>>"
	$ECHO "		-all <default|fcap|commoncert|https|radius|ldap|syslog|extn|mgmtip>"
    $ECHO "		[-f] - no warning"
	$ECHO 
}

importUsage() {
	$ECHO
	$ECHO "Usage:"
	$ECHO "seccertmgmt import"
    $ECHO "		-cert <fcap|commoncert|https|radius|ldap|syslog|extn|mgmtip>"
	$ECHO "		-ca -client|-server <fcap|commoncert|https|radius|ldap|syslog|extn|asc>"
    $ECHO "		-keypair_tag <keypair_name>"
	$ECHO "		-protocol <scp|ftp>"
	$ECHO "		-ipaddr <IP address>"
	$ECHO "		-remotedir <remote directory>"
	$ECHO "		-certname <certificate name>"
	$ECHO "		-cacert <preimported_local_ca_cert>"
	$ECHO "		-login <login name>"
	$ECHO "		-password <password>"
	$ECHO
}

exportUsage() {
    $ECHO
    $ECHO "Usage:"
    $ECHO "seccertmgmt export"
    $ECHO "		-cert <fcap|commoncert|https|radius|ldap|syslog|extn|mgmtip>"
    $ECHO "		-ca -client|-server <fcap|commoncert|https|radius|ldap|syslog|extn>"
    $ECHO "		-csr <fcap|commoncert|https|radius|ldap|syslog|extn>"
    $ECHO "		-keypair_tag <keypair_name>"
    $ECHO "		-protocol <scp|ftp>"
    $ECHO "		-ipaddr <IP address>"
    $ECHO "		-remotedir <remote directory>"
    $ECHO "		-certname <certificate name>"
    $ECHO "		-login <login name>"
    $ECHO "		-password <password>"
    $ECHO
}

showUsage() {
	$ECHO 
	$ECHO "Usage:"
	$ECHO "seccertmgmt show"
	$ECHO "		-cert <fcap|commoncert|https|radius|ldap|syslog|extn <certificate name>|mgmtip <certificate name>>"
	$ECHO "		-ca -client|-server <fcap|commoncert|https|radius|ldap|syslog|extn <certificate name>|asc|kafka>"
	$ECHO "		-csr <fcap|commoncert|https|radius|ldap|syslog|extn <csr name>>"
	$ECHO "		-keypair_tag <keypair_name>"
	$ECHO "		-hexdump - Dump the hexadecimal output"
	$ECHO "		-all"
	$ECHO
}

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

#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

}

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 compliant certificate."

			secOpConfirm

        	if [ $? -eq 1 ]; then
    	        exit 1
	        fi
		fi
	fi
	return $RET
}

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

	swbd=`sin | $AWK ' {print $2} ' | $GREP SWBD | sed 's@,@@'`
	checkFipsMode
	fips_mode=$?
	`$CONFIGSHOW_CMD | $GREP 'cfgload.secure' | $GREP -qE '1'`
	secure_mode=`$ECHO $? `

	if [ -z "$protocol" ] && [ "$inputtype" != "$KAFKA" ]; then
	    $ECHO -n "Select protocol ["$PROT_FTP" or "$PROT_SCP"]: "
	    read protocol
	fi
  	
	if [ "$protocol" == "$PROT_FTP" ] && [ ! -z "$secure_mode" ] && [ $secure_mode -eq 0 ] && [ "$inputtype" != "$KAFKA" ]; 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 1 ] && [ "$inputtype" != "$KAFKA" ]; then
	    $ECHO "Fips mode is active. Use SCP for file transfer..."
	    exit 1
	fi
	    
	if [ "$protocol" != "$PROT_FTP" ] && [ "$protocol" != "$PROT_SCP" ] && [ "$inputtype" != "$KAFKA" ]; then
		$ECHO Unknown protocol: "$protocol"
		exit 1
	fi

	if [ -z "$ipAddr" ] && [ "$inputtype" != "$KAFKA" ]; 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" ] && [ "$inputtype" != "$KAFKA" ]; then
		printf "Enter remote directory: "
		read remoteDir
		if [ -z "$remoteDir" ]; then
			printf "remote directory should not be empty\n"
			exit 1;
		fi
	fi

	if [ ! -z "$remoteDir" ]; then
	$ECHO "$remoteDir" | $GREP -v "[\`!@#$%^&*()+=|\\}{\"\':,?;><\[]" | $GREP -v "]" > /dev/null 2>&1
		if [ ! $? -eq 0 ]; then
			$ECHO "Unsupported characters in remote directory"
			exit 1
		fi
	fi

	if [ "$1" = "$CERT_IMPORT" ]; then
		if [ -z "$certFileName" ]; then
			if [ "$inputtype" == "$FCAPS" ] || [[ "$inputtype" == "$HTTPS" && "$impreq" == "CA" ]] || [[ "$inputtype" == "$SYSLOG" && "$impreq" == "CA" ]]; 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
		if [ ! -z "$certFileName" ]; then
		$ECHO "$certFileName" | $GREP -v "[~\`!@#$%^&*()+=|\\}{\"\':,?;><\[]" | $GREP -v "]" > /dev/null 2>&1
			if [ ! $? -eq 0 ]; then
				$ECHO "Unsupported characters in filename"
			fi
		fi
		certFileOnly=1
	else
		if [ "$inputtype" == "$MGMT" ]; then
			if [ -z "$certFileName" ]; then
				readInput "Enter certificate name (must have \".crt\" or \".cer\"  \".pem\" or \".psk\" suffix): "
				certFileName=$userInput
				$ECHO "$certFileName" | $GREP '/' >/dev/null 2>&1
				if [ "$?" -eq 0 ]; then
					$ECHO "Filename cannot be provided with path"
					exit 1
				fi
			fi			
		fi
	fi

	if [ -z "$userName" ] && [ "$inputtype" != "$KAFKA" ]; 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 "$userName" ]; then
			$ECHO "$userName" | $GREP -v "[~\`!#$%^&*()+=|}{\"\':?;,><\[]" | $GREP -v "]" > /dev/null 2>&1
			if [ ! $? -eq 0 ]; then
					$ECHO "Unsupported characters in login name"
					exit 1
			fi
		fi

	if [ -z "$password1" ] && [ "$inputtype" != "$KAFKA" ]; 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
		certImport $1 $impreq $inputtype $keypair
	else
		certExport $1 $expreq $inputtype $keypair
	fi
}

copyfromremote() {
	if [ "$protocol" == "$PROT_FTP" ]; then
		/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
	else
		if [ $extn -eq 1 ]; then
			/usr/bin/scp -q -oStrictHostKeyChecking=no \
				$userName@\[$ipAddr\]:$remoteDir/$userInput $EXTN_DIR/$certpkey 2> /dev/null
		else
			if [[ ! -z $restCaller ]]; then
				/usr/bin/scp -q -oStrictHostKeyChecking=no -oSSHPassword=$password1\
					$userName@\[$ipAddr\]:$remoteDir/$userInput ./$userInput 2> /dev/null
			else
				/usr/bin/scp -q -oStrictHostKeyChecking=no \
					$userName@\[$ipAddr\]:$remoteDir/$userInput ./$userInput 2> /dev/null
			fi
		fi	
	fi

    if [ $? != 0 ]; then
		$ECHO "error: Certificate import failed. Please check the certificate location and user credentials."
        exit 1
    else
		if [ "$protocol" == "$PROT_FTP" ] && [ $extn -eq 1 ]; then
			/bin/mv ${certFileName} ${EXTN_DIR}/${certpkey}
		fi
	 fi

	return 0
}

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

certImport() {

	certIndex=1
	certpkey=""
	extnLocalReimport=0
	depth=0
#	response="no"
	selfsign=0
	if [ "$inputtype" == "$FCAPS" ]; then
	    if [ ! -e "$FCAP_DIR" ]; then
    	    mkdir -p $FCAP_DIR
        fi
        cd $FCAP_DIR
			
		if [ "$impreq" == "CA" ]; then
			copyfromremote
   	        # 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 2> /dev/null
			if [[ -z $restCaller ]]; then
        	        	exit 1;
			else
				exit 12
			fi
   	        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 2> /dev/null
       	    if [ $total_certs -gt $MAX_ALLOWED_CACERTS ]; then
				if [ $commoncert -eq 0 ]; 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."
				else
   	                $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 2> /dev/null
		if [[ -z $restCaller ]]; then
       	        	exit 1
		else
			exit 14
		fi
            fi

   	        # Verifying each imported certificate to make sure its root CA certificate exist.
       	    i=1
            $CAT /dev/null > $FCAP_DIR/$FCAP_TEMP_FILE
   	        IFS_=${IFS}; IFS=$'\n'
       	    for LINE in `$CAT $FCAP_DIR/$userInput`;    do
           	    if [ "$LINE" == "$FCAP_CERT_HEADER" ] || [ $copy_cert -eq 1 ] ; then
               	    $ECHO $LINE >> $FCAP_DIR/$FCAP_TEMP_FILE
                   	copy_cert=1
                fi
	
   	            if [ "$LINE" == "$FCAP_CERT_FOOTER" ] ; then
       	            copy_cert=2
           	    fi
               	if [ $copy_cert -eq 2 ] ; then
                    #First we verify if the Root CA is in the imported file.
   	                output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $FCAP_DIR/$userInput $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null`

       	            check=`$ECHO "$output" | $AWK ' {print $2} '`
           	        if [ "$check" != "OK" ] ; then
               	        # If its not in imported file then we check if its in existing file.
						if [ -s $FCAP_DIR/$FCAP_CACERT_FILE ]; then
	                   	    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 2> /dev/null
           	        	        $RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
								$ECHO "Import failed"
               	        	    exit 1
	                   	    fi
						else
							printError
							$RM $FCAP_DIR/$userInput 2> /dev/null
							$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
							$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 2> /dev/null
       	                    $RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
				if [[ -z $restCaller ]]; then
           	                	exit 1
				else
					exit 15
				fi
               	        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 2> /dev/null
                        $RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
			if [[ -z $restCaller ]]; then
                        	exit 1
			else
				exit 15
			fi
                    fi
                done
            done
   	        IFS=${IFS_};
       	    # Certificate compliance with FIPs mode
           	checkForFIPsCompl $FCAP_DIR/$userInput
            if [ $? != 0 ]; then
   	            $ECHO "Operation cancelled."
       	        $RM $FCAP_DIR/$userInput 2> /dev/null
           	    $RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
               	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 2> /dev/null
            $RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
   	        updateFCAPConfigFile "ROOT_CA_CERTIFICATES:$total_certs"
			setDefaultContext
			VID=$?

   	        /fabos/cliexec/config save $FCAP_DIR/$FCAP_CERT_CONF_FILE
       	    /fabos/cliexec/config save $FCAP_DIR/$FCAP_CACERT_FILE

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

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

            if [ $commonCert -eq 1 ]; then
                $ECHO "Success: $1ed Common ca certificate ["$userInput"]."
            else
                $ECHO "Success: $1ed fcap ca certificate ["$userInput"]."
            fi
		else
			CertConfExist=0
            # Checking if the cert.conf file exist. So we can store the name
            # of the imported file into that file.
   	        if [ -e "$FCAP_DIR/$FCAP_CERT_CONF_FILE" ]; then
       	        CertConfExist=1
            fi

			copyfromremote

           	# 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 2> /dev/null
               	$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
		if [[ -z $restCaller ]]; then
                	exit 1;
		else
			exit 12
		fi
 	    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."
				$RM $FCAP_DIR/$userInput 2> /dev/null
				$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit 16
				fi
			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."
                $RM $FCAP_DIR/$userInput 2> /dev/null
				$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
		if [[ -z $restCaller ]]; then
   	            exit 1
		else
			exit 16
		fi
            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"

					secOpConfirm

			        if [ $? -eq 1 ]; then
						flag=0
					else
						flag=1
			        fi
           	    fi
            fi

			if [ $flag -eq 1 ]; then
   		        # validation with pvt key and csr - needed for sw certs
	       	    certPvtKeyValidate $1
        	   	# Certificate compliance with FIPs mode
            	checkForFIPsCompl $FCAP_DIR/$userInput
			fi

            if [ $? != 0 ]; then
                $ECHO "Operation cancelled."
                $RM $FCAP_DIR/$userInput 2> /dev/null
   	            $RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
       	        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 2> /dev/null
   	            $RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
       	        $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 2> /dev/null
   	        $RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
			setDefaultContext
			VID=$?

            /fabos/cliexec/config save $FCAP_DIR/$FCAP_SWCERT_FILE
   	        /fabos/cliexec/config save $FCAP_DIR/$FCAP_TOUCH_FILE
       	    /fabos/cliexec/config save $FCAP_DIR/$FCAP_CERT_CONF_FILE

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

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

            if [ $commonCert -eq 1 ]; then
                $ECHO "Success: $1ed Common switch certificate ["$userInput"]."
            else
                $ECHO "Success: $1ed fcap switch certificate ["$userInput"]."
            fi
		fi
	elif [ "$inputtype" == "$RADIUS" ]; then
	    if [ ! -e "$RADIUS_DIR" ]; then
            mkdir -p $RADIUS_DIR
        fi
        cd $RADIUS_DIR

		if [ "$impreq" == "CA" ]; then
			copyfromremote
            cLen=`expr length $userInput`
            let dotIndex="$cLen"-3
            fileSuffix=`expr substr $userInput $dotIndex $cLen`
            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 $RADIUS_DIR/$TEMP_CACERT > /dev/null 2>&1

                if [ $? != 0 ]; then
                    $ECHO "Failed to convert certificate to .pem"
                    $RM $RADIUS_DIR/$userInput 2> /dev/null
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit 17
			fi
                fi
            else
                #validate the file format
                $OPENSSL_CMD x509 -in $userInput -inform PEM -outform DER -out $RADIUS_DIR/$userInput.der > /dev/null 2>&1
                if [ $? != 0 ]; then
			$ECHO "Bad format certificate. Exiting.."
			$RM $RADIUS_DIR/$userInput 2> /dev/null
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit 12
			fi
		fi
		if [ -f $RADIUS_DIR/$userInput.der ]; then
	    	        $RM $RADIUS_DIR/$userInput.der 2> /dev/null
    	        fi
	        $CAT $RADIUS_DIR/$userInput >  $RADIUS_DIR/$TEMP_CACERT
	fi

			#Check valid CA certificate or not
			#Commenting out CC Mandates for RADIUS
			#Add '-CC_check' flag under verify when uncommenting to validate CC constraints
			#if [ "$AuditLogMode" == "Strict" ]; then
			#	$OPENSSL_CMD_NO_FIPS x509 -in  $RADIUS_DIR/$userInput -text -noout | $GREP -i CA:true > /dev/null 2>&1
			#	caTrue=$?

			#	if [ $caTrue -ne 0 ]; then
			#			$ECHO "Error: Invalid CA certificate"
			#			/fabos/libexec/secnotify cert_validation "invalid CA certificate"
	    	        #    $RM $RADIUS_DIR/$userInput 2> /dev/null
    	    	        #$RM $RADIUS_DIR/$TEMP_CACERT 2> /dev/null
        	    	#    $ECHO "Import failed"
            	    	#exit 1
			#	fi
			#fi

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

            # Certificate compliance with FIPs mode
            checkForFIPsCompl $RADIUS_DIR/$TEMP_CACERT
            if [ $? != 0 ]; then
                $ECHO "Operation cancelled."
                $RM $RADIUS_DIR/$TEMP_CACERT 2> /dev/null
                if [ "$userInput" != "$RADIUS_CACERT_FILE" ]; then
            	    $RM $RADIUS_DIR/$userInput 2> /dev/null
                	exit 1
				fi
            fi

			if [ "$CAFlag" == "client" ]; then
				$CAT $RADIUS_DIR/$TEMP_CACERT >> $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE
				$RM $RADIUS_DIR/$userInput 2> /dev/null
				/fabos/cliexec/config save $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE
			else
	            $CAT $RADIUS_DIR/$TEMP_CACERT >> $RADIUS_DIR/$RADIUS_CACERT_FILE
	            # As the certificate is appended to the RADIUS_CACERT_Fasc    	        # 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 swRADIUSca.pem, then it was getting deleted.
    	        if [ "$userInput" != "$RADIUS_CACERT_FILE" ]; then
        	        $RM $RADIUS_DIR/$userInput 2> /dev/null
            	fi
	            /fabos/cliexec/config save $RADIUS_DIR/$RADIUS_CACERT_FILE
			fi

			$RM $RADIUS_DIR/$TEMP_CACERT 2> /dev/null
			/fabos/cliexec/config save $RADIUS_DIR

			$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr" ""
            $ECHO "Success: $1ed $inputtype $CAFlag CA certificate ["$userInput"]."
		else
			if [ -f $userInput ] && [ ! -s $userInput ]; then
            	$RM -rf $userInput 2> /dev/null
            fi

            copyfromremote

		    if [ $swbd == "SWBD117" ]; then
		        validateSelfSigned
		    fi

			if [ ! -s $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE ]; then
				$ECHO "Error: CA certificate not found, please import the CA certificate"
                $RM $RADIUS_DIR/$userInput 2> /dev/null
		if [[ -z $restCaller ]]; then
                	exit 1
		else
			exit 16
		fi
			fi

			if [ "$AuditLogMode" == "Strict" ]; then
				#Commenting out CC Mandates for RADIUS
				#Add '-CC_check' flag under verify when uncommenting to validate CC constraints
				#output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE -purpose sslclient $RADIUS_DIR/$userInput 2> /dev/null`
				output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE $RADIUS_DIR/$userInput 2> /dev/null`
			else
				output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE $RADIUS_DIR/$userInput 2> /dev/null`
			fi
            check=`$ECHO "$output" | $AWK ' {print $2} '`
   	        if [ "$check" != "OK" ]; then
       	        printError
           	    #$ECHO "Please import CA certificate or check the validity before importing switch certificate."
				$RM $RADIUS_DIR/$userInput 2> /dev/null
   	            exit 1
       	    fi

			#Verify common name against IP address or hostname
			#Commenting out CC Mandates for RADIUS
			#Add '-CC_check' flag under verify when uncommenting to validate CC constraints
			#if [ "$AuditLogMode" == "Strict" ]; then
			#	fqdn_get
			#	output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE -verify_hostname "$fqdnval" -verify_host_ip "$switchIp" $RADIUS_DIR/$userInput 2> /dev/null`
    	        #check=`$ECHO "$output" | $AWK ' {print $2} '`
        	#    if [ "$check" != "OK" ]; then
		#			printError
   		#            $RM $RADIUS_DIR/$userInput 2> /dev/null
       		#        exit 1
		#		fi
		#	fi

		#OCSP Revocation Check Validation
		#Commenting out CC Mandates for RADIUS
		#Add '-CC_check' flag under verify when uncommenting to validate CC constraints
		#if [ "$AuditLogMode" == "Strict" ]; then
		#	output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE -ocsp_check $RADIUS_DIR/$userInput 2> /dev/null`
		#        check=`$ECHO "$output" | $AWK ' {print $2} '`
		#	no_url=`$ECHO "$output" | $GREP -c "unable to find OCSP responder url"`
		#	if [ $no_url -eq 1 ]; then
		#		check="OK"
		#	fi
	   	#        if [ "$check" != "OK" ]; then
	       	#	        printError
		#   	        $RM $RADIUS_DIR/$userInput 2> /dev/null
		#           	exit 1
		#        fi
		#fi

            # Certificate compliance wimh FIPs mode
            checkForFIPsCompl $RADIUS_DIR/$userInput
            if [ $? != 0 ]; then
             	$ECHO "Operation cancelled."
                $RM $RADIUS_DIR/$userInput 2> /dev/null
                exit 1
            fi

            # validate the certificate by comparing with private key and csr of the switch
            certPvtKeyValidate $1

			$CAT $RADIUS_DIR/$userInput >> $RADIUS_DIR/$RADIUS_SWCERT_FILE
            if [ "$userInput" != "$RADIUS_SWCERT_FILE" ]; then
                $RM $RADIUS_DIR/$userInput 2> /dev/null
            fi

            setDefaultContext

			/fabos/cliexec/config save $RADIUS_DIR/$RADIUS_SWCERT_FILE
            /fabos/cliexec/config save $RADIUS_DIR

            if [ $VID != -1 ]; then
                setcontext $VID
            fi
			$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr" ""
            $ECHO "Success: $1ed $inputtype switch certificate ["$userInput"]."
		fi
	elif [ "$inputtype" == "$LDAP" ]; then
	    if [ ! -e "$LDAP_DIR" ]; then
    	    mkdir -p $LDAP_DIR
        fi
        cd $LDAP_DIR

		if [ "$impreq" == "CA" ]; then
			copyfromremote
    	    cLen=`expr length $userInput`
	        let dotIndex="$cLen"-3
		    fileSuffix=`expr substr $userInput $dotIndex $cLen`
           	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 2> /dev/null
			if [[ -z $restCaller ]]; then
	                	exit 1
			else
				exit 17
			fi
                fi
			else
    	        #validate the file format
        	    $OPENSSL_CMD x509 -in $userInput -inform PEM -outform DER -out $LDAP_DIR/$userInput.der > /dev/null 2>&1
                if [ $? != 0 ]; then
               	    $ECHO "Bad format certificate. Exiting.."
                   	$RM $LDAP_DIR/$userInput
			if [[ -z $restCaller ]]; then
	                	exit 1
			else
				exit 12
			fi
    	        fi
        	    if [ -f $LDAP_DIR/$userInput.der ]; then
                    $RM $LDAP_DIR/$userInput.der 2> /dev/null
	            fi
    	        $CAT $LDAP_DIR/$userInput >  $LDAP_DIR/$TEMP_CACERT
        	fi

		#Check valid CA certificate or not
		#Commenting out CC Mandates for LDAP
		#Add '-CC_check' flag under verify when uncommenting to validate CC constraints
	    	#	if [ "$AuditLogMode" == "Strict" ]; then
	    	#    $OPENSSL_CMD_NO_FIPS x509 -in  $LDAP_DIR/$userInput -text -noout | $GREP -i CA:true > /dev/null 2>&1
		#		caTrue=$?

		#		if [ $caTrue -ne 0 ]; then
		#				$ECHO "Error: Invalid CA certificate"
		#				/fabos/libexec/secnotify cert_validation "invalid CA certificate"
	    	#            $RM $LDAP_DIR/$userInput 2> /dev/null
    	    	#        $RM $LDAP_DIR/$TEMP_CACERT 2> /dev/null
        	#    	    $ECHO "Import failed"
            	#    	exit 1
		#		fi
		#	fi

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

	        # Certificate compliance with FIPs mode
    	    checkForFIPsCompl $LDAP_DIR/$TEMP_CACERT
        	if [ $? != 0 ]; then
            	$ECHO "Operation cancelled."
                $RM $LDAP_DIR/$TEMP_CACERT 2> /dev/null
	            if [ "$userInput" != "$LDAP_CACERT_FILE" ]; then
    	            $RM $LDAP_DIR/$userInput 2> /dev/null
        	    fi
	            exit 1
    	    fi

			if [ "$CAFlag" == "client" ]; then
				$CAT $LDAP_DIR/$TEMP_CACERT >> $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE
				$RM $LDAP_DIR/$userInput 2> /dev/null
				/fabos/cliexec/config save $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE
			else
				certpkey="BRCD_LDAP_1"
	       	    $CAT $LDAP_DIR/$TEMP_CACERT >> $LDAP_DIR/$LDAP_CACERT_FILE
		        # 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" != "$LDAP_CACERT_FILE" ]; then
        	   	    $RM $LDAP_DIR/$userInput 2> /dev/null
	        	fi
	
				/fabos/cliexec/config save $LDAP_DIR/$LDAP_CACERT_FILE
			fi

			$RM $LDAP_DIR/$TEMP_CACERT 2> /dev/null
			/fabos/cliexec/config save $LDAP_DIR

			$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr" "$certpkey"
            $ECHO "Success: $1ed $inputtype $CAFlag CA certificate ["$userInput"]."
		else
            if [ -f $userInput ] && [ ! -s $userInput ]; then
                $RM -rf $userInput 2> /dev/null
            fi

            copyfromremote

		    if [ $swbd == "SWBD117" ]; then
		        validateSelfSigned
		    fi

            if [ ! -s $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE ]; then
                $ECHO "Error: CA certificate not found, please import the CA certificate"
                $RM $LDAP_DIR/$userInput 2> /dev/null
		if [[ -z $restCaller ]]; then
                	exit 1
		else
			exit 16
		fi
            fi

			if [ "$AuditLogMode" == "Strict" ]; then
	    			#Commenting out CC Mandates for LDAP
				#Add '-CC_check' flag under verify when uncommenting to validate CC constraints
				#output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE -purpose sslclient $LDAP_DIR/$userInput 2> /dev/null`
				output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE $LDAP_DIR/$userInput 2> /dev/null`
			else
				output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE $LDAP_DIR/$userInput 2> /dev/null`
			fi
            check=`$ECHO "$output" | $AWK ' {print $2} '`
   	        if [ "$check" != "OK" ]; then
       	        printError
           	    #$ECHO "Please import CA certificate or check the validity before importing switch certificate."
                $RM $LDAP_DIR/$userInput 2> /dev/null
   	            exit 1
			fi

			#Verify common name against IP address or hostname
			#Commenting out CC Mandates for LDAP
			#Add '-CC_check' flag under verify when uncommenting to validate CC constraints
			#if [ "$AuditLogMode" == "Strict" ]; then
			#	fqdn_get
	            #output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE -verify_hostname "$fqdnval" -verify_host_ip "$switchIp" $LDAP_DIR/$userInput 2> /dev/null`
    	        #check=`$ECHO "$output" | $AWK ' {print $2} '`
        	#    if [ "$check" != "OK" ]; then
		#			printError
		#			$RM $LDAP_DIR/$userInput 2> /dev/null
   	    	#        exit 1
	        #    fi
		#	fi

		
		#OCSP Revocation Check Validation
		#Commenting out CC Mandates for LDAP
		#Add '-CC_check' flag under verify when uncommenting to validate CC constraints
		#if [ "$AuditLogMode" == "Strict" ]; then
		#	output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE -ocsp_check $LDAP_DIR/$userInput 2> /dev/null`
		#        check=`$ECHO "$output" | $AWK ' {print $2} '`
		#	no_url=`$ECHO "$output" | $GREP -c "unable to find OCSP responder url"`
		#	if [ $no_url -eq 1 ]; then
		#		check="OK"
		#	fi
	   	#        if [ "$check" != "OK" ]; then
	       	#	        printError
		#   	        $RM $LDAP_DIR/$userInput 2> /dev/null
		#           	exit 1
		#        fi
		#fi

            # Certificate compliance wimh FIPs mode
            checkForFIPsCompl $LDAP_DIR/$userInput
            if [ $? != 0 ]; then
                $ECHO "Operation cancelled."
                $RM $LDAP_DIR/$userInput 2> /dev/null
                exit 1
            fi

            # validate the certificate by comparing with private key and csr of the switch
            certPvtKeyValidate $1

            $CAT $LDAP_DIR/$userInput >> $LDAP_DIR/$LDAP_SWCERT_FILE
            if [ "$userInput" != "$LDAP_SWCERT_FILE" ]; then
                $RM $LDAP_DIR/$userInput 2> /dev/null
            fi

            setDefaultContext

			/fabos/cliexec/config save $LDAP_DIR/$LDAP_SWCERT_FILE
			/fabos/cliexec/config save $LDAP_DIR

            if [ $VID != -1 ]; then
                setcontext $VID
            fi
			$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr" ""
            $ECHO "Success: $1ed $inputtype switch certificate ["$userInput"]."
		fi
	elif [ "$inputtype" == "$SYSLOG" ]; then
		if [ ! -e "$SYSLOG_DIR" ]; then
        	mkdir -p $SYSLOG_DIR
        fi
        cd $SYSLOG_DIR

		if [ "$impreq" == "CA" ]; then
            fileext=`$ECHO $certFileName | $AWK -F . '{ print $NF }'`
            if [ $fileext != "pem" ]; then
            	$ECHO "error: Only .pem formatted certificate files can be imported."
                exit 3
			fi

			copyfromremote
			if [ $? != 0 ]; then
				$ECHO "error: Certificate import failed. Please check the certificate location and user credentials."
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit 18
				fi
			fi

			#Check valid CA certificate or not
			if [ "$AuditLogMode" == "Strict" ]; then
				checkBasicConstraints $SYSLOG_DIR/$userInput
				caTrue=$?
				if [ $caTrue -ne 0 ]; then
					$ECHO "Error: Invalid CA certificate"
					/fabos/libexec/secnotify cert_validation "invalid CA certificate"
					$RM $SYSLOG_DIR/$userInput 2> /dev/null
					$ECHO "Import failed"
					exit 1
				fi
			fi


            output=`$OPENSSL_CMD_NO_FIPS verify -CC_check -CAfile $SYSLOG_DIR/$userInput $SYSLOG_DIR/$userInput `
            check=`$ECHO "$output" | $AWK ' {print $2} '`
            if [ "$check" != "OK" ] ; then
                printError
                $RM $SYSLOG_DIR/$userInput 2> /dev/null
				$ECHO "Import failed"
                exit 12
            fi

			if [ "$CAFlag" == "server" ]; then
	            # User has imported Syslog CA certificate with .pem extension
				certpkey="BRCD_SYSLOG_1"
				mv $SYSLOG_DIR/$userInput $SYSLOG_DIR/$SYSLOG_CACERT_FILE 2> /dev/null
        	    hashval=`$OPENSSL_CMD x509 -noout -hash -in $SYSLOG_DIR/$SYSLOG_CACERT_FILE`
            	/bin/ln -sf  $SYSLOG_DIR/$SYSLOG_CACERT_FILE $SYSLOG_DIR/$hashval.0
	            $ECHO "$SYSLOG_DIR/$SYSLOG_CACERT_FILE $SYSLOG_DIR/$hashval.0" > $SYSLOG_DIR/$SYSLOG_LINK_HASH
    	        /fabos/cliexec/config save $SYSLOG_DIR/$SYSLOG_CACERT_FILE
        	    /fabos/cliexec/config save $SYSLOG_DIR/$SYSLOG_LINK_HASH
			else
				mv $SYSLOG_DIR/$userInput $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE
				/fabos/cliexec/config save $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE
			fi

			/fabos/cliexec/config save $SYSLOG_DIR
			$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr" "$certpkey"
            $ECHO "Success: $1ed $inputtype $CAFlag CA certificate ["$certFileName"]."
		else
   	        if [ -f $userInput ] && [ ! -s $userInput ]; then
       	        $RM -rf $userInput 2> /dev/null
            fi

			copyfromremote

            if [ $swbd == "SWBD117" ]; then
                validateSelfSigned
            fi

            if [ ! -s $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE ]; then
                $ECHO "Error: CA certificate not found, please import the CA certificate"
                $RM $SYSLOG_DIR/$userInput 2> /dev/null
		if [[ -z $restCaller ]]; then
                	exit 1
		else
			exit 16
		fi
            fi

			if [ "$AuditLogMode" == "Strict" ]; then
				output=`$OPENSSL_CMD_NO_FIPS verify -CC_check -CAfile $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE -purpose sslclient $SYSLOG_DIR/$userInput 2> /dev/null`
			else
				output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE $SYSLOG_DIR/$userInput 2> /dev/null`
			fi
            check=`$ECHO "$output" | $AWK ' {print $2} '`
   	        if [ "$check" != "OK" ]; then
       	        printError
           	    #$ECHO "Please import CA certificate or check the validity before importing switch certificate."
                $RM $SYSLOG_DIR/$userInput 2> /dev/null
   	            exit 1
       	    fi

			if [ "$AuditLogMode" == "Strict" ]; then
				fqdn_get
	            output=`$OPENSSL_CMD_NO_FIPS verify -CC_check -CAfile $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE -verify_hostname "$fqdnval" -verify_host_ip "$switchIp" $SYSLOG_DIR/$userInput 2> /dev/null`
    	        check=`$ECHO "$output" | $AWK ' {print $2} '`
        	    if [ "$check" != "OK" ]; then
					printError
   		            $RM $SYSLOG_DIR/$userInput 2> /dev/null
       			    exit 1
    	        fi
			fi

		
		#OCSP Revocation Check Validation
		if [ "$AuditLogMode" == "Strict" ]; then
			output=`$OPENSSL_CMD_NO_FIPS verify -CC_check -CAfile $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE -ocsp_check $SYSLOG_DIR/$userInput 2> /dev/null`
			check=`$ECHO "$output" | $AWK ' {print $2} '`
			no_url=`$ECHO "$output" | $GREP -c "unable to find OCSP responder url"`
			if [ $no_url -eq 1 ]; then
				check="OK"
			fi
	   	        if [ "$check" != "OK" ]; then
	       		        printError
		   	        $RM $SYSLOG_DIR/$userInput 2> /dev/null
		           	exit 1
		        fi
		fi

            # Certificate compliance wimh FIPs mode
   	        checkForFIPsCompl $SYSLOG_DIR/$userInput
       	    if [ $? != 0 ]; then
           	    $ECHO "Operation cancelled."
               	$RM $SYSLOG_DIR/$userInput 2> /dev/null
                exit 1
   	        fi

       	    # validate the certificate by comparing with private key and csr of the switch
           	certPvtKeyValidate $1

            $CAT $SYSLOG_DIR/$userInput >> $SYSLOG_DIR/$SYSLOG_SWCERT_FILE
            if [ "$userInput" != "$SYSLOG_SWCERT_FILE" ]; then
                $RM $SYSLOG_DIR/$userInput 2> /dev/null
            fi

	     if [ "$AuditLogMode" == "Strict" ]; then
            	$CAT $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE >> $SYSLOG_DIR/$SYSLOG_SWCERT_FILE
	     fi
	
  	        setDefaultContext

			/fabos/cliexec/config save $SYSLOG_DIR/$SYSLOG_SWCERT_FILE
       	    /fabos/cliexec/config save $SYSLOG_DIR

       		if [ $VID != -1 ]; then
   	    	    setcontext $VID
   	        fi
			$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr" ""
            $ECHO "Success: $1ed $inputtype switch certificate ["$userInput"]."
		fi
		elif [ "$inputtype" == "$KAFKA" ]; then
			if [ ! -e "$KAFKA_DIR" ]; then
	        	mkdir -p $KAFKA_DIR
	        fi
	        cd $KAFKA_DIR
			
			if [ "$impreq" == "CA" ]; then
	            fileext=`$ECHO $certFileName | $AWK -F . '{ print $NF }'`
	            if [ $fileext != "pem" ]; then
	            	$ECHO "error: Only .pem formatted certificate files can be imported."
	                exit 12
				fi
	
				#Validate the file format
        	    $OPENSSL_CMD x509 -in $TMP_DIR/$userInput -inform PEM -outform DER -out $TMP_DIR/$userInput.der > /dev/null 2>&1
                if [ $? != 0 ]; then
               	    $ECHO "Bad format certificate. Exiting.."
               	    if [ -f $TMP_DIR/$userInput ]; then 
                   		$RM $TMP_DIR/$userInput
                   	fi
                   	
					if [[ -z $restCaller ]]; then
	                	exit 1
					else
						exit 12
					fi
    	        fi
        	    if [ -f $TMP_DIR/$userInput.der ]; then
                    $RM $TMP_DIR/$userInput.der 2> /dev/null
	            fi	           

				# Validate new certificate
	            output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $TMP_DIR/$userInput $TMP_DIR/$userInput `
	            check=`$ECHO "$output" | $AWK ' {print $2} '`
	            if [ "$check" != "OK" ] ; then
	                printError
	                $RM $TMP_DIR/$userInput 2> /dev/null
					$ECHO "Import failed"
	                exit 13
	            fi
	
		        # Delete previous Kafka certificate if it exists AFTER successful validation of new cert
				if [ -s $KAFKA_DIR/$KAFKA_CACERT_FILE ]; then
			       	$ECHO "About to delete $inputtype $KAFKA_CACERT_FILE file(s)"
			            
					# zeroize before delete
					deleteFiles 0 "$KAFKA_DIR/$KAFKA_CACERT_FILE"
						
					/fabos/cliexec/config save $KAFKA_DIR
					$AUDIT_NOTIFY "$CERT_DELE" "$KAFKA_CACERT_FILE" ""
		        fi
		        
				# Copy over new Kafka CA cert
	            mv $TMP_DIR/$userInput $KAFKA_DIR/$KAFKA_CACERT_FILE
	            
				/fabos/cliexec/config save $KAFKA_DIR/$KAFKA_CACERT_FILE
				/fabos/cliexec/config save $KAFKA_DIR
				$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "" ""
	            $ECHO "Success: $1ed $inputtype $CAFlag CA certificate ["$certFileName"]."
			fi
	elif [ "$inputtype" == "$MGMT" ]; then
		cd $MGMT_DIR
	    if [ -f $userInput ] && [ ! -s $userInput ]; then
            $RM -rf $userInput 2> /dev/null
        fi

        copyfromremote
        if [ $swbd == "SWBD117" ]; then
            validateSelfSigned
        fi

		# Create soft links in HTTPS cert directory. This is to support legacy behavior.
		/bin/ln -sf $MGMT_DIR/$userInput $CERT_DIR/$userInput

		/fabos/cliexec/config save $MGMT_DIR
		/fabos/cliexec/config save $CERT_DIR

		$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr" ""
		$ECHO "Success: $1ed $inputtype certificate ["$userInput"]."

	elif [ "$inputtype" == "$ASC" ]; then
		if [ ! -e "$ASC_DIR" ]; then
			mkdir -p $ASC_DIR
			mkdir -p $ASC_DIR_MNT
		fi

		if [ ! -e "$ASC_DIR_CACERT_CURL" ]; then
			mkdir -p $ASC_DIR_CACERT_CURL
			mkdir -p $ASC_DIR_CACERT_CURL_MNT
		fi


		cd $ASC_DIR


		if [ -f $ASC_DIR/$ASC_CACERT_FILE ]; then
				$ECHO "Please delete the existing certificate in order to import new certficate. Exiting.."
				exit 1
		fi

		copyfromremote

	#Validate self signed or not
		if [ ! -z $userInput ]; then
			output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $ASC_DIR/$userInput $ASC_DIR/$userInput 2> /dev/null`
			check=`$ECHO "$output" | $AWK ' {print $2} '`
			if [ "$check" != "OK" ]; then
				printError
				$RM $ASC_DIR/$userInput 2> /dev/null
				exit 1
			fi
			openssl x509 -in $userInput -issuer | head -1 > /tmp/$userInput.issuer
			openssl x509 -in $userInput -subject | head -1 > /tmp/$userInput.subject
			/bin/sed "s/issuer=//" /tmp/*.issuer > /tmp/$userInput.issuer.tmp
			/bin/mv /tmp/$userInput.issuer.tmp /tmp/$userInput.issuer
			/bin/sed "s/subject=//" /tmp/*.subject > /tmp/$userInput.subject.tmp
			/bin/mv /tmp/$userInput.subject.tmp /tmp/$userInput.subject
			ISSUER=$(echo $(md5sum /tmp/$userInput.issuer) | awk '{print $1}' )
			SUBJECT=$(echo $(md5sum /tmp/$userInput.subject) | awk '{print $1}' )
			if [ $ISSUER = $SUBJECT ]; then
				$ECHO "importing self signed certificate ${userInput}"
				selfsign=1
			fi
			$RM /tmp/$userInput.issuer 2> /dev/null
			$RM /tmp/$userInput.subject 2> /dev/null
		fi

	#Binary to Base64 conversion
		cLen=`expr length $userInput`
		let dotIndex="$cLen"-3
		fileSuffix=`expr substr $userInput $dotIndex $cLen`
		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 $ASC_DIR/$TEMP_ASCCERT_FILE > /dev/null 2>&1

			if [ $? != 0 ]; then
				$ECHO "Failed to convert certificate to .pem"
				$RM $ASC_DIR/$userInput 2> /dev/null
				exit 1
			fi
		else
			#validate the file format
			$OPENSSL_CMD x509 -in $userInput -inform PEM -outform DER -out $ASC_DIR/$userInput.der > /dev/null 2>&1
			if [ $? != 0 ]; then
				$ECHO "Bad format certificate. Exiting.."
				deleteFiles 0 $ASC_DIR/$userInput
				exit 1
			fi
			if [ -f $ASC_DIR/$userInput.der ]; then
				deleteFiles 0 $ASC_DIR/$userInput.der
			fi
			$CAT $ASC_DIR/$userInput >  $ASC_DIR/$TEMP_ASCCERT_FILE
		fi



		#Check valid CA certificate or not
		if [ "$AuditLogMode" == "Strict" ]; then
			checkBasicConstraints $ASC_DIR/$userInput
			caTrue=$?
				if [ $caTrue -ne 0 ]; then
					$ECHO "Error: Invalid CA certificate"
					/fabos/libexec/secnotify cert_validation "invalid CA certificate"
					deleteFiles 0 $ASC_DIR/$userInput
					$ECHO "Import failed"
					exit 1
				fi
		fi



	# Certificate compliance with FIPs mode
		checkForFIPsCompl $ASC_DIR/$userInput
		if [ $? != 0 ]; then
				$ECHO "Operation cancelled."
				deleteFiles 0 $ASC_DIR/$userInput
				deleteFiles 0 $ASC_DIR/$ASC_TEMP_FILE
				exit 1
		fi


		if [ -f $ASC_DIR/$TEMP_ASCCERT_FILE ]; then
				deleteFiles 0 $ASC_DIR/$userInput
				$CAT $ASC_DIR/$TEMP_ASCCERT_FILE > $ASC_DIR/$ASC_CACERT_FILE
				deleteFiles 0 $ASC_DIR/$TEMP_ASCCERT_FILE
		fi

	# Create ca-active.pem and copy the imported certificate.
		if [ -f $ASC_DIR/$ASC_CACERT_FILE ]; then
				$CAT $ASC_DIR/$ASC_CACERT_FILE > $ASC_DIR_CACERT_CURL/$ASC_CACERT_ACT_FILE
	# To-Do : Add support here when more than one ca is imported	
		#		$CAT $ASC_DIR/$ASC_CACERT_FILE >> $ASC_DIR_CACERT_CURL/$ASC_CACERT_ACT_FILE
		fi

		setDefaultContext

		/fabos/cliexec/config save $ASC_DIR/$ASC_CACERT_FILE
		/fabos/cliexec/config save $ASC_DIR_CACERT_CURL/$ASC_CACERT_ACT_FILE
		/fabos/cliexec/config save $ASC_DIR_CACERT_CURL
		/fabos/cliexec/config save $ASC_DIR
		/fabos/cliexec/config update

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

		if [ $selfsign -eq 1 ]; then
			$ECHO "Success: imported self signed certificate ["$userInput"]."
			$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "self signed certificate" "" "$ipAddr" ""
			selfsign=0
		else
			$ECHO "Success: $1ed $inputtype $CAFlag CA certificate ["$userInput"]."
			$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "CA certificate" "" "$ipAddr" ""
		fi

		$WEBLNOTIFY $ASC:$CERT_IMPORT
		#$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "" ""

	elif [ "$inputtype" == "$EXTN" ]; then

      #certFileName/userInput is remote dir file name
      #certpkey is filename as per our naming convention

      oldFile=""
		#Check if file already exists.
      if [ $extnLocalSwCert -eq 1 ]; then
			oldFile=`$LS ${EXTN_DIR}/*.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
      elif [ $extnRemoteSwCert -eq 1 ]; then
         oldFile=`$LS ${EXTN_DIR}/${userInput}.nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
      elif [ $extnCaCert -eq 1 ]; then
         oldFile=`$LS ${EXTN_DIR}/${userInput}.${EXTN_CACERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
      fi

      if [ "$oldFile" != "" ]; then
         $ECHO "WARNING!!!"
         if [ $extnLocalSwCert -eq 1 ]; then
            extnLocalReimport=1
            $ECHO "Certificate for keypair_tag \"${keypair}\" already exists."
            $ECHO
            $ECHO "Override of a certificate can bring down the IKE session and tunnel associated with this keypair_tag." 
				$ECHO "Please make sure the same certificate has been imported on the peer switch."
				$ECHO "In case of any failure, please try \"portcfg ipsec-policy restart\""
            $ECHO
            $ECHO -n "Do you want to override with new certificate: (yes, y, no, n) [no] "
         elif [ $extnRemoteSwCert -eq 1 ]; then
            $ECHO "$userInput already exists." 
            $ECHO
				$ECHO "Please make sure the same certificate has been imported on the peer switch."
				$ECHO "In case of any failure, please try \"portcfg ipsec-policy restart\""
            $ECHO
            $ECHO -n "Do you want to override with new certificate: (yes, y, no, n) [no] "
         else
            $ECHO "$userInput already exists." 
            $ECHO
            $ECHO -n "Do you want to override with new certificate: (yes, y, no, n) [no] "
         fi
         read response
         resp=`$ECHO $response | tr "[:lower:]" "[:upper:]"`
         if [ "$resp" == "N" -o "$resp" == "NO" ]; then
            exit 1
         elif [ "$resp" == "Y" -o "$resp" == "YES" ]; then
            if [ $extnLocalSwCert -eq 1 ]; then 
	            $ECHO "Deleting existing $impreq for keypair_tag ${keypair}"
            else
	            $ECHO "Deleting existing $impreq $userInput"
			   fi
            $RM -f $oldFile 2> /dev/null
            $RM -f "${oldFile}.hash" 2> /dev/null
         else
            $ECHO "Invalid input. Certificate file not imported."
            exit 1
          fi
      fi

      if [ $extnLocalSwCert -eq 1 ]; then
         if [ ! -e "$EXTN_DIR" ]; then
            mkdir -p $EXTN_DIR
         fi
         cd $EXTN_DIR
         certpkey="${userInput}.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}"
      elif [ $extnRemoteSwCert -eq 1 ]; then
         if [ ! -e "$EXTN_DIR" ]; then
            mkdir -p $EXTN_DIR
         fi
         cd $EXTN_DIR
         certpkey="${userInput}.nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}"
      elif [ $extnCaCert -eq 1 ]; then
         if [ ! -e "$EXTN_DIR" ]; then
            mkdir -p $EXTN_DIR
         fi
         cd $EXTN_DIR
         certpkey="${userInput}.${EXTN_CACERT_FILE_EXT}${PEM_SUFFIX}"
      fi

		copyfromremote

		if [ $extnLocalSwCert -eq 1 ] || [ $extnRemoteSwCert -eq 1 ]; then
			#Check if switch cert begins with FCAP_CERT_HEADER and ends with FCAP_CERT_FOOTER 
			#and is without text
			if [ "`awk 'NR==1;' "${EXTN_DIR}/${certpkey}"`" != "$FCAP_CERT_HEADER" ] ||
				[ "`awk 'END{print};' "${EXTN_DIR}/${certpkey}"`" != "$FCAP_CERT_FOOTER" ]; then
				$ECHO "Certificate in bad format."
				$RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
				exit 1;
			fi
		elif [ $extnCaCert -eq 1 ]; then
			# Check if CA chain certificates have correct header and footer.
			countAndValidateCertificates $EXTN_DIR/$certpkey
			return_val_imported_file=$?
			if [ $return_val_imported_file -eq -1 ]; then
				$RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
				exit 1;
			fi
		fi

		# validation with pvt key and csr for local switch certs
      if [ $extnLocalSwCert -eq 1 ]; then
         certPvtKeyValidate
		fi
	
		# verify cert with CA chain 
		# for CA cert, it will also verify if chain any
		if [ $selfSignedCert -eq 1 ] || [ $extnCaCert -eq 1 ]; then
			CAfileExtn="${EXTN_DIR}/${certpkey}"	
		else
      	CAfileExtn="${CAfile}.${EXTN_CACERT_FILE_EXT}${PEM_SUFFIX}"

			# Check if CA file is present
			if [ ! -s $CAfileExtn ]; then
				$ECHO "Error: CA certificate [$CAfile] not found, please import the CA certificate"
				$RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
				exit 1
			fi

		fi

		output=`$OPENSSL_CMD_NO_FIPS verify -suiteB_192 -check_ss_sig -x509_strict \
			-CAfile $CAfileExtn ${EXTN_DIR}/${certpkey} 2> /dev/null`
		check=`$ECHO "$output" | $AWK ' {print $2} '`
		if [ "$check" != "OK" ]; then
			# OpenSSL error indicates the depth and reason for verify failure.
			# we will interpret the depth value and display if the switch or CA certificate has the error.
			# printError routine will display the reason for verify failure
			if [ $selfSignedCert -eq 1 ]; then
				$ECHO -n "Switch Certificate [$userInput] "
			elif [ $extnCaCert -eq 1 ]; then
				$ECHO -n "CA Certificate [$userInput] "
			else
				depth=`$ECHO $output | $SED 's/^.*error\ [0-9]*\ at\ //g' |$AWK ' {print \$1} '`
				if [ "$depth" == 0 ]; then
					$ECHO -n "Switch Certificate [$userInput] "
				else
					$ECHO -n "CA Certificate [$CAfile] "
				fi
			fi
			printError
			$RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
			exit 1
		fi

		#Store hash of the file in new file filename.hash
		hash=`$OPENSSL_CMD_NO_FIPS dgst -r -sha1 "${EXTN_DIR}/${certpkey}" 2> /dev/null`
		if [ $? -eq 0 ]; then
			$ECHO $hash | cut -d ' ' -f 1 > "${EXTN_DIR}/${certpkey}.hash" 2> /dev/null
		else
			$ECHO "Failed cannot be imported because hash calculation failed."
			$RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
			exit 1
		fi
      
		/fabos/cliexec/config save "${EXTN_DIR}/${certpkey}"
		/fabos/cliexec/config save "${EXTN_DIR}/${certpkey}.hash"
		
		$ECHO "Success: $1ed $inputtype $impreq ["$userInput"]."
     
      if [ $extnLocalReimport -eq 1 ]; then
			output=`$ESMCMD op update local cert "$oldFile"`
			if [ "$output" != "Operation Succeeded" ] ; then
				$ECHO "Import success but failed to apply the new certificate configuration for the IPsec tunnel,"
				$ECHO "Error: \"$output\""
			fi
		fi	
 
	else
        cd $CERT_DIR
        if [ -f $userInput ] && [ ! -s $userInput ]; then
            $RM -rf $userInput 2> /dev/null
        fi

		copyfromremote

		if [ "$impreq" == "CA" ]; then
        	cLen=`expr length $userInput`
   		    let dotIndex="$cLen"-3
    	    fileSuffix=`expr substr $userInput $dotIndex $cLen`
			certname="$CA_CERT"

			if [ "$fileSuffix" == "$PEM_SUFFIX" ]; then
                $OPENSSL_CMD x509 -in $CERT_DIR/$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 2> /dev/null
			if [[ -z $restCaller ]]; then
	               	   exit 1
			else
				exit 13
			fi
                fi
   		        $RM $TMP_DIR/$userInput.der 2> /dev/null
			fi

            #Check valid CA certificate or not
			if [ "$AuditLogMode" == "Strict" ]; then
                                checkBasicConstraints $CERT_DIR/$userInput
                                caTrue=$?

				if [ $caTrue -ne 0 ]; then
						$ECHO "Error: Invalid CA certificate"
						/fabos/libexec/secnotify cert_validation "invalid CA certificate"
    	            	$RM $CERT_DIR/$userInput 2> /dev/null
	        	        $ECHO "Import failed"
        	    	    exit 1
				fi
			fi

            output=`$OPENSSL_CMD_NO_FIPS verify -CC_check -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 2> /dev/null
				$ECHO "Import failed"
                exit 1
            fi
		else
			certname="$SWITCH_CERT"
		    setDefaultContext
		    VID=$?

			httpsCaCert=`/fabos/cliexec/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 2> /dev/null
		if [[ -z $restCaller ]]; then
	        	exit 1
		else
			exit 16
		fi
            else
				if [ "$AuditLogMode" == "Strict" ]; then
					output=`$OPENSSL_CMD_NO_FIPS verify -CC_check -CAfile $CERT_DIR/$httpsCaCert -purpose sslserver $CERT_DIR/$userInput 2> /dev/null`
				else
					output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $CERT_DIR/$httpsCaCert $CERT_DIR/$userInput 2> /dev/null`
				fi
                check=`$ECHO "$output" | $AWK ' {print $2} '`
   	            if [ "$check" != "OK" ]; then
       		        printError
           	        $RM $CERT_DIR/$userInput 2> /dev/null
                   	exit 1
                fi

				if [ "$AuditLogMode" == "Strict" ]; then
					fqdn_get
					output=`$OPENSSL_CMD_NO_FIPS verify -CC_check -CAfile $CERT_DIR/$httpsCaCert -verify_hostname "$fqdnval" -verify_host_ip "$switchIp" $CERT_DIR/$userInput 2> /dev/null`
	                check=`$ECHO "$output" | $AWK ' {print $2} '`
    	            if [ "$check" != "OK" ]; then
						printError
                    	$RM $CERT_DIR/$userInput 2> /dev/null
    	                $ECHO "Import failed"
   	    	            exit 1
            	    fi
				fi

		#OCSP Revocation Check Validation
		if [ "$AuditLogMode" == "Strict" ]; then
			output=`$OPENSSL_CMD_NO_FIPS verify -CC_check -CAfile $CERT_DIR/$httpsCaCert -ocsp_check $CERT_DIR/$userInput 2> /dev/null`
		        check=`$ECHO "$output" | $AWK ' {print $2} '`
			no_url=`$ECHO "$output" | $GREP -c "unable to find OCSP responder url"`
			if [ $no_url -eq 1 ]; then
				check="OK"
			fi
	   	        if [ "$check" != "OK" ]; then
	       		        printError
		   	        $RM $CERT_DIR/$userInput 2> /dev/null
		           	exit 1
		        fi
		fi

            fi
		fi

        # Certificate compliance wimh FIPs mode
        checkForFIPsCompl $CERT_DIR/$userInput
   	    if [ $? != 0 ]; then
       	    $ECHO "Operation cancelled."
           	$RM $CERT_DIR/$userInput 2> /dev/null
            exit 1
        fi

		if [ "$impreq" == "CERT" ]; then
            if [ $swbd == "SWBD117" ]; then
                validateSelfSigned
            fi

            # validate the certificate by comparing with private key and csr of the switch
			certPvtKeyValidate $1
		fi

		setDefaultContext
		
		if [ "$certname" != "$userInput" ]; then
			$CP $CERT_DIR/$userInput $CERT_DIR/$certname 2> /dev/null
			$RM -f $CERT_DIR/$userInput 2> /dev/null
		fi
		if [ "$AuditLogMode" == "Strict" ]; then
			if [ "$impreq" == "CERT" ]; then
				$CAT $CERT_DIR/$httpsCaCert >> $CERT_DIR/$certname
			fi
		
		fi

		/fabos/cliexec/config save $CERT_DIR/$certname
		/fabos/cliexec/config save $CERT_DIR

        if [ $VID != -1 ]; then
            setcontext $VID
   	    fi
       	$ECHO "Success: $1ed $inputtype certificate ["$userInput"]."
	fi

	if [ $extn -eq 1 ]; then
		$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr" ""
	fi
}

certExport() {
		ROOT_CA_SUFFIX="fcapRootCA.pem"
		fcapswcsr="fcapSw.csr"
 		fcapCAFileName=$switchIp$ROOT_CA_SUFFIX
		commonCAFileName=$switchIp$COMMONCERT_CA_SUFFIX
		SWCsr=$switchIp$SW_CSR_SUFFIX
		commonSWCsr=$switchIp$COMMON_SW_CSR_SUFFIX
		certpkey=""

    if [ "$expreq" == "CA" ]; then
		if [ "$inputtype" == "$FCAPS" ]; then
			cd $FCAP_DIR
            if [ ! -s $FCAP_DIR/$FCAP_CACERT_FILE ]; then
				$ECHO "$inputtype $expreq file does not exist."
                exit 1
            fi
			
			if [ $commoncert -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 [ "$inputtype" == "$RADIUS" ]; then
			cd $RADIUS_DIR
			if [ "$CAFlag" == "server" ]; then
	            certFileName=$RADIUS_CACERT_FILE
			else
				certFileName=$RADIUS_CLIENT_CACERT_FILE
			fi

	    elif [ "$inputtype" == "$LDAP" ]; then
			cd $LDAP_DIR
			if [ "$CAFlag" == "server" ]; then
	            certFileName=$LDAP_CACERT_FILE
			else
				certFileName=$LDAP_CLIENT_CACERT_FILE
			fi
		elif [ "$inputtype" == "$SYSLOG" ]; then
			cd $SYSLOG_DIR
			if [ "$CAFlag" == "server" ]; then
				certFileName=$SYSLOG_CACERT_FILE
			else
				certFileName=$SYSLOG_CLIENT_CACERT_FILE
			fi
		elif [ "$inputtype" == "$EXTN" ]; then
			certpkey=`$LS ${EXTN_DIR}/${certFileName}.${EXTN_CACERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
		else
			cd $CERT_DIR
			setDefaultContext
			VID=$?
            certFileName=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`
			if [ $VID != -1 ];then
			    setcontext $VID
			fi
            $ECHO "$certFileName" | $GREP '/' >/dev/null 2>&1
            if [ "$certFileName" == "none" ]; then
				$ECHO "$inputtype $expreq file does not exist."
                exit 1
            fi
		fi
	elif [ "$expreq" == "CERT" ]; then
		if [ "$inputtype" == "$FCAPS" ]; then
			cd $FCAP_DIR
	        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
			if [ -s $FCAP_DIR/$FCAP_TOUCH_FILE ]; then
	            $CAT $FCAP_DIR/$FCAP_TOUCH_FILE > $FCAP_DIR/$certFileName
			else
				$ECHO "$inputtype $expreq file does not exist."
				exit 1
			fi
        elif [ "$inputtype" == "$RADIUS" ]; then
            cd $RADIUS_DIR
            certFileName=$RADIUS_SWCERT_FILE
        elif [ "$inputtype" == "$LDAP" ]; then
			cd $LDAP_DIR
            certFileName=$LDAP_SWCERT_FILE
        elif [ "$inputtype" == "$SYSLOG" ]; then
            cd $SYSLOG_DIR
            certFileName=$SYSLOG_SWCERT_FILE
        elif [ "$inputtype" == "$EXTN" ]; then
            if [ $extnLocalSwCert -eq 1 ]; then
                certpkey=`$LS ${EXTN_DIR}/${certFileName}.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
            elif [ $extnRemoteSwCert -eq 1 ]; then
                certpkey=`$LS ${EXTN_DIR}/${certFileName}.nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
            fi
		elif [ "$inputtype" == "$MGMT" ]; then
			cd $MGMT_DIR
        else
			cd $CERT_DIR
            if [ -z "$certFileName" ]; then
                setDefaultContext
                VID=$?
                certFileName=`/fabos/cliexec/config get $CERTCONFIG 5`
                if [ $VID != -1 ]; then
                    setcontext $VID
                fi
                $ECHO "$certFileName" | $GREP '/' >/dev/null 2>&1
                if [ "$certFileName" == "none" ]; then
					$ECHO "$inputtype $expreq file does not exist."
                    exit 1
                fi
            fi

        fi
	else
		if [ "$inputtype" == "$FCAPS" ]; then
			cd $FCAP_DIR
            if [ $commoncert -eq 1 ]; then
                $CAT $FCAP_DIR/$FCAP_SWCSR_FILE > $FCAP_DIR/$commonSWCsr
   	            certFileName=$commonSWCsr
            else
	            $CAT $FCAP_DIR/$FCAP_SWCSR_FILE > $FCAP_DIR/$switchIp$fcapswcsr
    	        certFileName=$switchIp$fcapswcsr
            fi
		elif [ "$inputtype" == "$RADIUS" ]; then
			cd $RADIUS_DIR
			certFileName=$SWCsr
		elif [ "$inputtype" == "$LDAP" ]; then
			cd $LDAP_DIR
			certFileName=$SWCsr
		elif [ "$inputtype" == "$SYSLOG" ]; then
			cd $SYSLOG_DIR
			certFileName=$SWCsr
		elif [ "$inputtype" == "$EXTN" ]; then
         if [ "$keypair" != "" ]; then
            certFileName="${keypair}${CSR_SUFFIX}"
         fi
         certpkey="${EXTN_DIR}/${certFileName}"
		else
			cd $CERT_DIR
			certFileName=$SWCsr
		fi
	fi

	if [ $extn -eq 1 ]; then
		if [ ! -s "$certpkey" ]; then
			$ECHO "Specified $inputtype $expreq file does not exist."
			exit 1
		fi
	else	
		if [ ! -s "$certFileName" ]; then
			$ECHO "$inputtype $expreq file does not exist."
			exit 1
		fi
	fi

	if [ $extn -eq 1 ]; then
		exportFilePath="${EXTN_DIR}/${exportFile}"
	else
		exportFilePath="${FCAP_DIR}/${exportFile}"
	fi

	if [ ! -f "$exportFilePath" ]; then
		$CAT /dev/null > "${exportFilePath}"
	fi

	flag=0

	if [ "$protocol" == "$PROT_FTP" ]; then
		if [ $extn -eq 1 ]; then
			#Since we have internal naming convention for certs, but we need to export
			#with original name and ftp doesnt allow to specify destination file name,
			#So copy to file with original file name and delete after ftp.
			if [ "$expreq" == "CA" ] || [ "$expreq" == "CERT" ]; then
				$CP $certpkey ${EXTN_DIR}/${certFileName} 2> /dev/null
			fi	
			/bin/ncftpput -t 60 -u $userName -p $password1 $ipAddr \
			$remoteDir ${EXTN_DIR}/${certFileName} 2> ${exportFilePath}
			flag=$?
			#Delete above created file.
			if [ "$expreq" == "CA" ] || [ "$expreq" == "CERT" ]; then
				$RM -f ${EXTN_DIR}/${certFileName} 2> /dev/null
			fi	
		else
			/bin/ncftpput -t 60 -u $userName -p $password1 $ipAddr \
			$remoteDir ./$certFileName 2> ${exportFilePath}
			flag=$?
			
		fi
	else
		if [ $extn -eq 1 ]; then
			/usr/bin/scp -q -oStrictHostKeyChecking=no \
				$certpkey $userName@\[$ipAddr\]:$remoteDir/$certFileName 2> ${exportFilePath}
		else
			if [[ ! -z $restCaller ]]; then
				/usr/bin/scp -q -oStrictHostKeyChecking=no -oSSHPassword=$password1 \
					./$certFileName $userName@\[$ipAddr\]:$remoteDir 2> ${exportFilePath}
			else
				/usr/bin/scp -q -oStrictHostKeyChecking=no ./$certFileName \
				$userName@\[$ipAddr\]:$remoteDir 2> ${exportFilePath}
			fi
		fi
		flag=$?
	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 ${exportFilePath}`
	if [ "$protocol" == "$PROT_FTP" ]; then
		if [ -f "${exportFilePath}" ]; then
			if [ "$output" != "" ] && [ "$flag" -eq 0 ]; then
				IFS_=${IFS}; IFS=$'\n'
				for LINE in `$CAT $exportFilePath`; 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 == 0 ]; then
		$AUDIT_NOTIFY "$CERT_EXPORT" "$certFileName" "$ipAddr"
		$ECHO "Success: $1ed $inputtype $expreq $certFileName"
	else
		$ECHO "Failed to $1 $inputtype $expreq to remote host: $ipAddr"
	fi

	if [ "$inputtype" == "$FCAPS" ]; then
		$RM -rf $FCAP_DIR/$certFileName 2> /dev/null
	fi
		
	if [ -f "${exportFilePath}" ]; then
		$RM -rf "${exportFilePath}"
	fi
	if [[ ! -z $restCaller ]] && [ $flag != 0 ]; then
		exit 20 # Handle scp / ftp error for rest
	fi
}

#
# Reset all parameters for SSL and notify applications
#
resetSSLState() {

	if [[ "$delall" != "noca" ]]; then
		/fabos/cliexec/config set $ROOTCERTCONFIG 5 none
	fi
	/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
		suiteBCert=0
		sanIpInclude=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

		if [[ ! -z $restCaller ]]; then
		#	echo "csr info " $@
		#	country=`echo $@ | cut -d " " -f 2 | cut -d "," -f 1`
		#	state=`echo $@ | cut -d " " -f 2 | cut -d "," -f 2`
		#	locality=`echo $@ | cut -d " " -f 2 | cut -d "," -f 3`
		#	company=`echo $@ | cut -d " " -f 2 | cut -d "," -f 4`
		#	unit=`echo $@ | cut -d " " -f 2 | cut -d "," -f 5`
		#	cn=`echo $@ | cut -d " " -f 2 | cut -d "," -f 6`
		#	sanIpInclude=`echo $@ | cut -d " " -f 2 | cut -d "," -f 7`
			country=`/bin/sed -n '1p' $REST_CSR_INPUT_INFO`
			state=`/bin/sed -n '2p' $REST_CSR_INPUT_INFO`
			locality=`/bin/sed -n '3p' $REST_CSR_INPUT_INFO`
			company=`/bin/sed -n '4p' $REST_CSR_INPUT_INFO`
			unit=`/bin/sed -n '5p' $REST_CSR_INPUT_INFO`
			cn=`/bin/sed -n '6p' $REST_CSR_INPUT_INFO`
			sanIpInclude=`/bin/sed -n '7p' $REST_CSR_INPUT_INFO`
		fi

# 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]"
			return 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"
			return 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
			if [ $extn -eq 1 ]; then
				#common name will be set to keypair_tag to make it unique
				cn="$keypair"
			elif [ "$certtype" == "$FCAPS" ]; then
				cn=`$ECHO "$WWN" | $SED 's/://g'`
			else
				readInput "Common Name (Fully qualified Domain Name, or IP address): "
				cn=$userInput
			fi
		fi
		$ECHO "commonName=$cn" >> $CSR_GEN_INFO

		if [[ -z $restCaller ]] && [[ "$certtype" != "$FCAPS" ]] && [[ $extn -ne 1 ]]; then
			$ECHO;$ECHO -n "Do you want to continue including IP in the SAN? (yes, y, no, n): [no] "
			read response
			if [ "$response" == "" ]; then
				response=no
			fi
			resp=`$ECHO $response | tr "[:lower:]" "[:upper:]"`
			if [ "$resp" == "Y" -o "$resp" == "YES" ]; then
				sanIpInclude=1
			elif [ "$resp" == "N" -o "$resp" == "NO" ]; then
				sanIpInclude=0
			else
				$ECHO "Invalid input. Exiting"
				if [ $extn -eq 0 ]; then
					exit 1
				else
					return 1
				fi
			fi
		fi

		if [ ! -z "$host" ] && [ ! -z "$domain" ] && [ ! -z "$switchIP" ] && [ $extn -ne 1 ]; then
			if [[ "$cn" == *"$host"* ]] && [[ "$cn" == *"$domain"* ]]; then
				version3Certs=1
			else
				$ECHO "Host name or domain name does not match with common name."
				return 1
			fi
		elif [ -z "$host" ] && [ -z "$domain" ] && [ -z "$switchIP" ] && [ $extn -ne 1 ]; then
			version3Certs=0
		elif [ $extn -eq 1 ]; then
			suiteBCert=1;
		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
			return 1
		fi

		$ECHO "" >> $CSR_GEN_INFO
		$ECHO "[ req_attributes ]" >> $CSR_GEN_INFO
#		$ECHO "unstructuredName=$switchIp" >> $CSR_GEN_INFO
		if [ $extn -ne 1 ]; then
			$ECHO "serialNumber=`wwn`" >> $CSR_GEN_INFO
		fi

		$ECHO "" >> $CSR_GEN_INFO
		$ECHO "[ v3_req ]" >> $CSR_GEN_INFO
		if [ $suiteBCert -eq 1 ]; then
			$ECHO "subjectKeyIdentifier=hash" >> $CSR_GEN_INFO
			$ECHO "keyUsage = critical, digitalSignature, nonRepudiation" >> $CSR_GEN_INFO	
		else
			if [ $switchIPv6 != 0 ]; then
				if [ $sanIpInclude -eq 0 ]; then
					$ECHO "subjectAltName=DNS:$cn" >> $CSR_GEN_INFO
				else
					$ECHO "subjectAltName=DNS:$cn, IP:$switchIPv6" >> $CSR_GEN_INFO
				fi
			else
				if [ $version3Certs -eq 1 ]; then
					$ECHO "keyUsage=digitalSignature, keyEncipherment" >> $CSR_GEN_INFO
					$ECHO "extendedKeyUsage=serverAuth, clientAuth" >> $CSR_GEN_INFO
				fi
				if [ $sanIpInclude -eq 0 ]; then
					$ECHO "subjectAltName=DNS:$cn" >> $CSR_GEN_INFO
				else
					$ECHO "subjectAltName=DNS:$cn, IP:$switchIp" >> $CSR_GEN_INFO
				fi
			fi
		fi

		return 0
}

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

	/fabos/cliexec/config set $HTTPFQDN 5 "$alias"
	/fabos/cliexec/config update

    if [ $VID != -1 ];then
	    setcontext $VID
    fi
	if [[ -z $restCaller ]]; then
		$WEBDHANDLER $HTTPFQDN:"$alias"
	fi
}

# Everything triggers of the switch ID and IP.

# Populate the FQDN value
fqdn_get() {
	host_name=`$HOSTNAME`
	domain_name=`$DOMAINNAME`

	fqdnval="$host_name.$domain_name"
}

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 [[ -z $restCaller ]]; then
	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
fi

# Set the openssl binary to be used
setFipsMode

#get the Validation Audit Flag Enabler
AuditLogMode=`/fabos/cliexec/config get $X509_VALIDATION_KEY 5`

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

case "$cmd_option" in

$CERT_EXPORT )

	declare -a cmdargs

	expreq=""
	keypair=""
	inputtype=""
	count=0
	protFlag=0
	typeFlag=0		
	commoncert=0
	filename=""
	certFileName=""
	extn=0
	extnLocalSwCert=0
	extnRemoteSwCert=0
	extnCaCert=0
	extnLocalSwCsr=0
	CAFlag=""
 
	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

        "$CERTSOURCE" )
			if [ $typeFlag -eq 0 ]; then
				expreq="CERT"
				typeFlag=1
			else
				exportUsage
				exit 1
			fi
			;;

        "$CASOURCE" )
			if [ $typeFlag -eq 0 ]; then
				expreq="CA"
				typeFlag=1
			else
				exportUsage
				exit 1
			fi
			;;

        "$CSRSOURCE" )
			if [ $typeFlag -eq 0 ]; then
				expreq="CSR"
				typeFlag=1
			else
				exportUsage
				exit 1
			fi
			;;

        "$CLIENT" )
			if [ "$CAFlag" == "" ]; then
	            CAFlag="client"
			else
				exportUsage
				exit 1
			fi
            ;;

        "$SERVER" )
			if [ "$CAFlag" == "" ]; then
	            CAFlag="server"
            else
                exportUsage
                exit 1
            fi
            ;;

   		"$TAG" )
            count=`expr $count + 1`         
           	keypair=${cmdargs[count]}
            ;;
 
            "$SYSLOG" )
				if [ "$protFlag" -eq 0 ] ; then
					inputtype=${cmdargs[count]}
					protFlag=1
				else
					exportUsage
					exit 1
				fi
            ;;

  			"$FCAPS" )
			if [ "$protFlag" -eq 0 ]; then
				inputtype=${cmdargs[count]}
				protFlag=1
			else
				exportUsage
				exit 1
			fi	
			;;
  
   			"$COMMONCERT" )
				if [ "$protFlag" -eq 0 ]; then
					inputtype="fcap"
					commoncert=1
					protFlag=1
				else
					exportUsage
					exit 1
				fi	
				;;

            "$HTTPS" )
				if [ "$protFlag" -eq 0 ] ; then
					inputtype=${cmdargs[count]}
					protFlag=1
				else
					exportUsage
					exit 1
				fi
            ;;

            "$RADIUS" )
				if [ "$protFlag" -eq 0 ]; then
					inputtype=${cmdargs[count]}
					protFlag=1
				else
					exportUsage
					exit 1
				fi
            ;;

            "$LDAP" )
				if [ "$protFlag" -eq 0 ]; then
					inputtype=${cmdargs[count]}
					protFlag=1
				else
					exportUsage
					exit 1
				fi
            ;;

			"$MGMT" )
                if [ "$protFlag" -eq 0 ]; then
                    inputtype=${cmdargs[count]}
                    protFlag=1
                else
                    exportUsage
                    exit 1
                fi
            ;;

            "$EXTN" )
				if [ "$protFlag" -eq 0 ]; then
					inputtype=${cmdargs[count]}
					extn=1
					protFlag=1
				else
					exportUsage
					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
			;;

	    	* )
			exportUsage
			exit 1
			;;

	    esac
	    count=`expr $count + 1`
	done

    if [ "$expreq" == "" ] || [ "$inputtype" == "" ]; then
        exportUsage
        exit 1
    fi

    if [[ "$keypair" != "" && "$inputtype" != "$EXTN" ]] || [[ "$inputtype" == "$MGMT" && "$expreq" != "CERT" ]]; then
        exportUsage
        exit 1
    fi

    if [ "$CAFlag" != "" ] && [ "$expreq" != "CA" ]; then
		exportUsage
        exit 1
    fi

    if [ "$CAFlag" == "" ] && [[ "$expreq" == "CA" && "$inputtype" != "$EXTN" ]]; then
		exportUsage
        exit 1
    fi

    if [ "$CAFlag" == "client" ] && [ "$inputtype" == "$HTTPS" ]; then
        $ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
        exit 1
    fi

    if [ "$CAFlag" == "server" ] && [ "$inputtype" == "$FCAPS" ]; then
        $ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
	if [ $commoncert -eq 1 ]; then
		$ECHO "Use -client option for $COMMONCERT"
		if [[ ! -z $restCaller ]]; then
			exit $COMMONCERT_NO_SERVER
		fi
	fi
        exit 1
    fi


	if  [ $extn -eq 1 ]; then

		is_extn_platform
		if [ $? -ne 0 ]; then
			$ECHO "This is not supported in non-extension platforms"
			exit 1
		fi

		if [ "$expreq" == "CA" ]; then
			if [ "$certFileName" == "" ]; then
				$ECHO "Export $expreq operation requires certname in this server to be specified"
				exit 1
			fi
			certNameValidate $certFileName
			if [ "$keypair" != "" ]; then
				$ECHO "keypair cannot be specified for $expreq export"
				exit 1
			fi
			extnCaCert=1
		elif [ "$expreq" == "CERT" ]; then
			if [ "$certFileName" == "" ]; then
				$ECHO "Export $expreq operation requires certname in this server to be specified"
				exit 1
			fi
			certNameValidate $certFileName	
			if [ "$keypair" != "" ]; then
				extnLocalSwCert=1
			else
				extnRemoteSwCert=1	
			fi
		elif [ "$expreq" == "CSR" ]; then
			if [ "$certFileName" == "" ] && [ "$keypair" == "" ]; then
				$ECHO "Export $expreq operation requires certname in this server OR keypair to be specified"
				exit 1
			fi
			if [ "$certFileName" != "" ]; then
				csrNameValidate $certFileName	
			fi		
			extnLocalSwCsr=1			
		fi
		
		if [ "$keypair" != "" ]; then
			$ECHO "$keypair" |  $GREP -v "[^a-zA-Z0-9~@%_+:-]" > /dev/null 2>&1
			if [ ! $? -eq 0 ]; then
				$ECHO "Error: keypair_tag must not have unsupported characters," \
					"supported characters are [a-zA-Z0-9~@%_+:-]"
				exit 1
			fi
		fi		

	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 [[ -z $restCaller ]]; then
		if [ "$protocol" == "$PROT_SCP" ] && [ -n "$password1" ]; then
			$ECHO "Don't enter the password in command line for SCP"
			exit 1
		fi
	fi


	promptHostInfo $CERT_EXPORT $expreq $inputtype $keypair
;;

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

	declare -a cmdargs

	count=0
	for arg in "$@"
	do
		cmdargs[$count]=$arg
		count=`expr $count + 1`
	done
	impreq=""
	certConfig=0
	enableHttps=0
	nowarn=0
	commonCert=0
	certFileOnly=0
	certpkey=""
	inputtype=""
	keypair=""
    protFlag=0
    typeFlag=0
	caCert=0
	swCert=0
	commonSwCert=0
	CAfile=""
	extn=0
	extnLocalSwCert=0
	extnRemoteSwCert=0
	extnCaCert=0
	selfSignedCert=0
	CAFlag=""
	output=0

	`$CONFIGSHOW_CMD | $GREP 'security.policymode' | $GREP -qE '1'`
	highSecurityModeFlag=`$ECHO $? `

    if [ $count -eq 0 ]; then
        importUsage
        exit 0
    fi

	cmdargs[$count]="NULL"
	count=1
	
	while [ $INFINITE_LOOP ]
	do
	    case ${cmdargs[count]} in

        "$CERTSOURCE" )
			if [ $typeFlag -eq 0 ]; then
				impreq="CERT"
				typeFlag=1
			else
				importUsage
				exit 1
			fi
			;;

        "$CASOURCE" )
			if [ $typeFlag -eq 0 ]; then
				impreq="CA"
				typeFlag=1
			else
				importUsage
				exit 1
			fi
			;;

		"$CLIENT" )
			if [ "$CAFlag" == "" ]; then
				CAFlag="client"
			else
                importUsage
                exit 1
            fi
			;;

		"$SERVER" )
			if [ "$CAFlag" == "" ]; then
				CAFlag="server"
			else
                importUsage
                exit 1
            fi

			;;

    	"$TAG" )
            count=`expr $count + 1`
            keypair=${cmdargs[count]}
            ;;

        "$CAfile_OPT" )
        	count=`expr $count + 1`
            CAfile=${cmdargs[count]}
            ;;

            "$SYSLOG" )
            if [ "$protFlag" -eq 0 ] ; then
				inputtype=${cmdargs[count]}
				protFlag=1
            else
				importUsage
				exit 1
            fi
            ;;

            "$FCAPS" )
            if [ "$protFlag" -eq 0 ]; then
				inputtype=${cmdargs[count]}
				protFlag=1
            else
				importUsage
				exit 1
            fi
            ;;

            "$COMMONCERT" )
            if [ "$protFlag" -eq 0 ]; then
				inputtype=$FCAPS
				commonCert=1
				protFlag=1
            else
				importUsage
				exit 1
            fi
            ;;

            "$HTTPS" )
            if [ "$protFlag" -eq 0 ] ; then
				inputtype=${cmdargs[count]}
				protFlag=1
            else
				importUsage
				exit 1
            fi
            ;;

            "$RADIUS" )
            if [ "$protFlag" -eq 0 ]; then
				inputtype=${cmdargs[count]}
                protFlag=1
            else
				importUsage
				exit 1
            fi
            ;;

            "$LDAP" )
            if [ "$protFlag" -eq 0 ]; then
				inputtype=${cmdargs[count]}
                protFlag=1
            else
				importUsage
				exit 1
            fi
            ;;
            
            "$KAFKA" )
            if [ "$protFlag" -eq 0 ]; then
				inputtype=${cmdargs[count]}
                protFlag=1
            else
				importUsage
				exit 1
            fi
            ;;

            "$MGMT" )
            if [ "$protFlag" -eq 0 ]; then
				inputtype=${cmdargs[count]}
				protFlag=1
            else
				importUsage
                exit 1
            fi
            ;;

            "$EXTN" )
            if [ "$protFlag" -eq 0 ]; then
               inputtype=${cmdargs[count]}
               extn=1
               protFlag=1
            else
					importUsage
					exit 1
            fi
            ;;

			"$ASC" )
			if [ "$protFlag" -eq 0 ]; then
			inputtype=${cmdargs[count]}
			protFlag=1
			else
			importUsage
			exit 1
			fi
			;;


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

	    	"NULL" )
			break
			;;

	    	* )
			importUsage
			exit 1
			;;

	    esac
	    count=`expr $count + 1`
	done
	
    if [ "$impreq" == "" ] || [ "$inputtype" == "" ]; then
        importUsage
        exit 1
    fi
	
	# Block KAFKA import from CLI
    if [ "$inputtype" == "$KAFKA" ]; then
    	if [[ -z $restCaller ]] || [ "$impreq" == "CERT" ]; then
			importUsage
			exit 1
		fi
    fi

	if [ "$keypair" != "" -o "$CAfile" != "" ] && [ "$inputtype" != "$EXTN" ]; then
        importUsage
        exit 1
	fi

	if [ "$CAFlag" != "" ] && [ "$impreq" != "CA" ]; then
		importUsage
		exit 1
	fi

	if [ "$CAFlag" == "" ] && [[ "$impreq" == "CA" && "$inputtype" != "$EXTN" ]]; then
        importUsage
        exit 1
    fi

	if [ "$CAFlag" == "client" ] && [ "$inputtype" == "$HTTPS" ]; then
		$ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
		exit 1
	fi

	if [ "$CAFlag" == "client" ] && [ "$inputtype" == "$KAFKA" ]; then
		$ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
		exit 1
	fi
	
    if [ "$CAFlag" == "client" ] && [ "$inputtype" == "$ASC" ]; then
        $ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
        exit 1
    fi

        if [ "$CAFlag" == "server" ] && [ "$inputtype" == "$FCAPS" ]; then
                $ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
		if [ $commonCert -eq 1 ]; then
			$ECHO "Use -client option for $COMMONCERT"
			if [[ ! -z $restCaller ]]; then
				exit $COMMONCERT_NO_SERVER
			fi
		fi
                exit 1
        fi

	if  [ $extn -eq 1 ]; then

		is_extn_platform
		if [ $? -ne 0 ]; then
			$ECHO "This is not supported in non-extension platforms"
			exit 1
		fi

		if [ "$certFileName" == "" ]; then
			$ECHO "Import operation requires certificate name on the remote server to be specified"
			exit 1
		fi

		if [ "$keypair" != "" ]; then
			$ECHO "$keypair" |  $GREP -v "[^a-zA-Z0-9~@%_+:-]" > /dev/null 2>&1
			if [ ! $? -eq 0 ]; then
				$ECHO "Error: keypair_tag must not have unsupported characters," \
					"supported characters are [a-zA-Z0-9~@%_+:-]"
				exit 1
			fi
		fi

		if [ "$impreq" == "CERT" ]; then
			if [ "$keypair" != "" ]; then
				extnLocalSwCert=1
			else
				extnRemoteSwCert=1
			fi
		elif [ "$impreq" == "CA" ]; then
			if [ "$keypair" != "" ]; then
				$ECHO "keypair cannot be specified for $impreq import"
				exit 1
			fi
			extnCaCert=1
		fi

		if [ "$CAfile" == "" ] && [ $extnLocalSwCert -eq 1 -o $extnRemoteSwCert -eq 1 ]; then
			#If user does not specify CA certificate, this is self signed cert.
			selfSignedCert=1
		fi

		if [ "$CAfile" != "" ] && [ $extnLocalSwCert -eq 0 ] && [ $extnRemoteSwCert -eq 0 ]; then
			$ECHO "CA file name cannot be specified with $impreq"
			exit 1
		fi
		if [ "$CAfile" != "" ]; then
			certNameValidate $CAfile
		fi
	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

	$ECHO "$certFileName" | $GREP '/' >/dev/null 2>&1
	if [ "$?" -eq 0 ]; then
		$ECHO "Filename cannot be provided with path"
		exit 1
	fi
  	
	if [ "$protocol" == "$PROT_SCP" ] && [ -n "$password1" ]; then
		if [[ -z $restCaller ]]; then
			$ECHO "Don't enter the password in command line for SCP"
			exit 1
		fi
	fi
 	
	promptHostInfo $CERT_IMPORT $impreq $inputtype $keypair

    if [ $commonCert -eq 1 ]; then
        if [ "$impreq" == "CA" ]; then
			certname="$CA_CERT"
            $CP $FCAP_DIR/$FCAP_CACERT_FILE $CERT_DIR/$certname 2> /dev/null
            /fabos/cliexec/config save $CERT_DIR/$certname
            /fabos/cliexec/config save $CERT_DIR
			fqdn_set
        else
			certname="$SWITCH_CERT"
            if [ -f $FCAP_DIR/$FCAP_CERT_CONF_FILE ]; then
                 #Now we parse the file to look for switch certificate name.
                IFS_=${IFS}; IFS=$'\n'
                for LINE in `$CAT $FCAP_DIR/$FCAP_CERT_CONF_FILE`; do
                    validate_string=`$ECHO "$LINE" | $AWK -F':' ' { print $1 } '`

                    if [ $validate_string == "SWITCH_CERT_NAME" ] ; then
                        certFileName=`$ECHO "$LINE" | $AWK -F':' ' { print $2 } '`
                    fi
                done
                IFS=${IFS_}
            fi
            $CAT $FCAP_DIR/$FCAP_TOUCH_FILE > $CERT_DIR/$certname
            /fabos/cliexec/config save $CERT_DIR/$certname
            /fabos/cliexec/config save $CERT_DIR
			fqdn_set
            $RM -rf $FCAP_DIR/$certFileName 2> /dev/null
        fi
    fi

	# set configuration as per options
	if [ "$inputtype" == "$HTTPS" ] || [ $commonCert -eq 1 ]; then
	    setDefaultContext
    	VID=$?

		if [ "$impreq" == "CERT" ]; then
			configToUpdate=$CERTCONFIG
			enableHttps=1
			certpkey="BRCD_HTTPS_SW"
		elif [ "$impreq" == "CA" ]; then
			configToUpdate=$ROOTCERTCONFIG
			certpkey="BRCD_HTTPS_CA"
		fi
		/fabos/cliexec/config set $configToUpdate 5 $certname
		/fabos/cliexec/config update

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

		$AUDIT_NOTIFY "$CERT_IMPORT" "$userInput" "$AuditSz" "$AuditSha" "$ipAddr" "$certpkey"
		$ECHO "Certificate file in configuration has been updated."
	fi

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

	    /fabos/cliexec/config set http.ssl.enabled 1 1
		/fabos/cliexec/config update
	
		# avoid HTTPS restart, if called from REST
		if [[ -z $restCaller ]]; then
	        $WEBDHANDLER $HTTPCONFIG:1
		fi

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

	    $ECHO "Secure http has been enabled."
	fi

;;


$CERT_SHOW )
	input=""
	cacert="Empty"
	swcert="Empty"
	fcap=0
	VID=-1
	inputtype=""
	typeFlag=0	
	protFlag=0
	keypair=""
	count=0
	filename=""
	inputfile=""
    extn=0
    extnCaCert=0
	extnLocalSwCert=0
	extnRemoteSwCert=0	
    extnLocalSwCsr=0
	hexdump=0
	isExtnPlatform=0
	CAFlag=""

    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
        "$CERTSOURCE" )
			if [ $typeFlag -eq 0 ]; then
				showreq="CERT"
				typeFlag=1
			else
				showUsage
				exit 1
			fi
			;;

        "$CASOURCE" )
			if [ $typeFlag -eq 0 ]; then
				showreq="CA"
				typeFlag=1
			else
				showUsage
				exit 1
			fi
			;;

        "$CSRSOURCE" )
			if [ $typeFlag -eq 0 ]; then
				showreq="CSR"
				typeFlag=1
			else
				showUsage
				exit 1
			fi
			;;

        "$CLIENT" )
			if [ "$CAFlag" == "" ]; then
	            CAFlag="client"
			else
				showUsage
				exit 1
			fi
            ;;

        "$SERVER" )
            if [ "$CAFlag" == "" ]; then
	            CAFlag="server"
            else
                showUsage
                exit 1
            fi

            ;;

        "$HTTPS"|"$FCAPS"|"$RADIUS"|"$LDAP"|"$SYSLOG"|"$KAFKA"|"$ASC" )
			if [ $protFlag -eq 0 ]; then
				inputtype=${cmdargs[count]}
				protFlag=1
			else
				showUsage
				exit 1
			fi
			;;
            
		"$MGMT" )
            if [ $protFlag -eq 0 ]; then
                inputtype=${cmdargs[count]}
                protFlag=1
				if [ "${cmdargs[count + 1]}" != "NULL" ]; then
					count=`expr $count + 1`
					filename=${cmdargs[count]}
				fi
            else
                showUsage
                exit 1
            fi
            ;;

		"$COMMONCERT" )
		if [ $protFlag -eq 0 ]; then
			inputtype=${cmdargs[count]}
			protFlag=1
		else
			showUsage
			exit 1
		fi
		;;

		"$EXTN" )
		if [ $protFlag -eq 0 ]; then
			inputtype=${cmdargs[count]}
			extn=1
			if [ "${cmdargs[count + 1]}" != "NULL" ]; then
				#Display file and not filtering based on keypair_tag
				isArgToken $CERT_SHOW ${cmdargs[count + 1]}
				result=$?
				if [ $result -eq 0  ]; then
					count=`expr $count + 1`
					filename=${cmdargs[count]}
				fi
			fi
			protFlag=1
		else
			showUsage
			exit 1
		fi
		;;

	        "$TAG" )
    	        count=`expr $count + 1`
        	    keypair=${cmdargs[count]}
            	;;

	        "$ALL" )
				if [ $typeFlag -eq 0 ]; then
					input="ALL"
					typeFlag=1
				else
					showUsage
					exit 1
				fi	
				;;

			"$HEX_DUMP" )
				hexdump=1
			;;
	        "NULL" )
    	    	break
            ;;

        * )
            showUsage
            exit 1
            ;;

        esac
        count=`expr $count + 1`
    done
	
	if [ "$inputtype" == "" ] && [ "$input" != "ALL" ]; then
		showUsage
		exit 1
	fi

	if [ "$inputtype" != "" ] && [ "$input" == "ALL" ]; then
		showUsage
		exit 1
	fi
	
	if [[ "$showreq" == "CERT" || "$showreq" == "CSR" ]] && [ "$inputtype" == "$KAFKA" ]; then
		showUsage
		exit 1
	fi

	if [[ "$keypair" != "" && "$inputtype" != "$EXTN" ]] || [[ "$inputtype" == "$MGMT" && "$showreq" != "CERT" ]]; then
		showUsage
		exit 1
	fi

    if [ "$CAFlag" != "" ] && [ "$showreq" != "CA" ]; then
		showUsage
        exit 1
    fi

    if [ "$CAFlag" == "" ] && [[ "$showreq" == "CA" && "$inputtype" != "$EXTN" ]]; then
		showUsage
        exit 1
    fi

    if [ "$CAFlag" == "client" ] && [ "$inputtype" == "$HTTPS" ]; then
        $ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
        exit 1
    fi

	if [ "$CAFlag" == "client" ] && [ "$inputtype" == "$ASC" ]; then
	$ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
	exit 1
	fi

	if [ "$CAFlag" == "client" ] && [ "$inputtype" == "$KAFKA" ]; then
        $ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
        exit 1
    fi

    if [ "$CAFlag" == "server" ] && [ "$inputtype" == "$FCAPS" ]; then
        $ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
        exit 1
    fi

    if [ "$CAFlag" == "server" ] && [ "$inputtype" == "$COMMONCERT" ]; then
	$ECHO "Error: Invalid option -server passed. Use -client option for $COMMONCERT"
	if [[ ! -z $restCaller ]]; then
		exit $COMMONCERT_NO_SERVER
	fi
	exit 1
    fi


	if [ "$inputtype" == "$COMMONCERT" ]; then
	    #Check for FIPS
		checkFipsMode
        if [ $? -eq 1 ]; then
            $ECHO "Common Cert related operations are not allowed in FIPS Mode."
            exit 1
        fi
	fi
	
	# KAFKA show
	if  [ "$inputtype" == "$KAFKA" ]; then
		if [ "$showreq" == "CA" ]; then
			if [ "$keypair" != "" ]; then
				$ECHO "keypair cannot be specified for $showreq file display"
				exit 1
	     		fi
			
			if [ -e $KAFKA_DIR ]; then
                cd $KAFKA_DIR
            fi

			if [ -s $KAFKA_CACERT_FILE ]; then
                inputfile=$KAFKA_CACERT_FILE   
            else
                $ECHO "No $inputtype $SWITCH_CACERT_DESC_NAME is installed"
                exit 1
            fi
	      
	   		if [ $hexdump -eq 1 ]; then
				$OPENSSL_CMD x509 -in ./$inputfile	
			else
				$OPENSSL_CMD x509 -in ./$inputfile -noout -custom \
					-nameopt multiline -subject -issuer -dates -fingerprint -custom
				if [[ ! -z $restCaller ]]; then
					$OPENSSL_CMD x509 -in ./$inputfile	
				fi
			fi
			ret=$?	
		else 
			showUsage
			exit 1
		fi	   
		if [ "$keypair" != "" ]; then
			$ECHO "$keypair" |  $GREP -v "[^a-zA-Z0-9~@%_+:-]" > /dev/null 2>&1
			if [ ! $? -eq 0 ]; then
				$ECHO "Error: keypair_tag must not have unsupported characters," \
					"supported characters are [a-zA-Z0-9~@%_+:-]"
				exit 1
			fi
		fi
		exit 0
	fi

 	is_extn_platform
	if [ $? -eq 0 ]; then
		isExtnPlatform=1
	fi

	if  [ $extn -eq 1 ]; then

		if [ $isExtnPlatform -eq 0 ]; then
			# Do not change the below line as preinstall script depends on 
			# this line for downgrade related check.	
			$ECHO "This is not supported in non-extension platforms"
			exit 1
      		fi

		if [ "$showreq" == "CA" ]; then
			if [ "$keypair" != "" ]; then
				$ECHO "keypair cannot be specified for $showreq file display"
				exit 1
	     		fi
			if [ "$filename" != "" ]; then
				certNameValidate $filename
			fi
			extnCaCert=1
		elif [ "$showreq" == "CERT" ]; then
			if [ "$filename" != "" ]; then
				certNameValidate $filename
			fi
			#Display local and remote
			if [ "$filename" == "" ] && [ "$keypair" == "" ]; then
				extnLocalSwCert=1
				extnRemoteSwCert=1
			else
				if [ "$keypair" != "" ]; then
					extnLocalSwCert=1
				else
					extnRemoteSwCert=1
				fi
			fi
		elif [ "$showreq" == "CSR" ]; then
			if [ "$filename" != "" ]; then
				csrNameValidate $filename
			fi		
			extnLocalSwCsr=1				
     		if [ "$keypair" != "" ] && [ "$filename" != "" ]; then
				$ECHO "Both filename and keypair cannot be specified for $showreq file display"
				exit 1
			fi
		else
			showUsage
			exit 1
		fi	   

		if [ "$keypair" != "" ]; then
			$ECHO "$keypair" |  $GREP -v "[^a-zA-Z0-9~@%_+:-]" > /dev/null 2>&1
			if [ ! $? -eq 0 ]; then
				$ECHO "Error: keypair_tag must not have unsupported characters," \
					"supported characters are [a-zA-Z0-9~@%_+:-]"
				exit 1
			fi
		fi
	fi

	input=`$ECHO $input | tr "[:lower:]" "[:upper:]"`

	if [ "$input" != "ALL" ]; then
		if [ $extn -eq 1 ]; then
			showFilesExtn
		else
			showFiles $showreq $inputtype $keypair 
		fi
	else
		$ECHO "                    "
		$ECHO "ssh private key: "
		if [ -f $PRIVKEY_DIR/$PRIVKEY_FILE ] || \
			[ -f $PRIVKEY_DIR/$PRIVKEY_FILE_OLD ] || \
			[ -f $PRIVKEY_DIR/$PRIVKEY_FILE_ECDSA ]; 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" "Client CA" "Server CA" "SW" \
				 "CSR" "PVT Key" "Passphrase"
		$ECHO -n "------------------------------------------------------------------------"
		$ECHO "--------------------------------------------"
		if [ -s $FCAP_DIR/$FCAP_CACERT_FILE ]; then
			cacert="Exist"
		else
			cacert="Empty"
		fi

        if [ -s $FCAP_DIR/$FCAP_SWCERT_FILE ]; then
            swcert="Exist"
        else
            swcert="Empty"
        fi

		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "FCAP" "$cacert" "NA" \
			"$swcert" \
			`/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`

        if [ -s $RADIUS_DIR/$PVT_KEY ]; then
            pvtKey="Exist"
        else
            pvtKey="Empty"
        fi

        if [ -s "$RADIUS_DIR/$switchIp$CSR_SUFFIX" ]; then
            csrFile="Exist"
        else
            csrFile="Empty"
        fi

        if [ -s $RADIUS_DIR/$RADIUS_CACERT_FILE ]; then
            cacert="Exist"
        else
            cacert="Empty"
        fi

        if [ -s $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE ]; then
            clientcacert="Exist"
        else
            clientcacert="Empty"
        fi

        if [ -s $RADIUS_DIR/$RADIUS_SWCERT_FILE ]; then
            swcert="Exist"
        else
            swcert="Empty"
        fi

        printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "RADIUS" "$clientcacert" "$cacert" "$swcert" \
            $csrFile $pvtKey "NA"
        if [ -s $LDAP_DIR/$PVT_KEY ]; then
            pvtKey="Exist"
        else
            pvtKey="Empty"
        fi

        if [ -s "$LDAP_DIR/$switchIp$CSR_SUFFIX" ]; then
            csrFile="Exist"
        else
            csrFile="Empty"
        fi

        if [ -s $LDAP_DIR/$LDAP_CACERT_FILE ]; then
            cacert="Exist"
        else
            cacert="Empty"
        fi

        if [ -s $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE ]; then
            clientcacert="Exist"
        else
            clientcacert="Empty"
        fi

        if [ -s $LDAP_DIR/$LDAP_SWCERT_FILE ]; then
            swcert="Exist"
        else
            swcert="Empty"
        fi

		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "LDAP" "$clientcacert" "$cacert" "$swcert" \
			$csrFile $pvtKey "NA"

		if [ -s $SYSLOG_DIR/$SYSLOG_CACERT_FILE ]; then
			cacert="Exist"
		else
			cacert="Empty"
		fi

		if [ -s $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE ]; then
			clientcacert="Exist"
		else
			clientcacert="Empty"
		fi

        if [ -s $SYSLOG_DIR/$SYSLOG_SWCERT_FILE ]; then
            swcert="Exist"
        else
            swcert="Empty"
        fi

        if [ -s $SYSLOG_DIR/$PVT_KEY ]; then
            pvtKey="Exist"
        else
            pvtKey="Empty"
        fi

        if [ -s "$SYSLOG_DIR/$switchIp$CSR_SUFFIX" ]; then
            csrFile="Exist"
        else
            csrFile="Empty"
        fi

		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "SYSLOG" "$clientcacert" "$cacert" "$swcert" \
			$csrFile $pvtKey "NA"

        setDefaultContext
		VID=$?

		httpsCert=`/fabos/cliexec/config get $CERTCONFIG 5 2> /dev/null`
		if [ $? != 0 ]; then
			httpsCert="Empty"
		elif [ "$httpsCert" != "none" ]; then
			httpsCert="Exist"
		else
			httpsCert="Empty"
		fi

        cacert=`/fabos/cliexec/config get $ROOTCERTCONFIG 5 2> /dev/null`
        if [ $? != 0 ]; then
            cacert="Empty"
        elif [ "$cacert" != "none" ]; then
			cacert="Exist"
		else
			cacert="Empty"
		fi

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

		if [ -s "$CERT_DIR/$switchIp$CSR_SUFFIX" ]; then
			csrFile="Exist"
		else
			csrFile="Empty"
		fi
		
		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "HTTPS" "NA" "$cacert" "$httpsCert" \
				$csrFile $pvtKey "NA"
		
		if [ -s $KAFKA_DIR/$KAFKA_CACERT_FILE ]; then
			cacert="Exist"
		else
			cacert="Empty"
		fi
		
		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "KAFKA" "NA" "$cacert" "NA" \
				"NA" "NA" "NA"

		if [ -s $ASC_DIR/$ASC_CACERT_FILE ]; then
			cacert="Exist"
		else
			cacert="Empty"
		fi

		printf "%-10s %-25s %-25s %-25s %-7s %-7s %-7s\n" "ASC" "NA" "$cacert" "NA" \
						"NA" "NA" "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" "NA" \
				"NA" "NA" "NA"
		done

		#EXTN files			
		if [ $isExtnPlatform -eq 1 ]; then
			showFilesExtn
		fi
			
        if [ $VID != -1 ]; then
            setcontext $VID
        fi
	fi
;;

$CERT_DELE )
	commoncert=0
	response="no"
	file=NULL
	flag=0
	count=0
	certpkey=""
	inputtype=""
	delreq=""
	keypair=""
	filename=""
	isExist=1
	optag=""
	curdir=""
	debug=0
	protFlag=0
	typeFlag=0
	isExtnPlatform=0
	syslogsecure=0
	isDeleteOk=$DEL_ERR_NO_CERT

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

	#NOTE: if you are adding any new arguments, please add the corresponding
	# tokens in the function isArgToken()
    while [ $INFINITE_LOOP ]
    do

        case ${cmdargs[count]} in
        "$CERTSOURCE" )
			if [ $typeFlag -eq 0 ]; then	
				delreq="CERT"
				optag=$SWITCH_CERT_DESC_NAME
				typeFlag=1
			else
				deleteUsage
				exit 1
			fi
			;;

        "$CASOURCE" )
			if [ $typeFlag -eq 0 ]; then	
				delreq="CA"
				optag=$SWITCH_CACERT_DESC_NAME
				typeFlag=1
			else
				deleteUsage
				exit 1
			fi
			;;

        "$CSRSOURCE" )
			if [ $typeFlag -eq 0 ]; then	
				delreq="CSR"
				typeFlag=1
			else
				deleteUsage
				exit 1
			fi
			;;

	    "$ALL" )
			if [ $typeFlag -eq 0 ]; then	
				delreq="ALL"
				typeFlag=1
			else
				deleteUsage
				exit 1
			fi
			;;

        "$CLIENT" )
            if [ "$CAFlag" == "" ]; then
                CAFlag="client"
            else
                showUsage
                exit 1
            fi
            ;;

        "$SERVER" )
            if [ "$CAFlag" == "" ]; then
                CAFlag="server"
            else
                showUsage
                exit 1
            fi
            ;;

        "$HTTPS"|"$FCAPS"|"$RADIUS"|"$LDAP"|"$SYSLOG"|"$ASC"|"$KAFKA" )
			if [ $protFlag -eq 0 ]; then
				inputtype=${cmdargs[count]}
				protFlag=1
			else
				deleteUsage
				exit 1
			fi	
        	;;

        "$MGMT" )
            if [ $protFlag -eq 0 ]; then
                inputtype=${cmdargs[count]}
                protFlag=1
                if [ "${cmdargs[count + 1]}" != "NULL" ]; then
                    count=`expr $count + 1`
                    filename=${cmdargs[count]}
                fi
            else
				deleteUsage
                exit 1
            fi
            ;;

        "$COMMONCERT" )
			if [ $protFlag -eq 0 ]; then
				commoncert=1
				inputtype=${cmdargs[count]}
				protFlag=1
			else
				deleteUsage
				exit 1
			fi	
        	;;

        "$EXTN" )
			if [ $protFlag -eq 0 ]; then
				inputtype=${cmdargs[count]}
				extn=1
				if [ "${cmdargs[count + 1]}" != "NULL" ]; then
					isArgToken $CERT_DELE ${cmdargs[count + 1]}
					if [ $? -ne 1 ]; then
						#The next argument is not a argument-token, so it is a filename
						count=`expr $count + 1`
						filename=${cmdargs[count]}
					fi
				fi
				protFlag=1
			else
				deleteUsage
				exit 1
			fi
			;;

        "$TAG" )
			if [ "${cmdargs[count + 1]}" == "NULL" ]; then
				deleteUsage
				exit 1
			fi
			count=`expr $count + 1`
			keypair=${cmdargs[count]}
            ;;

		"$ALL_OPT" )
		if [ $protFlag -eq 0 ]; then	
			inputtype=${cmdargs[count]}
			protFlag=1
		else
			deleteUsage
			exit 1
		fi	
			;;

		"$DEFAULT" )
            inputtype=${cmdargs[count]}
			;;

        "$NOWARN_OPT" )
            response="yes"
            ;;

		"-zeroize" )
			debug=1
			;;

        "NULL" )
            break
            ;;

        * )
            deleteUsage
            exit 1
            ;;

        esac
        count=`expr $count + 1`
    done

	if [ "$delreq" == "" ] || [ "$inputtype" == "" ]; then
		deleteUsage
		exit 1
	fi
	
	# Block KAFKA delete from CLI
    if [ "$inputtype" == "$KAFKA" ]; then
    	if [[ -z $restCaller ]] || [[ "$delreq" == "CERT" || "$delreq" == "CSR" || "$delreq" == "ALL" ]]; then
			deleteUsage
			exit 1
		fi
    fi

	if [ "$keypair" != "" ] && [ "$inputtype" != "$EXTN" ]; then
		deleteUsage
		exit 1
	fi

	if [ "$inputtype" == "$MGMT" ] && [[ "$delreq" != "CERT" && "$delreq" != "ALL" ]]; then
		deleteUsage
		exit 1
	fi

    if [ "$CAFlag" != "" ] && [ "$delreq" != "CA" ]; then
		deleteUsage
        exit 1
    fi

    if [ "$CAFlag" == "" ] && [[ "$delreq" == "CA" && "$inputtype" != "$EXTN" ]]; then
		deleteUsage
        exit 1
    fi

    if [ "$CAFlag" == "client" ] && [ "$inputtype" == "$HTTPS" ]; then
        $ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
        exit 1
    fi
    
    if [ "$CAFlag" == "client" ] && [ "$inputtype" == "$KAFKA" ]; then
        $ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
        exit 1
    fi

	if [ "$CAFlag" == "client" ] && [ "$inputtype" == "$ASC" ]; then
	$ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
	exit 1
	fi


	if [ "$CAFlag" == "server" ] && [ "$inputtype" == "$FCAPS" ]; then
        $ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
        exit 1
    fi
    if [ "$CAFlag" == "server" ] && [ $commoncert -eq 1 ]; then
	$ECHO "Error: Invalid option -server passed. Use -client option for $COMMONCERT"
	if [[ -z $restCaller ]]; then
		exit $COMMONCERT_NO_SERVER
	fi
	exit 1
    fi


    if [ "$inputtype" == "$COMMONCERT" ]; then
        #Check for FIPS
		checkFipsMode
        if [ $? -eq 1 ]; then
            $ECHO "Common Cert related operations are not allowed in FIPS Mode."
            exit 1
        fi
    fi

	if [ "$inputtype" == "$COMMONCERT" ]; then
		commoncert=1
		inputtype="$FCAPS"
		check_delete_commoncert $delreq	
	fi

	is_extn_platform
	if [ $? -eq 0 ]; then
		isExtnPlatform=1
	fi

	#Do syntax check for Extn case
	if [ "$inputtype" == "$EXTN" ]; then

		if [ $isExtnPlatform -eq 0 ]; then
			$ECHO "This is not supported in non-extension platforms"
			exit 1
		fi

		if [ "$delreq" == "CERT" ]; then
			if [ "$filename" == "" ] && [ "$keypair" == "" ] ;then
				$ECHO "Extn Cert delete needs cert-name or Keypair_tag"
				deleteUsage
				exit 1
			elif [ "$filename" != "" ] && [ "$keypair" != "" ];then
				$ECHO "Extn Cert delete needs either cert-name or Keypair_tag, not both"
				deleteUsage
				exit 1
			fi
		elif [ "$delreq" == "CA" ]; then
			if [ "$filename" == "" ] || [ "$keypair" != "" ] ;then
				deleteUsage
				exit 1
			fi
		elif [ "$delreq" == "CSR" ]; then
			if [ "$filename" != "" ] || [ "$keypair" == "" ] ; then
				deleteUsage
				exit 1
			fi
		elif [ "$delreq" == "ALL" ]; then
			if [ "$filename" != "" ] || [ "$keypair" != "" ] ;then
				deleteUsage
				exit 1
			fi
		fi
		if [ "$filename" != "" ]; then
			certNameValidate $filename
		fi
		if [ "$keypair" != "" ]; then
			$ECHO "$keypair" |  $GREP -v "[^a-zA-Z0-9~@%_+:-]" > /dev/null 2>&1
			if [ ! $? -eq 0 ]; then
				$ECHO "Error: keypair_tag must not have unsupported characters," \
					"supported characters are [a-zA-Z0-9~@%_+:-]"
				exit 1
			fi
		fi
	fi

	if [ "$inputtype" == "$EXTN" ]; then
		extn_files_to_delete=""
		extn_delete_prompt=""
		extn_audit_notify_arg2=""
		extn_audit_notify_arg3=""

		#The below function will prepare for delete
		#It will exit on any error
		#It will populate the following variables:
		#extn_files_to_delete - All the files to be deleted
		#extn_delete_prompt - The prompt that needs to be displayed to the user for delete
		#extn_audit_notify_arg? - Arguments to be passed for audit_notify
		extn_cert_del_prepare
		if [ "$response" == "no" ]; then
			$ECHO -e "$extn_delete_prompt"
			secOpConfirm
			if [ $? -ne 0 ]; then
				exit 1
			fi
		fi
		deleteFiles 0 $extn_files_to_delete
		/fabos/cliexec/config save $EXTN_DIR
		if [ "$delreq" != "CSR" ] ; then
			if [ "$extn_audit_notify_arg3" != "" ]; then
				$AUDIT_NOTIFY "$CERT_DELE" "$extn_audit_notify_arg2 (keypair_tag:$extn_audit_notify_arg3)" "" > /dev/null 2>&1
			else
				$AUDIT_NOTIFY "$CERT_DELE" "$extn_audit_notify_arg2" "" > /dev/null 2>&1
			fi	
		else
			$AUDIT_NOTIFY "$CERT_DEL_CSR" $extn_audit_notify_arg2 > /dev/null 2>&1
		fi
	elif [ "$delreq" == "CA" ] || [ "$delreq" == "CERT" ]; then
		if [ "$inputtype" == "$FCAPS" ] || [ "$inputtype" == "$RADIUS" ] || [ "$inputtype" == "$LDAP" ] || \
			[ "$inputtype" == "$SYSLOG" ] || [ "$inputtype" == "$HTTPS" ] || [ "$inputtype" == "$EXTN" ] || \
			[ "$inputtype" == "$MGMT" ] || [ "$inputtype" == "$KAFKA" ] || [ "$inputtype" == "$ASC" ]; then
				confirmDelete $inputtype
				if [ $commoncert -eq 1 ]; then
					confirmDelete $HTTPS
				fi
		elif [ "$inputtype" == "$ALL_OPT" ]; then
            confirmDelete $SYSLOG
            confirmDelete $FCAPS
            confirmDelete $RADIUS
            confirmDelete $LDAP
			confirmDelete $HTTPS
			confirmDelete $ASC
	    if [[ -z $restCaller ]]; then
				if [ $isExtnPlatform -eq 1 ]; then
					deleteExtensionCerts $delreq $inputtype
				fi
	    fi
		else
			deleteUsage
			exit 1
        fi
	elif [ "$delreq" == "CSR" ]; then
	    if [ "$response" == "no" ]; then
    	    $ECHO "WARNING!!!"
        	$ECHO
	        $ECHO "About to delete $inputtype $delreq file"
	        secOpConfirm

    	    if [ $? -eq 1 ]; then
        	    exit 1
	        fi
		fi

		file=$switchIp$CSR_SUFFIX
        if [ "$inputtype" == "$FCAPS" ]; then
			curdir=$FCAP_DIR
			file=$FCAP_SWCSR_FILE
        elif [ "$inputtype" == "$RADIUS" ]; then
			curdir=$RADIUS_DIR
        elif [ "$inputtype" == "$LDAP" ]; then
			curdir=$LDAP_DIR
        elif [ "$inputtype" == "$SYSLOG" ]; then
			curdir=$SYSLOG_DIR
        elif [ "$inputtype" == "$HTTPS" ]; then
			curdir=$CERT_DIR
        else
            deleteUsage
            exit 1
        fi

		# remove the csr
        if [ -s "$curdir/$file" ];then
            $CAT /dev/null > $curdir/$file
			/fabos/cliexec/config save $curdir/$file
            /fabos/cliexec/config save $curdir
			$AUDIT_NOTIFY "$CERT_DEL_CSR" $file
		isDeleteOk=$DELETE_SUCCESS
        else
		isDeleteOk=$DEL_ERR_NO_CSR
			$ECHO "CSR does not exist"
        fi

		if [ $commoncert -eq 1 ]; then
			if [ -s $CERT_DIR/$switchIp$CSR_SUFFIX ]; then
				$CAT /dev/null > $CERT_DIR/$switchIp$CSR_SUFFIX
				/fabos/cliexec/config save $CERT_DIR/$switchIp$CSR_SUFFIX
				/fabos/cliexec/config save $CERT_DIR
				$AUDIT_NOTIFY "$CERT_DEL_CSR" $switchIp$CSR_SUFFIX
			fi
		fi
		$ECHO
	elif [ "$delreq" == "ALL" ]; then
        if [ "$inputtype" == "$FCAPS" ]; then
			confirmDelete $inputtype
            if [ $commoncert -eq 1 ]; then
                confirmDelete $HTTPS
            fi
        elif [ "$inputtype" == "$RADIUS" ] || [ "$inputtype" == "$LDAP" ] || [ "$inputtype" == "$SYSLOG" ] || \
				[ "$inputtype" == "$HTTPS" ] || [ "$inputtype" == "$MGMT" ]; then
			syslogsecure=`$CONFIGSHOW_CMD | $GREP 'syslog.IP.secure' | $GREP -c ':1'`
			if [ $syslogsecure -ge 1 ] && [ "$inputtype" == "$SYSLOG" ]; then
				$ECHO "Syslog is configured in secure mode, so certificate cannot be deleted. Please remove secure mode configuration for Syslog and try again."
				exit 1
			fi
			confirmDelete $inputtype 
        elif [ "$inputtype" == "$DEFAULT" ]; then
			syslogsecure=`$CONFIGSHOW_CMD | $GREP 'syslog.IP.secure' | $GREP -c ':1'`
			if [ $syslogsecure -ge 1 ]; then
				$ECHO "Syslog is configured in secure mode, so certificate cannot be deleted. Please remove secure mode configuration for Syslog and try again."
				exit 1
			fi
			confirmDelete $FCAPS
			confirmDelete $RADIUS
			confirmDelete $LDAP
			confirmDelete $SYSLOG
			confirmDelete $HTTPS
			confirmDelete $MGMT
			if [ $isExtnPlatform -eq 1 ]; then
				confirmDelete $EXTN
			fi
        else
            deleteUsage
            exit 1
        fi
	else
        deleteUsage
        exit 1
    fi
    if [[ ! -z $restCaller ]]; then
    	exit $isDeleteOk
    fi
;;
 
$CERT_GEN )
	# verify input arguments before processing
	fcap=0
	response="no"
	genreq=""
	typeFlag=0
	protFlag=0	
	file=
	key_size=0
    keytype="no"
    hashtype="no"
    years=0
    flag=0
    count=0
    commoncert=0
    caCert=0
    https=0
    genswcert=0
    allopt=0
    showusage=0
    certtype=""
	sign=0
	keytype=""
	keypair=""
	extn=0

    declare -a cmdargs

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

	if [ $count -eq 0 ]; then
		generateUsage
		exit 0
	fi
		
    cmdargs[$count]="NULL"
    count=1

    while [ $INFINITE_LOOP ]
   	do
    	case ${cmdargs[count]} in
        "$CSRSOURCE" )
			if [ $typeFlag -eq 0 ]; then
            genreq="CSR"
				typeFlag=1
			else
				generateUsage
				exit 1
			fi
			;;

        "$CERTSOURCE" )
			if [ $typeFlag -eq 0 ]; then
				genreq="CERT"
				typeFlag=1
			else
				generateUsage
				exit 1
			fi
			;;

       	"$NOWARN_OPT" )
    	   	response="yes"
        	;;

        "$HTTPS" )
			if [ $protFlag -eq 0 ]; then
				https=1
				certtype=${cmdargs[count]}
				hashtype="sha256"
				key_size=2048
				keytype="rsa"
				years=5
				sign=1
				protFlag=1
			else
				generateUsage
				exit 1			
			fi
        	;;

        "$FCAPS" )
			if [ $protFlag -eq 0 ]; then
				fcap=1
				certtype=${cmdargs[count]}
				hashtype="sha256"
				key_size=2048
				keytype="rsa"
				years=5
				protFlag=1
			else
				generateUsage
				exit 1
			fi
        	;;

        "$COMMONCERT" )
			if [ $protFlag -eq 0 ]; then
				commoncert=1
				certtype=$FCAPS
				hashtype="sha256"
				key_size=2048
				keytype="rsa"
				years=5
				protFlag=1
			else
				generateUsage
				exit 1	
			fi
        	;;

        "$RADIUS" )
			if [ $protFlag -eq 0 ]; then
				certtype=${cmdargs[count]}
				hashtype="sha256"
				key_size=2048
				keytype="rsa"
				years=5
				protFlag=1
			else
				generateUsage
				exit 1
			fi
			;;

        "$LDAP" )
			if [ $protFlag -eq 0 ]; then
				certtype=${cmdargs[count]}
				hashtype="sha256"
				key_size=2048
				keytype="rsa"
				years=5
				protFlag=1
			else
				generateUsage
				exit 1
			fi
			;;

        "$SYSLOG" )
			if [ $protFlag -eq 0 ]; then
				certtype=${cmdargs[count]}
				hashtype="sha256"
				key_size=2048
				keytype="rsa"
				years=5
				protFlag=1
			else
				generateUsage
				exit 1
			fi
			;;

        "$EXTN" )
			if [ $protFlag -eq 0 ]; then
				extn=1
				certtype=${cmdargs[count]}    
				hashtype="sha384"
				key_size="P384"
				keytype="ecdsa"
				years=5
				protFlag=1
			else
				generateUsage
				exit 1
			fi
			;;

        "$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]}
        	;;

		"$TAG" )
			count=`expr $count + 1`
			keypair=${cmdargs[count]}
			;;

		"NULL" )
			break
			;;

		* )
 			generateUsage
			exit 1
			;;
	    esac
	    count=`expr $count + 1`
	done
	if [ "$genreq" == "" ] || [ "$certtype" == "" ]; then
		generateUsage
		exit 1
	fi

    if [ "$keypair" != "" ] && [ "$certtype" != "$EXTN" ]; then
		generateUsage
		exit 1
    fi

    if [ $years -lt 0 ] || [ $years -gt 50 ]; then
		$ECHO "Error: Valid input for years is 1 to 50"
        exit 1
    fi

    if [ "$certtype" != "$EXTN" ]; then
		if [ "$keytype" == "ecdsa" ]; then
			$ECHO "Error: Ecdsa keys not supported for $certtype."
			exit 1
		elif [ "$hashtype" == "sha384" ]; then
			$ECHO "Error: Sha384 hash not supported for $certtype."
			exit 1
		elif [ "$key_size" == "P384" ]; then
			$ECHO "Error: Invalid key size - $key_size."
			exit 1
		elif [ "$hashtype" != "sha1" ] && [ "$hashtype" != "sha256" ]  && [ "$hashtype" != "sha512" ]; then
	        $ECHO "Error: Unsupported/invalid hashtype for $certtype - $hashtype."
			exit 1
		elif [ "$key_size" != 1024 ] && [ "$key_size" != 2048 ] && [ "$key_size" != 4096 ]  && [ "$key_size" != 8192 ]; then
			$ECHO "Error: Unsupported/invalid $keytype key size for $certtype - $key_size."
			exit 1
		fi

	    if [ "$keytype" == "rsa" ] || [ "$keytype" == "dsa" ]; then
    		    if [ "$keytype" == "dsa" ]; then
	            	if [ "$hashtype" == "sha512" ]; then
			        $ECHO "Error: Unsupported hashtype passed - $hashtype, not supported by DSA"
			        exit 1
        		fi
		    fi
	    else
    	    	    $ECHO "Error: Invalid/unsupported key type - $keytype"
		    exit 1
	    fi

	    if [ "$certtype" == "$FCAPS" ]; then
		if [ "$keytype" != "rsa" ]; then
                    $ECHO "Error: Unsupported key type for fcap."
                    exit 1
                elif [ $key_size != 1024 ] && [ $key_size != 2048 ]; then
                    $ECHO "Error: Unsupported key size for fcap."
                    exit 1
                elif [ $hashtype != "sha1" ] && [ $hashtype != "sha256" ]; then
                    $ECHO "Error: Unsupported hash type for fcap."
                    exit 1
                fi
	    fi

	    checkFipsMode
	    retVal=$?

            if [ $retVal -eq 1 ]; then
            	if [ "$keytype" == "dsa" ]; then
                	$ECHO "Error: DSA key type is not allowed in FIPS Mode."
			exit 1
        	elif [ $key_size -lt 2048 ]; then
                	$ECHO "Error: Key size less than 2048 is not allowed in FIPS Mode."
                	exit 1
                elif [ $commoncert -eq 1 ];then
			$ECHO "Error: Common Cert related operations are not allowed in FIPS Mode."
			exit 1
	        fi
	    fi
    fi

    if [ $extn -eq 1 ]; then

		is_extn_platform
		if [ $? -ne 0 ]; then
			$ECHO "This is not supported in non-extension platforms"
			exit 1
		fi

		if [ "$keytype" != "$ECDSA_KEY" ]; then
			$ECHO "Error: Only ECDSA supported for Extension certificates"
			exit 1
		fi

		if [ "$key_size" != "P384" ]; then
			$ECHO "Error: Unsupported/invalid key size for $certtype: $key_size"
			exit 1
		fi

		if [ "$hashtype" != "sha384" ]; then
			$ECHO "Error: Unsupported/invalid hashtype for $certtype: $hashtype"
			exit 1
		fi

		if [ "$keypair" == "" ]; then
			$ECHO "Error: Extension certificates require a keypair name to be specified"
			exit 1
		fi

		$ECHO "$keypair" |  $GREP -v "[^a-zA-Z0-9~@%_+:-]" > /dev/null 2>&1
		if [ ! $? -eq 0 ]; then
			$ECHO "Error: keypair_tag must not have unsupported characters," \
				"supported characters are [a-zA-Z0-9~@%_+:-]"
			exit 1
		fi

		keypair_len=`expr length $keypair`
		if [ $keypair_len -gt 31 ]; then
			$ECHO "Error: keypair_tag should not exceed 31 characters"
			exit 1
		fi
	fi

  	if [ "$genreq" == "CERT" ]; then
		if [ $extn -eq 0 ]; then
			if [ $sign -eq 0 ]; then
				generateUsage
				exit 1
			fi
			# Generate Self-signed cert
    		GenerateSelfSignedCerts
		else
			GenerateSelfSignedCertsExtn
		fi

		if [ $? -eq 0 ]; then
			$ECHO "Generated self-signed $certtype certificate successfully."
		fi
		exit 0
	fi
	if [[ -z $restCaller ]]; then
	 	if [ $response == "no" ]; then
			if [ $extn -eq 1 ]; then
				$ECHO "Generating a new CSR:"
			else
				$ECHO "Generating a  CSR 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
			fi
			$ECHO
			$ECHO "Warning: Key-pair generation is CPU intensive and can cause high CPU usage"
			$ECHO "         Private IPs and hostnames should not be part of SCN and/or SAN per CA/Browser forum."
			$ECHO

			secOpConfirm

    	    if [ $? -eq 1 ]; then
        	    exit 1
	        fi
		fi
	fi

	if [ $extn -eq 1 ]; then
		generateCsrExtn $certtype $key_size $hashtype $keytype $keypair
	else
		generateCsrClient $certtype $key_size $hashtype $keytype
	fi

;; 

$CERT_HELP )
	usage
;;

* )
	usage
	exit 1
;;

esac

exit 0

