#!/bin/sh
#
#	 Copyright (c) 2016-2017 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
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
ECDSA_PARAMS_FILE=ecdsaparam.pem
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"
ECDSA_KEY="ecdsa"
DSA_KEY="dsa"

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"
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="org"
ORGANIZATION_UNIT="unit"
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"
CAfile_OPT="-cacert"
EXTN_LOCAL_SWCERT_FILE_EXT="swcert.local"
EXTN_REMOTE_SWCERT_FILE_EXT="swcert.remote"
EXTN_CACERT_FILE_EXT="cacert"
PORTSHOWCMD=/fabos/cliexec/portshow
PORTCFGCMD=/fabos/link_sbin/portcfg
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

VID=128
VF_ENABLED=1

#Extension error codes

#Extension common error codes
EXTN_SUCCESS=0
#Define error code to not conflict with standard exit codes.
EXTN_ERR=10
EXTN_ERR_NOT_SUPP=`expr $EXTN_ERR + 1`
EXTN_ERR_INVALID_ALGO=`expr $EXTN_ERR + 2`
EXTN_ERR_INVALID_KEYSIZE=`expr $EXTN_ERR + 3`
EXTN_ERR_INVALID_HASH=`expr $EXTN_ERR + 4`
EXTN_ERR_INVALID_ENTITY=`expr $EXTN_ERR + 5`
EXTN_ERR_NO_KEYPAIR=`expr $EXTN_ERR + 6`
EXTN_ERR_NO_CERT=`expr $EXTN_ERR + 7`
EXTN_ERR_NO_CERT_NO_KEYPAIR=`expr $EXTN_ERR + 8`
EXTN_ERR_NO_CSR_NO_KEYPAIR=`expr $EXTN_ERR + 9`
EXTN_ERR_NOT_SUPP_KEYPAIR=`expr $EXTN_ERR + 10`
EXTN_ERR_NOT_SUPP_CERT=`expr $EXTN_ERR + 11`
EXTN_ERR_NOT_SUPP_BOTH_KEYPAIR_CERT=`expr $EXTN_ERR + 12`
EXTN_ERR_NOT_SUPP_BOTH_KEYPAIR_CSR=`expr $EXTN_ERR + 13`
EXTN_ERR_NOT_SUPP_CERT_OR_KEYPAIR=`expr $EXTN_ERR + 14`
EXTN_ERR_INVALID_KEYPAIR_CHAR=`expr $EXTN_ERR + 15`
EXTN_ERR_INVALID_KEYPAIR_LEN=`expr $EXTN_ERR + 16`
EXTN_ERR_INVALID_CERT_NAME=`expr $EXTN_ERR + 17`
EXTN_ERR_INVALID_CERT_DOTS=`expr $EXTN_ERR + 18`
EXTN_ERR_INVALID_CERT_WITH_PATH=`expr $EXTN_ERR + 19`
EXTN_ERR_INVALID_CERT_FORMAT=`expr $EXTN_ERR + 20`
EXTN_ERR_INVALID_CSR_NAME=`expr $EXTN_ERR + 21`
EXTN_ERR_INVALID_CSR_DOTS=`expr $EXTN_ERR + 22`
EXTN_ERR_INVALID_CSR_CHARS=`expr $EXTN_ERR + 23`
EXTN_ERR_INVALID_CSR_WITH_PATH=`expr $EXTN_ERR + 24`
EXTN_ERR_INVALID_CSR_FORMAT=`expr $EXTN_ERR + 25`
EXTN_ERR_NOT_EXIST_CSR=`expr $EXTN_ERR + 26`
EXTN_ERR_NOT_EXIST_CERT=`expr $EXTN_ERR + 27`
EXTN_ERR_NOT_EXIST_CA_CERT=`expr $EXTN_ERR + 28`

#Extension error codes for generate
EXTN_ERR_GEN_MAX_KEYPAIR=`expr $EXTN_ERR + 29`
EXTN_ERR_GEN_KEYPAIR_EXISTS=`expr $EXTN_ERR + 30`
EXTN_ERR_GEN_KEY_GEN=`expr $EXTN_ERR + 31`
EXTN_ERR_GEN_CSR_GEN=`expr $EXTN_ERR + 32`
EXTN_ERR_GEN_V3_CREATE=`expr $EXTN_ERR + 33`
EXTN_ERR_GEN_HASH_CAL=`expr $EXTN_ERR + 34`
EXTN_ERR_GEN_CERT_GEN=`expr $EXTN_ERR + 35`

#Extension error codes for import/export
EXTN_ERR_IMPORT_NOT_FOUND_PVT_KEY=`expr $EXTN_ERR + 36`
EXTN_ERR_IMPORT_NOT_FOUND_CSR=`expr $EXTN_ERR + 37`
EXTN_ERR_IMPORT_NOT_SUPP_CACERT=`expr $EXTN_ERR + 38`
EXTN_ERR_IMPORT_NOT_FOUND_CA=`expr $EXTN_ERR + 39`
EXTN_ERR_IMPORT_COPY_FAIL=`expr $EXTN_ERR + 40`
EXTN_ERR_IMPORT_CERT_PVT_KEY_VERIFY_FAIL=`expr $EXTN_ERR + 41`
EXTN_ERR_IMPORT_CERT_VERIFICATION_ISSUE=`expr $EXTN_ERR + 42`
EXTN_ERR_IMPORT_CA_VERIFICATION_ISSUE=`expr $EXTN_ERR + 43`
EXTN_ERR_IMPORT_CERT_VERIFICATION_CERT_ISSUE=`expr $EXTN_ERR + 44`
EXTN_ERR_IMPORT_CERT_VERIFICATION_CA_ISSUE=`expr $EXTN_ERR + 45`
EXTN_ERR_IMPORT_HASH_CAL=`expr $EXTN_ERR + 46`

#Extension error codes for export
EXTN_ERR_EXP_COPY_FAIL=`expr $EXTN_ERR + 47`

#Extension error codes for delete
EXTN_ERR_DEL_KEYPAIR_IN_USE=`expr $EXTN_ERR + 48`
EXTN_ERR_CERT_IN_USE=`expr $EXTN_ERR + 49`
EXTN_ERR_EMPTY_FILE=`expr $EXTN_ERR + 50`
EXTN_ERR_WEAK_SIGN=`expr $EXTN_ERR + 51`

#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=`/fabos/cliexec/lscfg_util --switch $1 2> /dev/null`
		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 2> /dev/null)
			if [ -e /fabos/link_sbin/lscfg_test ]; then
				$RM /fabos/link_sbin/lscfg_test 2> /dev/null
			fi
		else
			eval $(/fabos/cliexec/lscfg_util --switch $1 2> /dev/null)
		fi
	else
		eval $(/fabos/cliexec/lscfg_util --chassis 2> /dev/null)
	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_TEMP=0
						 
	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_TEMP=`lscfg_test --fid 0 2> /dev/null`
		elif [ "$1" == "logical" ]; then
			VID_TEMP=`printenv | $GREP CURRENT_VF | cut -d"=" -f2`
		fi
	else
		VF_ENABLED=0
	fi
	
	if [ -e /fabos/link_sbin/lscfg_test ]; then
		$RM /fabos/link_sbin/lscfg_test 2> /dev/null
	fi

	return $VID_TEMP
}

# 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 == "all" ]; 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=0
	elif [ $heads -eq 0 ]; then
		$ECHO "Certificate in bad format."
		$ECHO "Warning: Certificate may be need conversion if it is in windows file format."
	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
}

setDefaultAttributeValues() {
	if [ "$keytype" == "none" ] ; then
		keytype=$RSA_KEY
	fi
	if [ "$keytype" == $RSA_KEY ] || [ "$keytype" == $DSA_KEY ] ; then
		if [ $key_size == "none" ]; then
			key_size="2048"
		fi
	else
		if [ "$key_size" == "none" ]; then
			key_size="P384"
		fi
	fi

	if [ "$hashtype" == "none" ]; then
		hashtype="sha256"
	fi
	if [ $years -eq 0 ]; then
		years=5
	fi
}

getecCurve() {
	if [ $1 == "P384" ]; then
		ec_curve="secp384r1"
	else
		return 1
	fi
	return 0
}

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/*$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/*$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/*$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() {
	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
    FABOS_SWITCHNO=0
	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
	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
	return 0
}

cleanUpHTTPS() {
	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
    FABOS_SWITCHNO=0

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

	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
}

syncUpFCAP() {
 
	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
    FABOS_SWITCHNO=0
	/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
	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
	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"
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit ${EXTN_ERR_GEN_MAX_KEYPAIR}
		fi
	fi

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

	$OPENSSL_CMD ecparam -genkey -name $curve -out "$pvtkeyfile" > /dev/null
	if [ $? != 0 ] ; then
		$ECHO "Key generation failed."
		deleteFiles 0 "$pvtkeyfile"
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit ${EXTN_ERR_GEN_KEY_GEN}
		fi
	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"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_GEN_CSR_GEN}
			fi
		fi
	fi

	trap 'cleanupOnTrap' 2 3

	if [[ -z $restCaller ]]; then
		#Prompt for required fields for generating a CSR.
		$ECHO "Input CSR details:"
		promptCSRInfo
	else
		promptCSRInfo
	fi

	if [ $? != 0 ]; then
		$ECHO "CSR Generation failed".
		$ECHO "Deleting key `basename $pvtkeyfile`"	
		deleteFiles 0 "$pvtkeyfile"
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit ${EXTN_ERR_GEN_CSR_GEN}
		fi
	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
		;;

	"$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
		elif [ "$keytype" == "$ECDSA_KEY" ]; then
			$OPENSSL_CMD ecparam -name $ec_curve -genkey -noout -out "$curdir/$certkey" -rand /usr/bin/openssl:/usr/bin/ssh 2> /dev/null
		else
			$OPENSSL_CMD dsaparam -genkey -noout -out "$curdir/$certkey" -rand /usr/bin/openssl:/usr/bin/ssh $key_size 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_SWITCHNO_TEMP=$FABOS_SWITCHNO
	    FABOS_SWITCHNO=0
		/fabos/cliexec/config save $curdir/$certkey
		/fabos/cliexec/config save $curdir/$csrfile
		/fabos/cliexec/config save $curdir
		FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

		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_SWITCHNO_TEMP=$FABOS_SWITCHNO
	    FABOS_SWITCHNO=0
		/fabos/cliexec/config save $PVT_KEY_FILE
		/fabos/cliexec/config save $CERT_DIR/$switchIp$CSR_SUFFIX
		/fabos/cliexec/config save $CERT_DIR
		FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
		$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"
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit ${EXTN_ERR_INVALID_CSR_NAME}
		fi
	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"
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit ${EXTN_ERR_INVALID_CSR_NAME}
		fi
	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"
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit ${EXTN_ERR_INVALID_CSR_DOTS}
		fi
	fi	

	$ECHO "$userInput" | $GREP '/' >/dev/null 2>&1
	if [ "$?" -eq 0 ]; then
		$ECHO "CSR file name cannot be provided with path"
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit ${EXTN_ERR_INVALID_CSR_WITH_PATH}
		fi
	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~@%_+:-]"
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit ${EXTN_ERR_INVALID_CSR_CHARS}
		fi
	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" ]] || [[ "$inputtype" == "$SYSLOG" && "$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" ]] || [[ "$inputtype" == "$SYSLOG" && "$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"
			if [[ ! -z $restCaller ]] && [ "$inputtype" == "$EXTN" ]; then
				exit ${EXTN_ERR_INVALID_CERT_NAME}
			else
				exit 1
			fi
		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"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_INVALID_CERT_DOTS}
				fi
			fi	
			$ECHO "$userInput" | $GREP '/' >/dev/null 2>&1
			if [ "$?" -eq 0 ]; then
				$ECHO "Certificate filename cannot be provided with path"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_INVALID_CERT_WITH_PATH}
				fi
			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~@%_+:-]"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_INVALID_KEYPAIR_CHARS}
				fi
			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 does not 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 does not exist";$ECHO
			if [[ ! -z $restCaller ]]; then
				exit $DEL_ERR_NO_CERT
			fi
			exit 0
		fi

		if [ "$fcapchksum" != "$httpschksum" ]; then
			$ECHO "$COMMONCERT $filetag does not 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
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		    FABOS_SWITCHNO=0
			inputfile=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`
			# Change the VF back to current context.
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			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
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		    FABOS_SWITCHNO=0
			inputfile=`/fabos/cliexec/config get $CERTCONFIG 5`
			# Change the VF back to current context.
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			compare_fcap_https_checksum $fcap_file $inputfile
		fi
		if [ "$delreq" == "CSR" -o "$delreq" == "ALL" ]; then
			filetag="csr"
			inputfile=$switchIp$CSR_SUFFIX
			# count_csr will check for number of files with .csr extension
			count_csr=`ls -1 $CERT_DIR/*$CSR_SUFFIX 2>/dev/null | wc -l`
			if [ -s $FCAP_DIR/$FCAP_SWCSR_FILE ] && [ $count_csr != 0 ]; 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/*$CSR_SUFFIX | $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/Venator (Gen6/Gen7)
# and Awing)
#
is_extn_platform()
{
	# Determine the system platform identifier.
	SWBD=$(sin | swbd 2> /dev/null)
	case ${SWBD##SWBD} in

		'148' | '178' | '165' | '166' | '179' | '180' )
			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 $userInput operation.."
			if [ -e ${EXTN_DIR}/${certpkey} ]; then
				$RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
			fi
			if [[ -z $restCaller ]]; then
				return 1
			else
				return ${EXTN_ERR_IMPORT_NOT_FOUND_PVT_KEY}
			fi
		fi
	else
		if [ ! -f $pvtkey ]; then
			$ECHO "The $inputtype key does not exist on the switch. Please generate $inputtype key and csr.Aborting $userInput operation.."
			if [ -e ./$userInput ]; then
					$RM ./$userInput 2> /dev/null
				fi
			if [[ -z $restCaller ]]; then
				return 1
			else
				return 111
			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 $userInput operation.."
			if [ -e $CERT_DIR/$userInput ]; then
				$RM $CERT_DIR/$userInput 2> /dev/null
			fi
			if [[ -z $restCaller ]]; then
				return 1
			else
				return 111
			fi
		fi	
	fi

	if [ "$inputtype" == "$FCAPS" ]; then
		certificate=./$userInput
	elif [ "$inputtype" == "$EXTN" ]; then
		certificate="${EXTN_DIR}/${certpkey}"
	else
		certificate=./$TEMP_CERT
	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
			if [[ -z $restCaller ]]; then
				return 1
			else
				return ${EXTN_ERR_IMPORT_NOT_FOUND_CSR}
			fi
		fi
	elif [ "$inputtype" != "$FCAPS" ]; then
		rsakey=`$GREP -c "BEGIN RSA PRIVATE KEY" $pvtkey`
		ecdsakey=`$GREP -c "BEGIN EC PRIVATE KEY" $pvtkey`
		if [ $rsakey -gt 0 ]; then
			pvt_key_type="rsa"
		elif [ $ecdsakey -gt 0 ]; then
			pvt_key_type="ec"
		else
			pvt_key_type="dsa"
		fi

		if [ $ecdsakey -gt 0 ]; then
			pvtkeyhash=`$OPENSSL_CMD $pvt_key_type -pubout -in $pvtkey 2> /dev/null | $OPENSSL_CMD_NO_FIPS md5`
			certkeyhash=`$OPENSSL_CMD x509 -noout -pubkey -in $certificate 2> /dev/null | $OPENSSL_CMD_NO_FIPS md5`
		else
			pvtkeyhash=`$OPENSSL_CMD $pvt_key_type -noout -modulus -in $pvtkey 2> /dev/null | $CUT -d "=" -f 2 | \
						$OPENSSL_CMD_NO_FIPS md5`
			certkeyhash=`$OPENSSL_CMD x509 -noout -modulus -in $certificate 2> /dev/null  | $CUT -d "=" -f 2 | \
						$OPENSSL_CMD_NO_FIPS md5`
		fi
	fi

	# Comparison 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
#	elif [ "$inputtype" == "$FCAPS" ]; then
#		certkeyhash=`$OPENSSL_CMD x509 -noout -modulus -in $certificate  2> /dev/null | $OPENSSL_CMD_NO_FIPS md5`
#		csrhash=`$OPENSSL_CMD req -in $csrFile -noout -modulus  2> /dev/null | $OPENSSL_CMD_NO_FIPS md5`
#		if [ "$certkeyhash" != "$csrhash" ]; then
#			invalSwCert=1
#		fi
#	fi

	if [ $invalSwCert -eq 1 ]; then
		$ECHO "Invalid switch certificate, verification with private key failed"
		$RM $certificate
		if [[ -z $restCaller ]]; then
			return 1
		else
			if [ "$inputtype" == "$EXTN" ]; then
				return ${EXTN_ERR_IMPORT_CERT_PVT_KEY_VERIFY_FAIL}
			else
				return 113
			fi	
		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() {
	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
    FABOS_SWITCHNO=0

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

	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
	if [ "$1" == "$configCert" ]; then
		certpkey="BRCD_HTTPS_SW"
	elif [ "$1" == "$caCert" ]; then
		certpkey="BRCD_HTTPS_CA"
	else
		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 != 0 ]; 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"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NOT_EXIST_CA_CERT}
				fi
			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 [ "$keypair" != "" ]; then
				#User provided keypair-tag option. Hence this is a local sw cert
				if [ "$filename" != "" ]; then
					extn_local_sw_cert=`$LS ${EXTN_DIR}/${filename}.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
				else
					extn_local_sw_cert=`$LS ${EXTN_DIR}/*.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX} 2> /dev/null`
				fi

				if [ "$extn_local_sw_cert" == "" ]; then
					$ECHO "Switch certificate $filename for keypair-tag ${keypair} does not exist."
					if [[ -z $restCaller ]]; then
						exit 1
					else
						exit ${EXTN_ERR_NOT_EXIST_CERT}
					fi
				fi

				#Check if this certificate is in use by ipsec_policy
				filename=`basename $extn_local_sw_cert | sed -e "s/".${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}"//"`
				$PORTSHOWCMD ipsec-policy | $GREP  "${filename}" > /dev/null 2>&1
				if [ $? -ne 1 ]; then
					$ECHO "${keypair} is in use by extension ipsec_policy"
					if [[ -z $restCaller ]]; then
						exit 1
					else
						exit ${EXTN_ERR_DEL_KEYPAIR_IN_USE}
					fi
				fi

				#delete pvt_key file too
				extn_csr_file=$EXTN_DIR/${keypair}${CSR_SUFFIX}
				extn_pvt_key_file=${EXTN_DIR}/${keypair}.${PVT_KEY}
				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
			elif [ "$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 [[ -z $restCaller ]]; 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
					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."
						if [[ -z $restCaller ]]; then
							exit 1
						else
							exit ${EXTN_ERR_NOT_EXIST_CERT}
						fi
					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}
					$PORTSHOWCMD ipsec-policy | $GREP  "${filename}" > /dev/null 2>&1
					if [ $? -ne 1 ]; then
						$ECHO "${filename} is in use by extension ipsec_policy"
						if [[ -z $restCaller ]]; then
							exit 1
						else
							exit ${EXTN_ERR_CERT_IN_USE}
						fi
					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
			fi
		elif [ "$delreq" == "CSR" ]; then
			if [ "$filename" != "" ]; then
				extn_files_to_delete=${EXTN_DIR}/${filename}
			else
				extn_files_to_delete=${EXTN_DIR}/${keypair}${CSR_SUFFIX}
			fi
			if [ ! -e $extn_files_to_delete ]; then
				if [ "$filename" != "" ]; then
					$ECHO "CSR ${filename} does not exist"
				else
					$ECHO "CSR for the keypair-tag ${keypair} does not exist"
				fi
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NOT_EXIST_CSR}
				fi
			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
			if [ "$filename" != "" ]; then
				extn_delete_prompt="${extn_delete_prompt}About to delete CSR -{$filename}"
			else
				extn_delete_prompt="${extn_delete_prompt}About to delete CSR for keypair_tag-{$keypair}"
			fi
			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
				keypair=`$ECHO $i | awk -F '.' ' { print $(NF-3) }'`
				filename=`basename $i | sed -e "s/".${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}"//"`
				#Check if this certificate is in use by ipsec_policy
				$PORTSHOWCMD ipsec-policy | $GREP  "${filename}" > /dev/null 2>&1	
				if [ $? -ne 1 ]; then	
					$ECHO "Extension Switch certificate ${filename} is in use by extension ipsec_policy"
					$ECHO "Aborting..."
					if [[ -z $restCaller ]]; then
						exit 1
					else
						exit ${EXTN_ERR_CERT_IN_USE}
					fi
				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
				keypair=`$ECHO $i | awk -F '.' ' { print $(NF-3) }'`
				filename=`basename $i | sed -e "s/".${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}"//"`
				#Check if this certificate is in use by ipsec_policy
				$PORTSHOWCMD ipsec-policy | $GREP  "${filename}" > /dev/null 2>&1
				if [ $? -ne 1 ]; then
					$ECHO "Extension Switch certificate ${filename} is in use by extension ipsec_policy"
					$ECHO "Aborting..."
					if [[ -z $restCaller ]]; then
						exit 1
					else
						exit ${EXTN_ERR_CERT_IN_USE}
					fi
				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
			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
				$CAT /dev/null > $i
				#FCAP files are installed (created) along with firmware,
				#removal results in firmware commit failure during download
				if [ "$inputtype" != "$FCAPS" ]; then
					$RM -rf $i > /dev/null
				fi
				/fabos/cliexec/config save $i
			fi
		done
	else
		#TODO: Read back the file before delete
		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
			$CAT /dev/null > $i
			#FCAP files are installed (created) along with firmware,
			#removal results in firmware commit failure during download
			if [ "$inputtype" != "$FCAPS" ]; then
				$RM -rf $i > /dev/null
			fi
			/fabos/cliexec/config save $i
		done
	fi
	return 0
}


check_https_files() {

	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
    FABOS_SWITCHNO=0
	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

	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

	return $https_exist
}


#
# 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
			if [ $commoncert -eq 1 ]; then
				$ECHO "About to delete commoncert $optag file(s)"
				$ECHO "This will disable secure protocols such as HTTPS and"
				$ECHO "ISLs may be segmented during next E-port(s) bring-up"
			else
				$ECHO "About to delete $inputtype $optag file(s)"
				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"
				fi
			fi
		elif [ "$delreq" == "ALL" ]; then
			if [ "$inputtype" == "$DEFAULT" ]; then
				$ECHO "About to delete all certificate files and configurations"
			else
				if [ $commoncert -eq 1 ]; then
					$ECHO "About to delete all commoncert certificate files and configurations"
					$ECHO "This will disable secure protocols such as HTTPS and"
					$ECHO "ISLs may be segmented during next E-port(s) bring-up"
				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"
					fi
				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 does not exist"
				return 1;
			fi

			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		    FABOS_SWITCHNO=0
			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/$FCAP_CACERT_FILE
			/fabos/cliexec/config save $FCAP_DIR
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			$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 does not exist"
				return 1
			fi
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		    FABOS_SWITCHNO=0
			zeroizeFiles $FCAP_DIR/$FCAP_SWCERT_FILE $FCAP_DIR/$FCAP_TOUCH_FILE
			updateFCAPConfigFile "SWITCH_CERT_NAME:None"
			/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
			/fabos/cliexec/config save $FCAP_DIR
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			$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

			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		    FABOS_SWITCHNO=0

			# /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
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			syncUpFCAP

			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 does not 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 does not 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 does not 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 does not 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
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		    FABOS_SWITCHNO=0
			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.
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			$AUDIT_NOTIFY "$CERT_DELE" "$file" "BRCD_HTTPS_CA"
			isDeleteOk=$DELETE_SUCCESS
		elif [ "$delreq" == "CERT" ]; then
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		    FABOS_SWITCHNO=0
			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.
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			$AUDIT_NOTIFY "$CERT_DELE" "$file" "BRCD_HTTPS_SW"
			isDeleteOk=$DELETE_SUCCESS
		else
			if [ $debug -eq 1 ]; then
				$ECHO "Removing all HTTPS Keys/Certificates"
				delall="all"
			fi
			cleanUpHTTPS
		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 does not 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" ""
		# ASC module also adds Kafka certificate into CURL repository for
		# schema server https connection.
		$WEBLNOTIFY $ASC:$CERT_DELE
		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
		/fabos/cliexec/config save $EXTN_DIR
	fi
	

	return 0
}

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

confirmSelfSignedCertGenerate() {
	
	if [ "$response" == "no" ]; then
		$ECHO "Generating a new certificate will automatically do the following"
		$ECHO "1. Delete existing switch certificate(s)."
		$ECHO "2. Disable secure protocol HTTPS"
		$ECHO
		$ECHO "Warning: Certificate generation is CPU intensive and can cause high CPU usage"
		$ECHO

		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 create file that specifies certificate extensions to use"
			$ECHO "Deleting key `basename $pvtkeyfile`"
			deleteFiles 0 "$pvtkeyfile"
			$ECHO "Deleting CSR `basename $csrfile`"
			deleteFiles 0 "$csrfile"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_GEN_V3_CREATE}
			fi
		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
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_GEN_HASH_CAL}
			fi
		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
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit ${EXTN_ERR_GEN_CERT_GEN}
		fi
	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

	cleanUpHTTPS

	cd $TEMP_CERTGEN_PATH

	if [ "$keytype" == $ECDSA_KEY ]; then
		$OPENSSL_CMD ecparam -name $ec_curve -out $ECDSA_PARAMS_FILE 2> /dev/null
	elif [ "$keytype" == $DSA_KEY ]; 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_KEY ]; 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
	elif [ "$keytype" == $ECDSA_KEY ]; then
		$OPENSSL_CMD req -nodes -x509 -config $EMBEDDED_OPENSSL_CONF -newkey ec:$ECDSA_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 
	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

	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
	FABOS_SWITCHNO=0

	/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

	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

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

# Input filename, keypair and filepath
displayFileSummary() {
	if [ $hexdump -eq 1 ]; then
		$ECHO ""
		$OPENSSL_CMD x509 -in "$3"
		ret=$?
		$ECHO ""
	else
		$ECHO ""
		$OPENSSL_CMD x509 -in "$3" -noout -custom \
			-nameopt multiline -subject -issuer -dates -fingerprint -custom 2> /dev/null
		ret=$?
		if [ $ret -eq 0 ]; then
			dgst=`$OPENSSL_CMD_NO_FIPS dgst -r -sha1 "$3" 2> /dev/null`
			ret=$?
			if [ $ret -eq 0 ] ; then
				hash=`$ECHO $dgst | cut -d ' ' -f 1`
				if [ -f "$3.hash" ]; then
					import_hash=`$CAT $3.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
				#Display the hexdump as well for REST
				if [[ ! -z $restCaller ]]; then
					$OPENSSL_CMD x509 -in "$3"
					ret=$?
				fi
			fi
		fi
	fi
	if [ $ret != 0 ]; then
		if [ ! -z "$keypair" ] && [ ! -z "$filename" ]; then
			$ECHO "Certificate $1 with keypair $2: Is an unknown x509 format."
		elif [ ! -z "$keypair" ]; then
			$ECHO "Certificate with keypair $2: Is an unknown x509 format."
		elif [ ! -z "$filename" ]; then
			$ECHO "Certificate $1: Is an unknown x509 format."
		fi
		if [[ -z $restCaller ]]; then
			exit 1
		else
			exit ${EXTN_ERR_INVALID_CERT_FORMAT}
		fi
	fi
}


showFilesExtn() {

	file_summary=0
	filename_path=""
	local_filename_path=""
	remote_filename_path=""
	file_LocalSwCert=""
	file_RemoteSwCert=""
	file_CaCert=""
	file_LocalSwCsr=""

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

	if [ $extnLocalSwCert -eq 1 ] && [ $extnRemoteSwCert -eq 1 ]; then
		if [ ! -z "$filename" ]; then
			local_filename_path=`$LS ${EXTN_DIR}/${filename}.*.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
			remote_filename_path=`$LS ${EXTN_DIR}/${filename}.nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
		else
			file_LocalSwCert=`$LS ${EXTN_DIR}/*.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}	2> /dev/null`
			file_RemoteSwCert=`$LS ${EXTN_DIR}/*.nohash.${EXTN_REMOTE_SWCERT_FILE_EXT}${PEM_SUFFIX}  2> /dev/null`
		fi
	elif [ $extnLocalSwCert -eq 1 ]; then
		if [ ! -z "$keypair" ] && [ ! -z "$filename" ]; then
			local_filename_path=`$LS ${EXTN_DIR}/${filename}.${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}	2> /dev/null`
		elif [ ! -z "$keypair" ]; then
			local_filename_path=`$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
	elif [ $extnRemoteSwCert -eq 1 ]; then
		if [ ! -z "$filename" ]; then
			remote_filename_path=`$LS ${EXTN_DIR}/${filename}.nohash.${EXTN_REMOTE_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`
		elif [ ! -z "$keypair" ]; then
			filename_path=`$LS ${EXTN_DIR}/${keypair}${CSR_SUFFIX}	2> /dev/null`
		else
			file_LocalSwCsr=`$LS ${EXTN_DIR}/*${CSR_SUFFIX}  2> /dev/null`
		fi
	fi

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

		if [ $file_summary -eq 1 ]; then

			if [ $extnLocalSwCsr -eq 1 ]; then
				if [ ! -z "$filename" ]; then
					$ECHO "Displaying contents of $showreq $filename"
				else
					$ECHO "Displaying contents of $showreq with keypair_tag $keypair"
				fi
				$ECHO ""
				if [ $hexdump -eq 1 ]; then
					$OPENSSL_CMD req -in "$filename_path"
					ret=$?
				else
					$OPENSSL_CMD req -in "$filename_path" -noout -text -custom \
						-nameopt multiline -config $CONFIG_FILE 2> /dev/null
					ret=$?
					if [ $ret == 0 ]; then
						if [[ ! -z $restCaller ]]; then
							$ECHO ""
							$OPENSSL_CMD req -in "$filename_path"
							ret=$?
						fi
					fi
				fi
				if [ $ret != 0 ]; then
					if [ ! -z "$filename" ]; then
						$ECHO "$filename: Is an unknown CSR format."
					else
						$ECHO "CSR with keypair_tag $keypair: Is an unknown CSR format."
					fi
					if [[ -z $restCaller ]]; then
						exit 1
					else
						exit ${EXTN_ERR_INVALID_CSR_FORMAT}
					fi
				fi
				exit 0
			fi

			if [ $extnLocalSwCert -eq 1 ] &&  [ $extnRemoteSwCert -eq 1 ]; then
				if [ ! -z "$local_filename_path" ]; then
					$ECHO "Displaying contents of local $showreq $filename"
					displayFileSummary "$filename" "$keypair" "$local_filename_path"
				fi
				if [ ! -z "$remote_filename_path" ]; then
					$ECHO "Displaying contents of remote $showreq $filename"
					displayFileSummary	"$filename" "$keypair" "$remote_filename_path"
				fi
			elif [ $extnLocalSwCert -eq 1 ]; then
				if [ ! -z "$keypair" ] && [ ! -z "$filename" ]; then
					$ECHO "Displaying contents of local $showreq $filename with keypair_tag $keypair"
					displayFileSummary "$filename" "$keypair" "$local_filename_path"
				elif [ ! -z "$keypair" ]; then
					$ECHO "Displaying contents of local $showreq with keypair_tag $keypair"
					displayFileSummary "$filename" "$keypair" "$local_filename_path"
				fi
			elif [ $extnRemoteSwCert -eq 1 ]; then
				$ECHO "Displaying contents of remote $showreq $filename"
				displayFileSummary "$filename" "$keypair" "$remote_filename_path"
			else
				$ECHO "Displaying contents of $showreq $filename"
				displayFileSummary "$filename" "$keypair" "$filename_path"
			fi

			exit 0
		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 ] && [ $extnRemoteSwCert -eq 1 ]; then
				$ECHO "No $showreq $filename found."
			elif [ $extnLocalSwCert -eq 1 ] ; then
				$ECHO "No local $showreq $filename with keypair_tag $keypair found."
			elif [ $extnRemoteSwCert -eq 1 ] ; then
				$ECHO "No remote $showreq $filename found."
			elif [ $extnLocalSwCsr -eq 1 ]; then
				if [ ! -z "$filename" ]; then
					$ECHO "No $showreq $filename found."
				else
					$ECHO "No $showreq with keypair_tag $keypair found."
				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
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0
			inputfile=`/fabos/cliexec/config get $CERTCONFIG 5`
			# Change the VF back to current context.
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			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
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0
			inputfile=`/fabos/cliexec/config get $CERTCONFIG 5`
			# Change the VF back to current context.
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			$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
		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
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0
			inputfile=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`
			# Change the VF back to current context.
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			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
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0
			inputfile=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`
			# Change the VF back to current context.
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			$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" == "$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
	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>)|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>"
	$ECHO "		[-f] - no warning"
	$ECHO 
}

importUsage() {
	$ECHO
	$ECHO "Usage:"
	$ECHO "seccertmgmt import"
	$ECHO "		-cert <fcap|commoncert|https|radius|ldap|syslog|extn>"
	$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>"
	$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>>"
	$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 $1 ] && [ $highSecurityModeFlag -eq 0 ]; then
		output=`$OPENSSL_CMD_NO_FIPS verify ./$1 2> /dev/null | $GREP "error" | $AWK ' {print $1$2} '`
		if [ "$output" == "error18" ] ; then
			$ECHO "Self signed certificate cannot be imported"
			$RM -rf ./$1 2> /dev/null
			if [ -f ./$userInput ]; then
				$RM -rf ./$userInput 2> /dev/null
			fi
			exit 18
		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

}

checkWeakAlgo() {
	signAlgo=""
	signAlgo=`$OPENSSL_CMD x509 -in $1 -text -noout 2> /dev/null| \
					$GREP -m 1 "Signature Algorithm:" 2> /dev/null`

	case "$signAlgo" in
		(*"md5"* | *"MD5"*)
			$RM $1 2> /dev/null
			$ECHO "Error: Certificate import failed, signature algorithm has md5"
			if [[ -z $restCaller ]]; then
				return 1
			else
				if [ $extn -eq 1 ]; then
					return ${EXTN_ERR_WEAK_SIGN} 
				else
					return 122
				fi
			fi
		;;
	esac

	return 0
}

#Get certificate algo details
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"* | *"SHA1"*) AuditSha=sha1;;
		(*"sha224"* | *"SHA224"*) AuditSha=sha224;;
		(*"sha256"* | *"SHA256"*) AuditSha=sha256;;
		(*"sha384"* | *"SHA384"*) AuditSha=sha384;;
		(*"sha512"* | *"SHA512"*) AuditSha=sha512;;
		(*"md5"* | *"MD5"*) AuditSha=md5;;
	esac
	case "$AuditSz" in
	    (*"256"*) AuditSz=256;;
		(*"512"*) AuditSz=512;;
		(*"768"*) AuditSz=768;;
		(*"1024"*) AuditSz=1024;;
		(*"2048"*) AuditSz=2048;;
		(*"3072"*) AuditSz=3072;;
		(*"4096"*) AuditSz=4096;;
		(*"8192"*) AuditSz=8192;;
		(*"P384"*) AuditSz=384;;
	esac

#Below has no significance, commenting out
#	if [ ! -z "$fips_mode" ] && [ $fips_mode -eq 1 ]; then
#		if [ $AuditSz != "2048" ] || [ $AuditSha != "sha256" ]; then
#			if [[ -z $restCaller ]]; then
#				$ECHO -n "You are importing a Non-FIPS compliant certificate."
	
#				secOpConfirm

#				if [ $? -eq 1 ]; then
#					return 1
#				fi
#			else
#				return 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
	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
}

certFormatValidate() {

	if [ "$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
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_INVALID_CERT_FORMAT}
			fi
		fi
	elif [ "$inputtype" != "$KAFKA" ]; then
		cLen=`expr length $1`
		let dotIndex="$cLen"-3
		fileSuffix=`expr substr $1 $dotIndex $cLen`

		if [ "$impreq" == "CA" ]; then
			TEMP_DST_FILE=$TEMP_CACERT
		else
			TEMP_DST_FILE=$TEMP_CERT
		fi

		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
                        # Identify encoding(DER or PEM)
                        $OPENSSL_CMD x509 -in ./$1 -text -noout  > /dev/null 2>&1
                        if [ $? != 0 ]; then
				$OPENSSL_CMD x509 -in ./$1 -inform DER -outform PEM -out ./$TEMP_DST_FILE > /dev/null 2>&1

				if [ $? != 0 ]; then
					$ECHO "Failed to convert certificate to .pem"
					$RM ./$1 2> /dev/null
					if [[ -z $restCaller ]]; then
						exit 1
					else
						exit 117
					fi
				fi
				$RM ./$1 2> /dev/null
			else
				$MV ./$1 ./$TEMP_DST_FILE
			fi
		else
			#validate the file format
			$OPENSSL_CMD x509 -in ./$1 -inform PEM -outform DER -out ./$1.der > /dev/null 2>&1
			if [ $? != 0 ]; then
				$ECHO "Bad format certificate. Exiting.."
				$RM ./$1 2> /dev/null
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit 112
				fi
			fi
			if [ -f ./$1.der ]; then
				$RM ./$1.der 2> /dev/null
			fi
			$MV ./$1 ./$TEMP_DST_FILE
		fi
	fi
}
copyfromremote() {

	cLen=`expr length $userInput`
	let dotIndex="$cLen"-3
	fileSuffix=`expr substr $userInput $dotIndex $cLen`

	if [ "$protocol" == "$PROT_FTP" ]; then
		if [ $extn -eq 1 ]; then
			/bin/wget -T 60 -t 1 --user=$userName --password=$password1 \
				ftp://$ipAddr/$remoteDir/$userInput -O ${EXTN_DIR}/${certpkey} 2> /dev/null
			if [ $? != 0 ]; then
				/bin/wget -T 60 -t 1 --user=$userName --password=$password1 \
					ftp://\[$ipAddr\]/$remoteDir/$userInput -O ${EXTN_DIR}/${certpkey} 2> /dev/null
			fi
		else
			/bin/wget -T 60 -t 1 --user=$userName --password=$password1 \
				ftp://$ipAddr/$remoteDir/$userInput -O ./temp$impreq$fileSuffix 2> /dev/null
			if [ $? != 0 ]; then
				/bin/wget -T 60 -t 1 --user=$userName --password=$password1 \
					ftp://\[$ipAddr\]/$remoteDir/$userInput -O ./temp$impreq$fileSuffix 2> /dev/null
			fi
		fi
	else
		if [ $extn -eq 1 ]; then
			if [[ ! -z $password1 ]]; then
				/usr/bin/scp -q -oStrictHostKeyChecking=no -oSSHPassword=$password1\
					$userName@\[$ipAddr\]:$remoteDir/$userInput $EXTN_DIR/$certpkey 2> /dev/null
			else
				/usr/bin/scp -q -oStrictHostKeyChecking=no \
					$userName@\[$ipAddr\]:$remoteDir/$userInput $EXTN_DIR/$certpkey 2> /dev/null
			fi
		else
			if [[ ! -z $password1 ]]; then
				/usr/bin/scp -q -oStrictHostKeyChecking=no -oSSHPassword=$password1\
					$userName@\[$ipAddr\]:$remoteDir/$userInput ./temp$impreq$fileSuffix 2> /dev/null
			else
				/usr/bin/scp -q -oStrictHostKeyChecking=no \
					$userName@\[$ipAddr\]:$remoteDir/$userInput ./temp$impreq$fileSuffix 2> /dev/null
			fi
		fi	
	fi

	if [ $? != 0 ]; then
		$ECHO "Error: Certificate import failed. Please check the certificate location and user credentials."

		if [ "$protocol" == "$PROT_FTP" ] && [ $extn -eq 1 ]; then
			$RM ${EXTN_DIR}/${certpkey} 2> /dev/null
		elif [ "$protocol" == "$PROT_FTP" ] && [ $extn -ne 1 ]; then
			$RM ./temp$impreq$fileSuffix 2> /dev/null
		fi

		if [[ -z $restCaller ]]; then
			exit 1
		else
			if [ $extn -eq 1 ]; then
				exit ${EXTN_ERR_IMPORT_COPY_FAIL}
			else
				exit 1
			fi
		fi
	fi

	# Check for empty file
	if [ $extn -eq 1 ]; then
		if [ ! -s ${EXTN_DIR}/${certpkey} ]; then
			$RM ${EXTN_DIR}/${certpkey} 2> /dev/null
			$ECHO "Error: Certificate import failed, file is empty"
			exit ${EXTN_ERR_EMPTY_FILE}
		fi
	else
		if [ ! -s ./temp$impreq$fileSuffix ]; then
			$RM ./temp$impreq$fileSuffix 2> /dev/null 
			$ECHO "Error: Certificate import failed, file is empty"
			exit 121			#These hardcoded exit codes needs to be replaced with macros
		fi
	fi
	certFormatValidate ./temp$impreq$fileSuffix
	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
	switch_cert_err=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/$TEMP_CACERT
			return_val_imported_file=$?
			if [ $return_val_imported_file -eq 0 ]; then
				$RM -rf $FCAP_DIR/$TEMP_CACERT 2> /dev/null
				if [[ -z $restCaller ]]; then
					exit 1;
				else
					exit 112
				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/$TEMP_CACERT
			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/$TEMP_CACERT 2> /dev/null
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit 114
				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/$TEMP_CACERT`;	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/$TEMP_CACERT $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/$TEMP_CACERT 2> /dev/null
								$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
								$ECHO "Import failed"
								exit $check
							fi
						else
							printError
							$RM $FCAP_DIR/$TEMP_CACERT 2> /dev/null
							$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
							$ECHO "Import failed"
							exit $check
						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/$TEMP_CACERT 2> /dev/null
							$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
							if [[ -z $restCaller ]]; then
								exit 1
							else
								exit 115
							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
						if [ $commonCert -ne 1 ]; then
							$RM $FCAP_DIR/$TEMP_CACERT 2> /dev/null
							$ECHO "Success: $1ed fcap ca certificate ["$userInput"]."
						else
							$ECHO "Success: $1ed commoncert ca certificate ["$userInput"]."
						fi
						$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
						return 0 
					fi
				done
			done
			IFS=${IFS_};
			# Certificate compliance with FIPs mode
			#Get certificate algo details
			checkForFIPsCompl $FCAP_DIR/$TEMP_CACERT

			# If reached here, then we can append new imported certificate to the existing list of certificates.
			$CAT $FCAP_DIR/$TEMP_CACERT >> $FCAP_DIR/$FCAP_CACERT_FILE
			$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
			updateFCAPConfigFile "ROOT_CA_CERTIFICATES:$total_certs"
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0

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

			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

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

			if [ $commonCert -eq 1 ]; then
				$ECHO "Success: $1ed commoncert ca certificate ["$userInput"]."
			else
				$RM $FCAP_DIR/$TEMP_CACERT 2> /dev/null
				$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/$TEMP_CERT
			return_val_imported_file=$?
			if [ $return_val_imported_file -eq 0 ]; then
				$RM -rf $FCAP_DIR/$TEMP_CERT 2> /dev/null
				$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
				if [[ -z $restCaller ]]; then
					exit 1;
				else
					exit 112
				fi
			fi

			flag=1
			copy_cert=0
			counter=0
			response="no"
			output="NO"
			if [ $swbd == "SWBD117" ]; then
				validateSelfSigned $FCAP_DIR/$TEMP_CERT
			fi
			# Checking if root CA certificate exists for the imported sw cert.
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0

			httpsCaCert=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`

            FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

			if [[ ! -s $FCAP_DIR/$FCAP_CACERT_FILE ]] || [[ $commonCert -eq 1  && ! -s $CERT_DIR/$httpsCaCert ]]; then
				$ECHO "Please import CA certificate  before importing switch certificate."
				$RM $FCAP_DIR/$TEMP_CERT 2> /dev/null
				$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit 116
				fi
			fi

			output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $FCAP_DIR/$FCAP_CACERT_FILE $FCAP_DIR/$TEMP_CERT 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/$TEMP_CERT 2> /dev/null
				$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit $check
				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 $FCAP_DIR/$TEMP_CERT
				retvar=$?
				if [ $retvar != 0 ]; then
					$RM $FCAP_DIR/$TEMP_CERT 2> /dev/null
					exit $retvar
				fi
				# Certificate compliance with FIPs mode
				#Get certificate algo details
				checkForFIPsCompl $FCAP_DIR/$TEMP_CERT
				#Certificate signature algorithm should not have md5
				checkWeakAlgo $FCAP_DIR/$TEMP_CERT
				retvar=$?
				if [ $retvar != 0 ]; then
					$RM $FCAP_DIR/$TEMP_CERT 2> /dev/null
					exit $retvar
				fi
			fi

			if [ $? != 0 ]; then
				$ECHO "Operation cancelled."
				$RM $FCAP_DIR/$TEMP_CERT 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/$TEMP_CERT`; 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/$TEMP_CERT 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:$TEMP_CERT"
			cp $FCAP_DIR/$FCAP_TEMP_FILE $FCAP_DIR/$FCAP_SWCERT_FILE
			cp $FCAP_DIR/$TEMP_CERT $FCAP_DIR/$FCAP_TOUCH_FILE
			$RM -rf $FCAP_DIR/$TEMP_CERT 2> /dev/null
			$RM -rf $FCAP_DIR/$FCAP_TEMP_FILE 2> /dev/null
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0

			/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

			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

			$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

			#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/$TEMP_CACERT -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/$TEMP_CACERT $RADIUS_DIR/$TEMP_CACERT 2> /dev/null`
			check=`$ECHO "$output" | $AWK ' {print $2} '`
			if [ "$check" != "OK" ] ; then
				printError
				$RM $RADIUS_DIR/$TEMP_CACERT 2> /dev/null
				$ECHO "Import failed"
				exit $check
			fi

			# Certificate compliance with FIPs mode
			#Get certificate algo details
			checkForFIPsCompl $RADIUS_DIR/$TEMP_CACERT

			if [ "$CAFlag" == "client" ]; then
				$CAT $RADIUS_DIR/$TEMP_CACERT >> $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE
				/fabos/cliexec/config save $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE
			else
				$CAT $RADIUS_DIR/$TEMP_CACERT >> $RADIUS_DIR/$RADIUS_CACERT_FILE
				/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 $RADIUS_DIR/$TEMP_CERT
			fi

			if [ ! -s $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE ]; then
				$ECHO "Error: CA certificate not found, please import the CA certificate"
				$RM $RADIUS_DIR/$TEMP_CERT 2> /dev/null
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit 116
				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 -purpose sslclient $RADIUS_DIR/$TEMP_CERT 2> /dev/null`
			else
				output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $RADIUS_DIR/$RADIUS_CLIENT_CACERT_FILE -purpose sslclient $RADIUS_DIR/$TEMP_CERT 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/$TEMP_CERT 2> /dev/null
				exit $check
			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_hostip "$switchIp" $RADIUS_DIR/$TEMP_CERT 2> /dev/null`
				#check=`$ECHO "$output" | $AWK ' {print $2} '`
			#	 if [ "$check" != "OK" ]; then
		#			printError
		#			 $RM $RADIUS_DIR/$TEMP_CERT 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/$TEMP_CERT 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/$TEMP_CERT 2> /dev/null
		#				exit 1
		#		 fi
		#fi

			# Certificate compliance wimh FIPs mode
			#Get certificate algo details
			checkForFIPsCompl $RADIUS_DIR/$TEMP_CERT

			# validate the certificate by comparing with private key and csr of the switch
			certPvtKeyValidate $RADIUS_DIR/$TEMP_CERT
			retvar=$?
			if [ $retvar != 0 ]; then
				$RM $RADIUS_DIR/$TEMP_CERT 2> /dev/null
				exit $retvar
			fi
			#Certificate signature algorithm should not have md5
			checkWeakAlgo $RADIUS_DIR/$TEMP_CERT
			retvar=$?
			if [ $retvar != 0 ]; then
				$RM $RADIUS_DIR/$TEMP_CERT 2> /dev/null
				exit $retvar
			fi

			$MV $RADIUS_DIR/$TEMP_CERT $RADIUS_DIR/$RADIUS_SWCERT_FILE
			$RM $RADIUS_DIR/$TEMP_CERT 2> /dev/null

			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0

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

			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			$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

		#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/$TEMP_CACERT -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/$TEMP_CACERT $LDAP_DIR/$TEMP_CACERT 2> /dev/null`
			check=`$ECHO "$output" | $AWK ' {print $2} '`
			if [ "$check" != "OK" ] ; then
				printError
				$RM $LDAP_DIR/$TEMP_CACERT 2> /dev/null
				$ECHO "Import failed"
				exit $check
			fi

			# Certificate compliance with FIPs mode
			#Get certificate algo details
			checkForFIPsCompl $LDAP_DIR/$TEMP_CACERT

			if [ "$CAFlag" == "client" ]; then
				$CAT $LDAP_DIR/$TEMP_CACERT >> $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE
				/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
				/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 $LDAP_DIR/$TEMP_CERT
			fi

			if [ ! -s $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE ]; then
				$ECHO "Error: CA certificate not found, please import the CA certificate"
				$RM $LDAP_DIR/$TEMP_CERT 2> /dev/null
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit 116
				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 -purpose sslclient $LDAP_DIR/$TEMP_CERT 2> /dev/null`
			else
				output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $LDAP_DIR/$LDAP_CLIENT_CACERT_FILE -purpose sslclient $LDAP_DIR/$TEMP_CERT 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/$TEMP_CERT 2> /dev/null
				exit $check
			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_hostip "$switchIp" $LDAP_DIR/$TEMP_CERT 2> /dev/null`
				#check=`$ECHO "$output" | $AWK ' {print $2} '`
			#	 if [ "$check" != "OK" ]; then
		#			printError
		#			$RM $LDAP_DIR/$TEMP_CERT 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/$TEMP_CERT 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/$TEMP_CERT 2> /dev/null
		#				exit 1
		#		 fi
		#fi

			# Certificate compliance wimh FIPs mode
			#Get certificate algo details
			checkForFIPsCompl $LDAP_DIR/$TEMP_CERT

			# validate the certificate by comparing with private key and csr of the switch
			certPvtKeyValidate $LDAP_DIR/$TEMP_CERT
			retvar=$?
			if [ $retvar != 0 ]; then
				$RM $LDAP_DIR/$TEMP_CERT 2> /dev/null
				exit $retvar
			fi
			#Certificate signature algorithm should not have md5
			checkWeakAlgo $LDAP_DIR/$TEMP_CERT
			retvar=$?
			if [ $retvar != 0 ]; then
				$RM $LDAP_DIR/$TEMP_CERT 2> /dev/null
				exit $retvar
			fi

			$CP $LDAP_DIR/$TEMP_CERT $LDAP_DIR/$LDAP_SWCERT_FILE
			$RM $LDAP_DIR/$TEMP_CERT 2> /dev/null

			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0

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

			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			$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
			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 118
				fi
			fi

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

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

            # Certificate compliance with FIPs mode
			#Get certificate algo details
			checkForFIPsCompl $SYSLOG_DIR/$TEMP_CACERT

			if [ "$CAFlag" == "server" ]; then
				# User has imported Syslog CA certificate with .pem extension
				certpkey="BRCD_SYSLOG_1"

				# Delete existing symbolic link and reference file before replacing
				# newly imported certificate with existing
				if [ -s $SYSLOG_DIR/$SYSLOG_CACERT_FILE ]; then
					SYSLOG_LINK=`$CAT $SYSLOG_DIR/$SYSLOG_LINK_HASH | $GREP '' | $AWK ' { print $2 }'`
					# Cleanup the SYSLOGCA_DIR from stale symbolic links
					$RM -f $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
				fi

				mv $SYSLOG_DIR/$TEMP_CACERT $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/$TEMP_CACERT $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 $SYSLOG_DIR/$TEMP_CERT
			fi

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

			if [ "$AuditLogMode" == "Strict" ]; then
				output=`$OPENSSL_CMD_NO_FIPS verify -cert_strict -CAfile $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE -purpose sslclient $SYSLOG_DIR/$TEMP_CERT 2> /dev/null`
			else
				output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE -purpose sslclient $SYSLOG_DIR/$TEMP_CERT 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/$TEMP_CERT 2> /dev/null
				exit $check
			fi

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

		
			#OCSP Revocation Check Validation
			if [ "$AuditLogMode" == "Strict" ]; then
				output=`$OPENSSL_CMD_NO_FIPS verify -cert_strict -ocsp_check -CAfile $SYSLOG_DIR/$SYSLOG_CLIENT_CACERT_FILE $SYSLOG_DIR/$TEMP_CERT 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/$TEMP_CERT 2> /dev/null
					exit $check
				fi
			fi

			# Certificate compliance wimh FIPs mode
			#Get certificate algo details
			checkForFIPsCompl $SYSLOG_DIR/$TEMP_CERT

			# validate the certificate by comparing with private key and csr of the switch
			certPvtKeyValidate $SYSLOG_DIR/$TEMP_CERT
			retvar=$?
			if [ $retvar != 0 ]; then
				$RM $SYSLOG_DIR/$TEMP_CERT 2> /dev/null
				exit $retvar
			fi
			#Certificate signature algorithm should not have md5
			checkWeakAlgo $SYSLOG_DIR/$TEMP_CERT
			retvar=$?
			if [ $retvar != 0 ]; then
				$RM $SYSLOG_DIR/$TEMP_CERT 2> /dev/null
				exit $retvar
			fi

			$CP $SYSLOG_DIR/$TEMP_CERT $SYSLOG_DIR/$SYSLOG_SWCERT_FILE
			$RM $SYSLOG_DIR/$TEMP_CERT 2> /dev/null

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

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

			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			$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 112
			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 112
				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 $check
			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

			#Get certificate algo details
			checkForFIPsCompl $TMP_DIR/$userInput
				
			# 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" "" ""
			# ASC module also adds Kafka certificate into CURL repository for
			# schema server https connection.
			$WEBLNOTIFY $ASC:$CERT_IMPORT

			$ECHO "Success: $1ed $inputtype $CAFlag CA certificate ["$certFileName"]."
		fi
	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 $TEMP_CACERT ]; then
			output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $ASC_DIR/$TEMP_CACERT $ASC_DIR/$TEMP_CACERT 2> /dev/null`
			check=`$ECHO "$output" | $AWK ' {print $2} '`
			if [ "$check" != "OK" ]; then
				printError
				$RM $ASC_DIR/$TEMP_CACERT 2> /dev/null
				exit $check
			fi
			openssl x509 -in $TEMP_CACERT -issuer | head -1 > /tmp/$userInput.issuer
			openssl x509 -in $TEMP_CACERT -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

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

		# Certificate compliance with FIPs mode
		#Get certificate algo details
		checkForFIPsCompl $ASC_DIR/$TEMP_CACERT

		if [ -f $ASC_DIR/$TEMP_CACERT ]; then
			$CAT $ASC_DIR/$TEMP_CACERT > $ASC_DIR/$ASC_CACERT_FILE
			deleteFiles 0 $ASC_DIR/$TEMP_CACERT
		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

		FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		FABOS_SWITCHNO=0
		/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

		FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

		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

			#Do not allow reimport if the certificate is in use by IPsec policy
			if [ $extnLocalSwCert -eq 1 ]; then
				oldFilename=`basename $oldFile | sed -e "s/".${keypair}.${EXTN_LOCAL_SWCERT_FILE_EXT}${PEM_SUFFIX}"//"`
	
				$PORTSHOWCMD ipsec-policy | $GREP  "${oldFilename}" > /dev/null 2>&1
				if [ $? -ne 1 ]; then
					$ECHO "Extension Switch certificate ${oldFilename} is in use by extension ipsec_policy"
					if [[ -z $restCaller ]]; then
						exit 1
					else
						exit ${EXTN_ERR_CERT_IN_USE}
					fi
				fi	
			fi

			if [[ -z $restCaller ]]; 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
				else
					$ECHO "Invalid input. Certificate file not imported."
					exit 1
				fi
			fi
	
			$RM -f $oldFile 2> /dev/null
			$RM -f "${oldFile}.hash" 2> /dev/null
		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
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_INVALID_CERT_FORMAT}
				fi
			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 0 ]; then
				$RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
				if [[ -z $restCaller ]]; then
					exit 1;
				else
					exit ${EXTN_ERR_INVALID_CERT_FORMAT}
				fi
			fi
		fi

		# validation with pvt key and csr for local switch certs
		if [ $extnLocalSwCert -eq 1 ]; then
			certPvtKeyValidate
			#Certificate signature algorithm should not have md5
			checkWeakAlgo ${EXTN_DIR}/${certpkey}
			retvar=$?
			if [ $retvar != 0 ]; then
				$RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
				exit $retvar
			fi
		fi

		#Get certificate algo details
		checkForFIPsCompl ${EXTN_DIR}/${certpkey}
	
		# 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
				if [[ -z $restCaller ]]; then
					exit 1;
				else
					exit ${EXTN_ERR_IMPORT_NOT_FOUND_CA}
				fi
			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] "
				switch_cert_error=1
			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] "
					switch_cert_error=1
				else
					$ECHO -n "CA Certificate [$CAfile] "
				fi
			fi
			printError
			$RM -f "${EXTN_DIR}/${certpkey}" 2> /dev/null
			if [[ -z $restCaller ]]; then
				exit 1;
			else
				if [ $selfSignedCert -eq 1 ]; then
					exit ${EXTN_ERR_IMPORT_CERT_VERIFICATION_ISSUE}
				elif [ $extnCaCert -eq 1 ]; then
					exit ${EXTN_ERR_IMPORT_CA_VERIFICATION_ISSUE}
				else		
					if [ $switch_cert_error -eq 1 ]; then
						exit ${EXTN_ERR_IMPORT_CERT_VERIFICATION_CERT_ISSUE}
					else
						exit ${EXTN_ERR_IMPORT_CERT_VERIFICATION_CA_ISSUE}
					fi
				fi
			fi
		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
			if [[ -z $restCaller ]]; then
				exit 1;
			else
				exit ${EXTN_ERR_IMPORT_HASH_CAL}
			fi
		fi
	  
		/fabos/cliexec/config save "${EXTN_DIR}/${certpkey}"
		/fabos/cliexec/config save "${EXTN_DIR}/${certpkey}.hash"
		
		$ECHO "Success: $1ed $inputtype $impreq ["$userInput"]."
	 
	else
		cd $CERT_DIR
		if [ -f $userInput ] && [ ! -s $userInput ]; then
			$RM -rf $userInput 2> /dev/null
		fi

		copyfromremote

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

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

			if [ "$AuditLogMode" == "Strict" ]; then
				output=`$OPENSSL_CMD_NO_FIPS verify -cert_strict -CAfile $CERT_DIR/$TEMP_CACERT $CERT_DIR/$TEMP_CACERT 2> /dev/null`
			else
				output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $CERT_DIR/$TEMP_CACERT $CERT_DIR/$TEMP_CACERT 2> /dev/null`
			fi
			check=`$ECHO "$output" | $AWK ' {print $2} '`
			if [ "$check" != "OK" ] ; then
				printError
				$RM $CERT_DIR/$TEMP_CACERT 2> /dev/null
				$ECHO "Import failed"
				exit $check
			fi
		else
			certname="$SWITCH_CERT"
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0

			httpsCaCert=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`

			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

			if [ "$httpsCaCert" == "none" ] || [ ! -s $CERT_DIR/$httpsCaCert ]; then
				$ECHO "Please import CA certificate before importing switch certificate."
				$RM $CERT_DIR/$TEMP_CERT 2> /dev/null
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit 116
				fi
			else
				if [ "$AuditLogMode" == "Strict" ]; then
					output=`$OPENSSL_CMD_NO_FIPS verify -cert_strict -CAfile $CERT_DIR/$httpsCaCert -purpose sslserver $CERT_DIR/$TEMP_CERT 2> /dev/null`
				else
					output=`$OPENSSL_CMD_NO_FIPS verify -CAfile $CERT_DIR/$httpsCaCert -purpose sslserver $CERT_DIR/$TEMP_CERT 2> /dev/null`
				fi
				check=`$ECHO "$output" | $AWK ' {print $2} '`
				if [ "$check" != "OK" ]; then
					printError
					$RM $CERT_DIR/$TEMP_CERT 2> /dev/null
					exit $check
				fi

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

				#OCSP Revocation Check Validation
				if [ "$AuditLogMode" == "Strict" ]; then
					output=`$OPENSSL_CMD_NO_FIPS verify -cert_strict -ocsp_check -CAfile $CERT_DIR/$httpsCaCert $CERT_DIR/$TEMP_CERT 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/$TEMP_CERT 2> /dev/null
						exit $check
					fi
				fi

			fi
		fi

		# Certificate compliance wimh FIPs mode
		#Get certificate algo details
		if [ "$impreq" == "CA" ]; then
			checkForFIPsCompl $CERT_DIR/$TEMP_CACERT
		else
			checkForFIPsCompl $CERT_DIR/$TEMP_CERT
		fi

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

			# validate the certificate by comparing with private key and csr of the switch
			certPvtKeyValidate $CERT_DIR/$TEMP_CERT
			retvar=$?
			if [ $retvar != 0 ]; then
				$RM $CERT_DIR/$TEMP_CERT 2> /dev/null
				exit $retvar
			fi
			#Certificate signature algorithm should not have md5
			checkWeakAlgo $CERT_DIR/$TEMP_CERT
			retvar=$?
			if [ $retvar != 0 ]; then
				$RM $CERT_DIR/$TEMP_CERT 2> /dev/null
				exit $retvar
			fi
		fi

		FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		FABOS_SWITCHNO=0
		
		if [ "$impreq" == "CERT" ]; then
			$CP $CERT_DIR/$TEMP_CERT $CERT_DIR/$certname 2> /dev/null
			$RM $CERT_DIR/$TEMP_CERT 2>/dev/null
		else
			$CP $CERT_DIR/$TEMP_CACERT $CERT_DIR/$certname 2> /dev/null
			$RM -f $CERT_DIR/$TEMP_CACERT 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

		FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
		$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
				if [ $commoncert -eq 1 ]; then
					$ECHO "commoncert $expreq file does not exist."
				else
					$ECHO "$inputtype $expreq file does not exist."
				fi
				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
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0
			certFileName=`/fabos/cliexec/config get $ROOTCERTCONFIG 5`
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			$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
				if [ $commoncert -eq 1 ]; then
					$ECHO "commoncert $expreq file does not exist."
				else
					$ECHO "$inputtype $expreq file does not exist."
				fi
				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
		else
			cd $CERT_DIR
			if [ -z "$certFileName" ]; then
				FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
				FABOS_SWITCHNO=0
				certFileName=`/fabos/cliexec/config get $CERTCONFIG 5`
				FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
				$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."
			if [[ -z $restCaller ]]; then
				exit 1;
			else
				if [ "$expreq" == "CSR" ]; then
					exit ${EXTN_ERR_NOT_EXIST_CSR}
				elif [ "$expreq" == "CERT" ]; then
					exit ${EXTN_ERR_NOT_EXIST_CERT}
				elif [ "$expreq" == "CA" ]; then
					exit ${EXTN_ERR_NOT_EXIST_CA_CERT}
				fi
			fi
		fi
	else	
		if [ ! -s "$certFileName" ]; then
			if [ $commoncert -eq 1 ]; then
				$ECHO "commoncert $expreq file does not exist."
			else
				$ECHO "$inputtype $expreq file does not exist."
			fi
			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
			if [[ ! -z $password1 ]]; then
				/usr/bin/scp -q -oStrictHostKeyChecking=no -oSSHPassword=$password1 \
					$certpkey $userName@\[$ipAddr\]:$remoteDir/$certFileName 2> ${exportFilePath}
			else
				/usr/bin/scp -q -oStrictHostKeyChecking=no \
					$certpkey $userName@\[$ipAddr\]:$remoteDir/$certFileName 2> ${exportFilePath}
			fi
		else
			if [[ ! -z $password1 ]]; 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"
		if [ $commoncert -eq 1 ]; then
			$ECHO "Success: $1ed commoncert $expreq $certFileName"
		else
			$ECHO "Success: $1ed $inputtype $expreq $certFileName"
		fi
	else
		if [ $extn -eq 1 ]; then
			$ECHO "Failed to $1 $inputtype $expreq to remote host: $ipAddr, scp/ftp error."
		elif [ $commoncert -eq 1 ]; then	
				$ECHO "Failed to $1 commoncert $expreq to remote host: $ipAddr"
		else
			$ECHO "Failed to $1 $inputtype $expreq to remote host: $ipAddr"
		fi
	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
		if [ $extn -eq 1 ]; then
			exit ${EXTN_ERR_EXP_COPY_FAIL}
		else
			exit 120 # Handle scp / ftp error for rest
		fi
	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="*"
	FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
	FABOS_SWITCHNO=0

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

	FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
	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
			#Check if platform is starlynx and vlan is enabled
			SWBD=$(sin | swbd 2> /dev/null)
			if [ "$SWBD" == "SWBD175" ]; then
				ipv4enabled=`/fabos/cliexec/config get fred.vlan.ipv4enabled 2`
				if [ $ipv4enabled -eq 1 ]; then
					switchIp=`/fabos/cliexec/config get fred.vlan.ip 5`
				else
					ipv6enabled=`/fabos/cliexec/config get fred.vlan.ipv6enabled 2`
					if [ $ipv6enabled -eq 1 ]; then
						switchIp=`/fabos/cliexec/config get fred.vlan.ipv6 5`
					else
						$ECHO "Configure a Valid IPv4 or IPv6 address"
						$ECHO
						exit 1
					fi
				fi
			else
				$ECHO "Configure a Valid IPv4 or IPv6 address"
				$ECHO
				exit 1
			fi
		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
# "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
AuditLogMode=`/fabos/cliexec/config get $X509_VALIDATION_KEY 5`
# Change the VF back to current context.
FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

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

			"$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" ]]; then
		exportUsage
		exit 1
	fi

	if [[ "$certFileName" != "" && "$inputtype" != "$EXTN" ]]; 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"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_NOT_SUPP}
			fi
		fi

		if [ "$expreq" == "CA" ]; then
			if [ "$keypair" != "" ]; then
				$ECHO "keypair cannot be specified for $expreq export"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NOT_SUPP_KEYPAIR}
				fi
			fi
			if [ "$certFileName" == "" ]; then
				$ECHO "Export $expreq operation requires certname in this server to be specified"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NO_CERT}
				fi
			fi
			certNameValidate $certFileName
			extnCaCert=1
		elif [ "$expreq" == "CERT" ]; then
			if [ "$certFileName" == "" ]; then
				$ECHO "Export $expreq operation requires certname in this server to be specified"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NO_CERT}
				fi
			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"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NO_CERT_NO_KEYPAIR}
				fi
			elif [ "$certFileName" != "" ] && [ "$keypair" != "" ] ; then
				$ECHO "Both CSR name and keypair cannot be specified for Export $expreq operation"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NOT_SUPP_BOTH_KEYPAIR_CSR}
				fi
			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~@%_+:-]"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_INVALID_KEYPAIR_CHAR}
				fi
			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
 
	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
			;;

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

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

			"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 [ "$impreq" != "CA" ] && [ "$inputtype" == "$ASC" ]; 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"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_NOT_SUPP}
			fi
		fi

		if [ "$certFileName" == "" ]; then
			$ECHO "Import operation requires certificate name on the remote server to be specified"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_NO_CERT}
			fi
		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~@%_+:-]"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_INVALID_KEYPAIR_CHAR}
				fi
			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"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NOT_SUPP_KEYPAIR}
				fi
			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"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_IMPORT_NOT_SUPP_CACERT}
			fi
		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
	
	promptHostInfo $CERT_IMPORT $impreq $inputtype $keypair

	if [ $commonCert -eq 1 ]; then
		if [ "$impreq" == "CA" ]; then
			certname="$CA_CERT"
			$CP $FCAP_DIR/$TEMP_CACERT $CERT_DIR/$certname 2> /dev/null
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0
			/fabos/cliexec/config save $CERT_DIR/$certname
			/fabos/cliexec/config save $CERT_DIR
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			fqdn_set
			$RM $FCAP_DIR/$TEMP_CACERT 2> /dev/null
		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_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0
			/fabos/cliexec/config save $CERT_DIR/$certname
			/fabos/cliexec/config save $CERT_DIR
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			fqdn_set
			$RM -rf $FCAP_DIR/$certFileName 2> /dev/null
		fi
	fi

	# set configuration as per options
	if [ "$inputtype" == "$HTTPS" ] || [ $commonCert -eq 1 ]; then
		FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		FABOS_SWITCHNO=0

		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

		FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

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

	if [ $enableHttps -eq 1 ]; then
		FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		FABOS_SWITCHNO=0

		/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

		FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

		$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
			;;
			
		"$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" ]]; 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"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_NOT_SUPP}
			fi
		fi

		if [ "$showreq" == "CA" ]; then
			if [ "$keypair" != "" ]; then
				$ECHO "keypair cannot be specified for $showreq file display"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NOT_SUPP_KEYPAIR}
				fi
			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
					#Display local certificate with filename if exists
					if [[ -z $restCaller ]]; then
						extnLocalSwCert=1
					fi
					extnRemoteSwCert=1
				fi
			fi
		elif [ "$showreq" == "CSR" ]; then
			if [ "$filename" != "" ]; then
				csrNameValidate $filename
			fi		
			extnLocalSwCsr=1				
			if [ "$keypair" != "" ] && [ "$filename" != "" ]; then
				$ECHO "Both certificate name and keypair cannot be specified for $showreq file display"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NOT_SUPP_BOTH_KEYPAIR_CERT}
				fi
			fi
		else
			showUsage
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_INVALID_ENTITY}
			fi
		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~@%_+:-]"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_INVALID_KEYPAIR_CHAR}
				fi
			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"

		FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		FABOS_SWITCHNO=0

		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
			
		FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
	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	
			;;

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

		"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 [ "$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" == "server" ] && [ "$inputtype" == "$FCAPS" ]; then
		$ECHO "Error: Invalid option -$CAFlag passed, not applicable to $inputtype."
		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"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_NOT_SUPP}
			fi
		fi

		if [ "$delreq" == "CERT" ]; then
			if [ "$filename" == "" ] && [ "$keypair" == "" ] ;then
				$ECHO "Extn Cert delete needs cert-name or Keypair_tag"
				deleteUsage
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NO_CERT_NO_KEYPAIR}
				fi
			fi
			if [ "$filename" != "" ]; then
				certNameValidate $filename
			fi
		elif [ "$delreq" == "CA" ]; then
			if [ "$keypair" != "" ] ;then
				if [[ -z $restCaller ]]; then
					$ECHO "keypair cannot be specified for Extn CA delete"
					deleteUsage
					exit 1
				else
					exit ${EXTN_ERR_NOT_SUPP_KEYPAIR}
				fi
			fi
			if [ "$filename" == "" ]; then
				if [[ -z $restCaller ]]; then
					$ECHO "Extn CA delete needs certificate name"
					deleteUsage
					exit 1
				else
					exit ${EXTN_ERR_NO_CERT}
				fi
			fi
			if [ "$filename" != "" ]; then
				certNameValidate $filename
			fi
		elif [ "$delreq" == "CSR" ]; then
			if [ "$filename" == "" ] && [ "$keypair" == "" ] ;then
				$ECHO "Extn CSR delete needs CSR name or Keypair_tag"
				deleteUsage
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NO_CSR_NO_KEYPAIR}
				fi
			elif [ "$filename" != "" ] && [ "$keypair" != "" ] ; then
				$ECHO "Both CSR name and keypair cannot be specified for Extn CSR delete"
				deleteUsage
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NOT_SUPP_BOTH_KEYPAIR_CSR}
				fi
			fi
			if [ "$filename" != "" ]; then
				csrNameValidate $filename
			fi
		elif [ "$delreq" == "ALL" ]; then
			if [ "$filename" != "" ] || [ "$keypair" != "" ] ;then
				$ECHO "Certificate name OR keypair cannot be specified with Extn delete \"ALL\""
				deleteUsage
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_NOT_SUPP_CERT_OR_KEYPAIR}
				fi
			fi
		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~@%_+:-]"
				if [[ -z $restCaller ]]; then
					exit 1
				else
					exit ${EXTN_ERR_INVALID_KEYPAIR_CHAR}
				fi
			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 [[ -z $restCaller ]]; then
			if [ "$response" == "no" ]; then
				$ECHO -e "$extn_delete_prompt"
				secOpConfirm
				if [ $? -ne 0 ]; then
					exit 1
				fi
			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" == "$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
			if [ $commoncert -eq 1 ]; then
				$ECHO "About to delete commoncert $delreq file"
			else
				$ECHO "About to delete $inputtype $delreq file"
			fi
			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
			FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
			FABOS_SWITCHNO=0
			deleteFiles 0 $curdir/$file
			/fabos/cliexec/config save $curdir
			FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
			$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
				FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
				FABOS_SWITCHNO=0
				deleteFiles 0 $CERT_DIR/$switchIp$CSR_SUFFIX
				/fabos/cliexec/config save $CERT_DIR
				FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP

				$AUDIT_NOTIFY "$CERT_DEL_CSR" $switchIp$CSR_SUFFIX
			fi
			# remove stale common cert csr from https certs dir
			deleteFiles 0 $CERT_DIR/*$CSR_SUFFIX
			/fabos/cliexec/config save $CERT_DIR
		fi
		
		# remove stale csr
		FABOS_SWITCHNO_TEMP=$FABOS_SWITCHNO
		FABOS_SWITCHNO=0
		deleteFiles 0 $curdir/*$CSR_SUFFIX
		/fabos/cliexec/config save $curdir
		FABOS_SWITCHNO=$FABOS_SWITCHNO_TEMP
		
		$ECHO
	elif [ "$delreq" == "ALL" ]; then
		# cleanup https from rest with timer
		if [[ ! -z $restCaller ]] && [ "$inputtype" == "$HTTPS" ]; then
			sleep 7
			confirmDelete $HTTPS
			isDeleteOk=$DELETE_SUCCESS
		elif [ "$inputtype" == "$FCAPS" ]; then
			confirmDelete $inputtype
			if [ $commoncert -eq 1 ]; then
				confirmDelete $HTTPS
			fi
		elif [ "$inputtype" == "$RADIUS" ] || [ "$inputtype" == "$LDAP" ] || [ "$inputtype" == "$SYSLOG" ] || \
				[ "$inputtype" == "$HTTPS" ]; 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
			if [[ -z $restCaller ]]; then
				confirmDelete $HTTPS
			fi
			if [ $isExtnPlatform -eq 1 ]; then
				confirmDelete $EXTN
			fi
		else
			deleteUsage
			exit 1
		fi
	else
		deleteUsage
		exit 1
	fi
	if [[ ! -z $restCaller ]]; then
		# In case of extension, exit on error is done.
		if [ "$inputtype" == "$EXTN" ]; then
			exit 0
		else 
			exit $isDeleteOk
		fi
	fi
;;
 
$CERT_GEN )
	# verify input arguments before processing
	fcap=0
	response="no"
	genreq=""
	typeFlag=0
	protFlag=0	
	file=
	key_size="none"
	keytype="none"
	hashtype="none"
	years=0
	flag=0
	count=0
	commoncert=0
	caCert=0
	https=0
	genswcert=0
	allopt=0
	showusage=0
	certtype=""
	sign=0
	keypair=""
	extn=0
	ec_curve=""

	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]}
				sign=1
				protFlag=1
			else
				generateUsage
				exit 1			
			fi
			;;

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

		"$COMMONCERT" )
			if [ $protFlag -eq 0 ]; then
				commoncert=1
				certtype=$FCAPS
				protFlag=1
			else
				generateUsage
				exit 1	
			fi
			;;

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

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

		"$SYSLOG" )
			if [ $protFlag -eq 0 ]; then
				certtype=${cmdargs[count]}
				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

	setDefaultAttributeValues

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

		if [ "$hashtype" != "sha1" ] && [ "$hashtype" != "sha256" ]  && [ "$hashtype" != "sha384" ] && [ "$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
			if [ "$certtype" != "$HTTPS" ] || [ "$keytype" != "ecdsa" ]; then
				$ECHO "Error: Unsupported/invalid $keytype key size for $certtype - $key_size."
				exit 1
			fi
		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

		if [ "$keytype" == "ecdsa" ]; then
			getecCurve $key_size
			if [ $? -ne 0 ]; then
				$ECHO "Error: Unsupported/invalid $keytype key size for $certtype - $key_size."
				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 == "1024" ]; 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"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_NOT_SUPP}
			fi
		fi

		if [ "$keytype" != "$ECDSA_KEY" ]; then
			$ECHO "Error: Only ECDSA supported for Extension certificates"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_INVALID_ALGO}
			fi
		fi

		if [ "$key_size" != "P384" ]; then
			$ECHO "Error: Unsupported/invalid key size for $certtype: $key_size"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_INVALID_KEYSIZE}
			fi
		fi

		if [ "$hashtype" != "sha384" ]; then
			$ECHO "Error: Unsupported/invalid hashtype for $certtype: $hashtype"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_INVALID_HASH}
			fi
		fi

		if [ "$keypair" == "" ]; then
			$ECHO "Error: Extension certificates require a keypair name to be specified"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_NO_KEYPAIR}
			fi
		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~@%_+:-]"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_INVALID_KEYPAIR_CHAR}
			fi
		fi

		keypair_len=`expr length $keypair`
		if [ $keypair_len -gt 31 ]; then
			$ECHO "Error: keypair_tag should not exceed 31 characters"
			if [[ -z $restCaller ]]; then
				exit 1
			else
				exit ${EXTN_ERR_INVALID_KEYPAIR_LEN}
			fi
		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 $key_size $hashtype $keytype $keypair
		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:"
			$ECHO "	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


