#!/bin/bash 
# #################################################################################
# Exceed TurboX Connection Node
# Copyright (c) Open Text. All Rights Reserved. Trademarks owned by Open Text.
# #################################################################################
# install
# #################################################################################

# Node SSL helper script

read_yesno()
{
# accepts y, n, yes, no; converts input to lowercase
# by default null input is "no", $1 overrides yndefault (n, y, none, block)
# yes: returns 0 (useful for: if read_yesno ; then )
# no: returns 1; Enter: returns default: 0, 1, or 2

	# set default answer if null response
	yndefault=$1
	if [ -z "${yndefault}" ] ; then
		yndefault=n
	fi
	
	while true ; do
		
		read answer
		#convert to lowercase
		answer=`${ECHO} ${answer}| ${TR} [:upper:] [:lower:]`
		${ECHO}
		
		case "${answer}" in
			y|yes )
				return 0
				;;
			n|no )
				return 1
				;;
			"" )
				case "${yndefault}" in
					y ) return 0 ;;
					n ) return 1 ;;
					none ) return 2 ;;
					block )
						${ECHO} "Invalid input. Please try again: \c"
						;;
				esac
				;;
			* )
				${ECHO} "Invalid input '${answer}'. Please try again: \c"
				;;
		esac
	
	done
}

read_noyes()
{
# no: returns 0 (useful for: if read_noyes ; then )

	read_yesno $*
	resp=$?
	if [ $resp -eq 0 ] ; then
		return 1
	elif [ $resp -eq 1 ] ; then
		return 0
	else
		return $resp
	fi
}

set_message_strings()
{
	VERSION=
	SRV_NAME="Exceed TurboX Connection Node"
	PROD_NAME="${SRV_NAME}${VERSION}"
	Q_CONTINUE="Continue [y]es or [n]o (<Enter> for no): \c"
	ABORTING="Installation aborted"
	YES_OR_NO_DEFAULT_NO="[y]es or [n]o (<Enter> for no):  \c"
	YES_OR_NO_DEFAULT_YES="[y]es or [n]o (<Enter> for yes):  \c"
	SERVER_USEOWN_SSLCERTS="An SSL certificate in runtime/keys is required for secure communication.\nYou must either specify your own certificate or have one generated for you.\n"
	SERVER_USEOWN_SSLCERTS_QUEST="Would you like to use an existing certificate?"
	ASK_OWN_CERT_PUBLIC="Please provide the path to the public certificate file (.pem):"
	ASK_OWN_CERT_PRIVATE="Please provide the path to the private key file (.pem):"
	SERVER_WANT_TO_USE_AUTOMATIC="Would you like to use the above certificate?"
	
}

usage()
{
	${ECHO} "Usage: $0 [-s reponsefile ]"
}

strlen()
{
	# `expr length "$*"` is not supported in older systems
	strlenresult=`expr "$*" : '.*'`
	return ${strlenresult}
}

printsectmessage()
{
	if [ "${bSilent}" = "1" ] ; then
		return
	fi
	# calculate proper # of = for this header
	strlen $*
	slen=$?
	lpos=0
	suffix=
	while test ${lpos} -lt  ${slen}
	do
		suffix="${suffix}="
		lpos=`expr ${lpos} + 1`
	done
	${ECHO}
	${ECHO} $*
	${ECHO} ${suffix}
	${ECHO}
}

cd_and_exit()
{
	resetCDir
	exit $1
}

test_GREP()
{
	${ECHO} ${GREP} -e GREP "$0" > /dev/null 2>&1
	${GREP} -e GREP "$0" > /dev/null 2>&1
	if [ $? -gt 0 ] ; then
		return 1
	else
		return 0
	fi
}

find_good_grep()
{
	GREP=`which grep`
	test_GREP
	if [ $? -gt 0 ] ; then
		GREP=`which egrep`
		test_GREP
		if [ $? -gt 0 ] ; then
			GREP=/usr/xpg4/bin/grep
			test_GREP
			if [ $? -gt 0 ] ; then
				${ECHO} "FATAL ERROR: The grep version on this machine is too old.  It needs to be equivalent to GNU grep."
				cd_and_exit 1
			fi
		fi
	fi
	export GREP
	return
}

test_AWK()
{
	awk_result=`${ECHO} "Access: (0755/d)" | ${AWK} 'BEGIN{FS="[(/]"} {print $2}' 2>/dev/null`
	if [ "${awk_result}" = "0755" ] ; then
		return 0
	else
		return 1
	fi
}

find_good_AWK()
{
	AWK=`which awk`
	test_AWK
	if [ $? -gt 0 ] ; then
		AWK=/usr/xpg4/bin/awk
		test_AWK
		if [ $? -gt 0 ] ; then
			${ECHO} "FATAL ERROR: The awk version on this machine is too old.  It needs to be equivalent to GNU awk."
			cd_and_exit 1
		fi
	fi
	export AWK
	return
}



test_STAT()
{
	${STAT} / > /dev/null 2>&1
	if [ $? -gt 0 ] ; then
		return 1
	else
		return 0
	fi
}

find_good_STAT()
{
	STAT=`which stat`
	test_STAT
	if [ $? -gt 0 ] ; then
		${ECHO} "Warning: stat command unavailable on this platform.\n"
		${ECHO} "Please manually check permissions on patch directory if stat does not exist."
		STAT=
	fi
	export STAT
}

test_TR()
{
	echo "aaAA" | ${TR} [:upper:] [:lower:]  > /dev/null 2>&1
	if [ $? -gt 0 ] ; then
		return 1
	else
		return 0
	fi
}

find_good_TR()
{
	TR=`which tr`
	test_TR
	if [ $? -gt 0 ] ; then
		TR=/usr/bin/tr
		test_TR
		if [ $? -gt 0 ] ; then
			TR=/usr/xpg4/bin/tr
			test_TR
			if [ $? -gt 0 ] ; then
				TR=/usr/ucb/tr
				test_TR
				if [ $? -gt 0 ] ; then
					${ECHO} "FATAL ERROR: The tr version on this machine is too old.  It needs to be equivalent to GNU tr."
					cd_and_exit 1
				fi
			fi
		fi
	fi
	export TR
	return
}

test_ECHO()
{
	${ECHO} -e "test\c" | grep "\-e" > /dev/null
	if [ $? -gt 0 ] ; then
		# -e is supported so add it
		ECHO="${ECHO} -e"
	fi
}

find_good_ECHO()
{
	ECHO=`which echo`
	test_ECHO
	export ECHO
}


logIncident()
{
	if [ "${1}" = "1" ] ; then
		incidentCategory="INFORMATION"
	elif [ "${1}" = "2" ] ; then
		incidentCategory="WARNING"
	elif [ "${1}" = "3" ] ; then
		incidentCategory="FATAL ERROR"
	else
		incidentCategory="UNKNOWN"
	fi
	
	thisLogFile="${2}"
	smallTab="  "
	
	${ECHO} "${incidentCategory}: `basename ${0}`" >> "${thisLogFile}"
	
	if [ ! "${3}x" = "x" ] ; then
		${ECHO} "${3}" >> "${thisLogFile}"
	fi
	
	if [ ! "${4}x" = "x" ] ; then
		${ECHO} "${smallTab}${4}" >> "${thisLogFile}"
	fi
	
	if [ ! "${5}x" = "x" ] ; then
		${ECHO} "${smallTab}${5}" >> "${thisLogFile}"
	fi
	
	if [ ! "${6}x" = "x" ] ; then
		${ECHO} "${smallTab}${6}" >> "${thisLogFile}"
	fi
	
	if [ ! "${7}x" = "x" ] ; then
		${ECHO} "${smallTab}${7}" >> "${thisLogFile}"
	fi
	
	if [ ! "${8}x" = "x" ] ; then
		${ECHO} "${smallTab}${8}" >> "${thisLogFile}"
	fi
	
	if [ ! "${9}x" = "x" ] ; then
		${ECHO} "${smallTab}${9}" >> "${thisLogFile}"
	fi
	
	${ECHO} >> "${thisLogFile}"
}

resolveDir()
{
	# resolve links - $0 may be a softlink
	thisPRG="${1}"
	
	while [ -h "$thisPRG" ]; do
		ls_ld=`ls -ld "$thisPRG"`
		this_link=`expr "${ls_ld}" : '.*-> \(.*\)$'`
		
		if expr "${this_link}" : '/.*' > /dev/null; then
			thisPRG="${this_link}"
		else
			thisPRG=`dirname "${thisPRG}"`/"${this_link}"
		fi
	done

	# -- we only want to check fully resolved path
	if [ "${3}" = "CD" ] ; then
		eval ${2}="${thisPRG}"
		return
	fi
	
	CDir=`pwd`
	
	thisPrgDirName="`dirname ${thisPRG}`"
	
	cd "${thisPrgDirName}" > /dev/null 2>&1
	cd .. > /dev/null 2>&1 
	
	Here=`pwd`
	eval ${2}="${Here}"

	cd ${CDir}

}

getInstallDir()
{
	resolveDir $0 InstallDir
}

resetCDir()
{
	cd "${CDir}" > /dev/null 2>&1
}

finalize()
{
	resetCDir
	${ECHO} "${PROD_NAME} Installation Complete" >> $logfile
}

initialize()
{
	init_variables $*
	export_globals
	init_log_file
	printsectmessage "SSL Certificates"
	areYouRoot
}


gen_config()
{
	${ECHO} "Generating ${etxsslconfig}"
	cat > ${etxsslconfig} <<EOT
HOME                    = $1
RANDFILE                = $1/.rnd
[ ca ]
default_ca      = CA_default
[ CA_default ]
certs           = .
crl_dir         = .
database        = index.txt
new_certs_dir   = $1
certificate     = $3
serial          = serial
private_key     = $2
RANDFILE        = $1/.rand
x509_extensions = usr_cert
name_opt        = ca_default
cert_opt        = ca_default
# 10 years (+ assume 2 leap days)
default_days    = 3652
default_crl_days= 30
default_md      = sha2
preserve        = no
policy          = policy_match
[ policy_match ]
countryName             = match
stateOrProvinceName     = match
organizationName        = match
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional
[ policy_anything ]
countryName             = optional
stateOrProvinceName     = optional
localityName            = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional
[ req ]
default_bits            = 2048
default_md              = sha2
default_keyfile         = privkey.pem
distinguished_name      = req_distinguished_name
attributes              = req_attributes
req_extensions		= req_exts
x509_extensions = v3_ca
string_mask = MASK:0x2002
[ req_distinguished_name ]
countryName                     = Country Name (2 letter code)
countryName_default             = US
countryName_min                 = 2
countryName_max                 = 2
stateOrProvinceName             = State or Province Name (full name)
localityName                    = Locality Name (eg, city)
0.organizationName              = Organization Name (eg, company)
organizationalUnitName          = Organizational Unit Name (eg, section)
commonName                      = Common Name (eg, Connection Node hostname)
commonName_max                  = 64
emailAddress                    = Email Address
emailAddress_max                = 64
[ req_attributes ]
challengePassword               = A challenge password
challengePassword_min           = 4
challengePassword_max           = 20
unstructuredName                = An optional company name
[ req_exts ]
extendedKeyUsage		= codeSigning
keyUsage			= digitalSignature
[ usr_cert ]
basicConstraints=CA:FALSE
nsComment                       = "OpenSSL Generated Certificate"
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints = CA:true
[xpclient_ext]
extendedKeyUsage = 1.3.6.1.5.5.7.3.2
[xpserver_ext]
extendedKeyUsage = 1.3.6.1.5.5.7.3.1
[ SAN_ENV ]
subjectAltName=${SAN_ENV}
EOT
}

isItSUSELinux()
{
	if [ -d "/etc/init.d" ] ; then
		isSUSE=1
	fi
}

getThisPlatform()
{
	osAix=aix
	osLinux=linux
	osSolaris=solaris
	osHPUX=hpux
	
	archPpc=ppc
	archi586=i586
	archx86_64=x86_64
	archSparc=sparc
	archParisc=parisc
	
	unknown=unknown
	
	thisOS=${unknown}
	thisArch=${unknown}
	
	thisUname=`uname`
	
	fgrepOptions="-c -i"
	optionL="-L"
	
	hasi86=`uname -a | grep ${fgrepOptions} i386`
	
	if [ ${hasi86} = "0" ] ; then
		hasi86=`uname -a | grep ${fgrepOptions} i686`
	fi
	
	isx86_64=`uname -a | grep ${fgrepOptions} x86_64`
	
	if [ ${hasi86} = "0" ] ; then
		if [ ! ${isx86_64} = "0" ] ; then
			thisArch=${archx86_64}
		fi
	else
		thisArch=${archi586}
	fi
	
	case ${thisUname} in
		AIX )
			thisOS=${osAix}
			thisArch=${archPpc}
			;;
		Linux )
			thisOS=${osLinux}
			isItSUSELinux
			;;
		SunOS )
			thisOS=${osSolaris}
			if [ ${hasi86}=0 ] ; then
				thisArch=${archSparc}
				optionL="-h"
			fi
			solarisVersion=`uname -r|cut -d "." -f2`
			export solarisVersion
			;;
		HP-UX )
			thisOS=${osHPUX}
			thisArch=${archParisc}
			;;
		* )
			;;
	esac
}

acceptfullyqualified()
{
	case $1 in
		*.*)
			hostname=$1
			return 0
			;;
	esac
	return 1
}




gethostnamefqdn()
{
        orighostname=`hostname 2>/dev/null`
        if [ $? -eq 0 ] ; then
                if acceptfullyqualified $orighostname ; then
                        return 0
                fi
        else
                orighostname=
        fi
	
	# -- ok hostname is NOT FQDN
	if [ "${thisOS}" = "${osLinux}" ] ; then
                hostname=`hostname --fqdn 2>/dev/null`
                if [ $? -gt 0 ] ; then
                        if [ -z ${orighostname} ] ; then
                                hostname=`uname -n 2>/dev/null`
                                if [ $? -gt 0 ] ; then
                                        hostname=`hostnamectl 2>/dev/null| grep "Static hostname:" | cut -d: -f 2 | tr -d \ `
                                        if [ -z ${hostname} ] ; then
                                                hostname=localhost
                                        fi
                                fi
                        else
                                hostname=${orighostname}
                        fi
                fi
                return 0
	elif [ -f /usr/sbin/check-hostname ] ; then
		# ETX 11.5.5 - check-hostname must return OK:
		/usr/sbin/check-hostname | grep OK\: > /dev/null 2>&1
		if [ $? -eq 0 ] ; then
			hostname=`/usr/sbin/check-hostname | awk '{ print $NF }'`
			echo $hostname | grep `hostname` > /dev/null 2>&1
			if [ $? -eq 0 ] ; then
				# this means hostname we found is reasonable
				return 0
			fi
		fi
	fi

	# some older unix flavours do not support --fqdn so this may
	# inadvertantly change the hostname itself
	hostname --fqdn > /dev/null 2>&1
	newhostname=`hostname 2>/dev/null`
	if [ "${newhostname}" = "--fqdn" ] ; then
		# switch hostname back!
		hostname "${orighostname}"
		hostname="${orighostname}"
	else
		hostname=${newhostname}
	fi
}

keys_match()
{
	key1=$1
	key2=$2

	fromcert=${etxssldir}/fromcert.pub
	frompriv=${etxssldir}/frompriv.pub

	openssl x509 -in ${key1} -pubkey -noout > ${fromcert} 2>/dev/null
	certok=$?
	if [ ${certok} -eq 0 ] ; then
		openssl ec  -in ${key2} -pubout > ${frompriv}  2>/dev/null
		ectypeok=$?
		if [ ! ${ectypeok} -eq 0 ] ; then
			openssl rsa  -in ${key2} -pubout > ${frompriv}  2>/dev/null
			ectypeok=$?
			if [ ! ${ectypeok} -eq 0 ] ; then
				${ECHO} "Invalid private key file specified:\n${key2}"
				return 1
			fi
		fi
	else
		${ECHO} "Invalid public certificate file specified:\n${key1}"
		return 1
	fi

	diff ${fromcert} ${frompriv}  > /dev/null 2>/dev/null 
	result=$?
	rm -f ${fromcert} 2>/dev/null
	rm -f ${fromkey}  2>/dev/null
	return $result
}

cert_from_host()
{
	key1=$1
        certhost=`openssl x509 -in ${key1} -noout -subject 2> /dev/null|cut -f3- -d=|cut -f1 -d/`
	if [ "${certhost}" = "${hostname}" ] ; then
		return 0
	elif [ -z "${certhost}" ] ; then
		${ECHO} "Warning: The Common Name from provided public certificate cannot be found."
		${ECHO} "Are you sure you want to continue using these files?"
		${ECHO} "${YES_OR_NO_DEFAULT_NO}"
		if read_yesno ; then
			return 0 
		fi
	else
		${ECHO} "Warning: The Common Name from provided public certificate does not\nmatch the current hostname FQDN exactly."
		${ECHO} "If you continue there is a possibility that sessions will not launch."
		${ECHO} "Value found: ${certhost} "
		${ECHO}
		${ECHO} "Are you sure you want to continue using these files?"
		${ECHO} "${YES_OR_NO_DEFAULT_NO}"
		if read_yesno ; then
			return 0
		fi
	fi
	return 1
}



handle_ssl()
{
	# we need FQDN hostname all the time
	gethostnamefqdn

	if [ -f ${etxcertpem} ] ; then
		OverwriteSettings=0
		if [ "${bFromInstall}" -eq 0 ] ; then
			if [ ! "${bSilent}" = "1" ] ; then
				${ECHO} "${etxcertpem} exists.\n\nDo you want to overwrite certificates for this Connection Node?"
				${ECHO} "${YES_OR_NO_DEFAULT_NO}"
				if read_yesno ; then
					OverwriteSettings=1
				fi
			
			fi
			if [ ${OverwriteSettings} -gt 0 ] ; then
				${ECHO} "New SSL certificates will be generated."
				${ECHO}
			else
				cd_and_exit 0
			fi
		else
			${ECHO}
			${ECHO} "${etxcertpem} exists.  Skipping SSL certificate creation."
			${ECHO}
			return
		fi
	fi
	
	### From this point don't exit without changing SSL details back to normal
	
	ORIG_OPENSSL_CONF=${OPENSSL_CONF}
	OPENSSL_CONF=${etxsslconfig}
	export OPENSSL_CONF
	
	ORIG_LD_LIBRARY_PATH=${LD_LIBRARY_PATH}
	LD_LIBRARY_PATH=${InstallDir}/bin/sys:${LD_LIBRARY_PATH}
	export LD_LIBRARY_PATH
	
	ORIG_RANDFILE=${RANDFILE}
	RANDFILE=${etxssldir}/.rnd
	export RANDFILE

	delete_new_certs
	
	SSLAutogenerate=1
	# note etxssl_config.cnf may not exist first time around so create it in this case

	cert_CommonName=${hostname}
	cert_OrganizationUnit=
	cert_Organization="Automatically created by Exceed TurboX Install"
	cert_Location=
	cert_State=
	cert_Country=
	if [ "localhost" = "${hostname}" ] ; then
		# don't let SAN be localhost blank is better
		SAN_ENV=
	else
		SAN_ENV="DNS:${hostname}"
	fi
	
	if [ "${bFromInstall}" -eq 0 ] ; then
		if [ ! "${bSilent}" = "1" ] ; then
			${ECHO} "${SERVER_USEOWN_SSLCERTS}"
			while [ 1 ]
			do
				UseOwnCertificates=0
				${ECHO} "${SERVER_USEOWN_SSLCERTS_QUEST}"
				${ECHO} "${YES_OR_NO_DEFAULT_NO}"

				if read_yesno ; then
					# Now get the path and validate it
					${ECHO} "${ASK_OWN_CERT_PUBLIC}"
					read existingPublicPemFile
					if [ -f "${existingPublicPemFile}" ] ; then
						${ECHO} "Copying ${existingPublicPemFile}"
						cp -f "${existingPublicPemFile}" ${etxcertpem}.new
						chmod 644 ${etxcertpem}.new
						
						${ECHO}
						${ECHO} "${ASK_OWN_CERT_PRIVATE}"
						read existingPrivatePemFile
						
						if [ -f "${existingPrivatePemFile}" ] ; then
							${ECHO} "Copying ${existingPrivatePemFile}"
							cp -f "${existingPrivatePemFile}" ${etxprivpem}.new
							chmod 640 ${etxprivpem}.new
							${ECHO}
							${ECHO} "Verifying public certificate and private key files."
							keys_match "${etxcertpem}.new" "${etxprivpem}.new"
							keyresult=$?
							if [ ${keyresult} -eq 0 ] ; then
								# In 11.5.2+ we don't care since the trust between server and node ensures if fingerprints match TLS is secure
								#${ECHO} "Verifying public certificate specifies this hostname."
								#cert_from_host "${etxcertpem}" "${etxprivpem}"
								#certresult=$?
								#if [ ${certresult} -eq 0 ] ; then
									# we have success so exit loop
									UseOwnCertificates=1
									SSLAutogenerate=0
								#fi
							fi
							rm -f ${etxcertpem}.new
							rm -f ${etxprivpem}.new
							${ECHO}
						else
							${ECHO} "Error cannot access ${existingPrivatePemFile}"
							${ECHO}
						fi
					else
						${ECHO} "Error cannot access ${existingPublicPemFile}"
						${ECHO}
					fi
				else
					break
				fi
				if [ ${UseOwnCertificates} -gt 0 ] ; then
					break
				fi
			done
		else
			# silent install -- you can answer use automatic and some details ???
			AUTOGENERATEFLAGS="/CN=${hostname}"
			if [ ! -z "${cert_OrganizationUnit}" ] ; then
				AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/OU=${cert_OrganizationUnit}"
			fi
			if [ ! -z "${cert_Organization}" ] ; then
				AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/O=${cert_Organization}"
			fi
			if [ ! -z "${cert_Location}" ] ; then
				AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/L=${cert_Location}"
			fi
			if [ ! -z "${cert_State}" ] ; then
				AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/ST=${cert_State}"
			fi
			if [ ! -z "${cert_Country}" ] ; then
				AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/C=${cert_Country}"
			fi
		fi

		if [ ${UseOwnCertificates} -eq 0 ] ; then
			#  Ask questions to provide details
			displayList=1
			while [ 1 ]
			do
				${ECHO} "The following certificate will be created:"
				${ECHO} "Common Name: ${cert_CommonName}"
				${ECHO} "Organizational Unit: ${cert_OrganizationUnit}"
				${ECHO} "Organization: ${cert_Organization} "
				${ECHO} "Location: ${cert_Location}"
				${ECHO} "State/Province: ${cert_State}"
				${ECHO} "Country: ${cert_Country}"
				${ECHO} "Subject Alt Name: ${SAN_ENV}"
				${ECHO}
				${ECHO} "${SERVER_WANT_TO_USE_AUTOMATIC}"
				${ECHO} "${YES_OR_NO_DEFAULT_YES}"

				if read_yesno y ; then
					AUTOGENERATEFLAGS="/CN=${hostname}"
					if [ ! -z "${cert_OrganizationUnit}" ] ; then
						AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/OU=${cert_OrganizationUnit}"
					fi
					AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/O=${cert_Organization}"
					if [ ! -z "${cert_Location}" ] ; then
						AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/L=${cert_Location}"
					fi
					if [ ! -z "${cert_State}" ] ; then
						AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/ST=${cert_State}"
					fi
					if [ ! -z "${cert_Country}" ] ; then
						AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/C=${cert_Country}"
					fi
					break
				fi

				${ECHO} "Please provide Organization Unit (example -- Engineering Group)"
				read cert_OrganizationUnit

				while [ 1 ]
				do
					${ECHO} "Please provide Organization (example -- YourCompanyName)"
					read cert_Organization
					if [ -z "${cert_Organization}" ] ; then
						${ECHO} "The Organization value cannot be empty"
						${ECHO}
					else
						break
					fi
				done

				${ECHO} "Please provide Location (example -- Los Angeles)"
				read cert_Location

				${ECHO} "Please provide State/Province (example -- CA)"
				read cert_State

				${ECHO} "Please provide Country Code (Example -- US) "
				read cert_Country

				${ECHO} "Please provide SAN (example DNS:abc.sample.com,IP:10.1.1.5)[Optional]"
				read SAN_ENV
				
				${ECHO}
			done
		fi
	else
		# silent install -- you can answer use automatic and some details ???
		AUTOGENERATEFLAGS="/CN=${hostname}"
		if [ ! -z "${cert_OrganizationUnit}" ] ; then
			AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/OU=${cert_OrganizationUnit}"
		fi
		if [ ! -z "${cert_Organization}" ] ; then
			AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/O=${cert_Organization}"
		fi
		if [ ! -z "${cert_Location}" ] ; then
			AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/L=${cert_Location}"
		fi
		if [ ! -z "${cert_State}" ] ; then
			AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/ST=${cert_State}"
		fi
		if [ ! -z "${cert_Country}" ] ; then
			AUTOGENERATEFLAGS="${AUTOGENERATEFLAGS}/C=${cert_Country}"
		fi
		
	fi

	if [ ${SSLAutogenerate} -gt 0 ] ; then
		export SAN_ENV
		touch ${logDir}/sslcertcreate.log
		gen_config ${etxssldir} ${etxprivpem}.new ${etxcertpem}.new
		openssl ecparam -name prime256v1 -out ${etxeccparam}.new 2>>${logDir}/sslcertcreate.log
		opensslresult=$?		
		if [ 0$opensslresult -lt 1 ] ; then
			# Generate hostname only certificate so that we can guarantee SSL usage
			if [ x"${SAN_ENV}" = x ] ; then
				openssl req -config ${etxsslconfig} -x509 -nodes -days 3652 -sha256 -newkey ec:${etxeccparam}.new -keyout ${etxprivpem}.new -out ${etxcertpem}.new -subj "${AUTOGENERATEFLAGS}"  2>>${logDir}/sslcertcreate.log
			else
				openssl req -config ${etxsslconfig} -x509 -nodes -days 3652 -sha256 -newkey ec:${etxeccparam}.new -extensions SAN_ENV  -keyout ${etxprivpem}.new -out ${etxcertpem}.new -subj "${AUTOGENERATEFLAGS}" 2>>${logDir}/sslcertcreate.log
			fi
			opensslresult=$?
		fi
		if [ 0$opensslresult -gt 0 ] ; then
			# system openssl does not support prime256v1 or cannot create certificate - do it ourselves
			${ECHO} "Warning: SSL certificate missing prime256v1 support, using fallback.\n"
			${InstallDir}/bin/nodemaintctl fromnodecmds	gencert
			${ECHO}
			opensslresult=$?
		fi
		# display message if not silent
		if [ ! "${bSilent}" = "1" ] ; then
			if [ ! -f ${etxcertpem}.new -o ! -f ${etxprivpem}.new ] ; then
				${ECHO} "Warning: SSL certificate was not properly generated."
			else
				${ECHO} "SSL certificate successfully generated.\n"
			fi
		fi
		
		if [ -f ${etxprivpem}.new ] ; then
			chmod 640 ${etxprivpem}.new
		fi
	fi
	
	rm -f ${etxeccparam}.new  2 > /dev/null

	OPENSSL_CONF=${ORIG_OPENSSL_CONF}
	export OPENSSL_CONF
	LD_LIBRARY_PATH=${ORIG_LD_LIBRARY_PATH}
	export LD_LIBRARY_PATH
	RANDFILE=${ORIG_RANDFILE}
	export RANDFILE
	
	### Ok we are good to exit any time from this point since env is back to normal
	copy_new_certs
}

copy_new_certs()
{
    if [ -f ${etxprivpem}.new ]; then
	mv -f ${etxprivpem}.new ${etxprivpem}
    else
	rm -f ${etxprivpem} > /dev/null 2>&1
    fi

    if [ -f ${etxcertpem}.new ]; then
	mv -f ${etxcertpem}.new ${etxcertpem}
    else
	rm -f ${etxcertpem} > /dev/null 2>&1
    fi

    if [ -f ${etxeccparam}.new ]; then
	mv -f ${etxeccparam}.new ${etxeccparam}
    else
	rm -f ${etxeccparam} > /dev/null 2>&1
    fi
}

delete_new_certs()
{
    rm -f ${RANDFILE} ${etxprivpem}.new ${etxcertpem}.new ${etxeccparam}.new > /dev/null 2>&1
}

init_variables()
{
	InstallCompleteFlag="InstallComplete=1"
	ETXCNProps=${InstallDir}/conf/etxcn.properties

	logDir=${InstallDir}/installlogs
	logfile=${logDir}/install.log

	binDir=${InstallDir}/bin
	binetxpmcontrol=${binDir}/etxpmctl
	binsysetxpmcontrol=${binDir}/sys/etxpmctl
	binnodemaintcontrol=${binDir}/nodemaintctl
	binsysnodemaintcontrol=${binDir}/sys/nodemaintctl
	binnodecmds=${binDir}/nodecmds

	conf_dir=${InstallDir}/conf
	etxssldir=${InstallDir}/runtime/keys
	etxcertpem=${etxssldir}/etxcert.pem
	etxprivpem=${etxssldir}/etxpriv.pem
	etxsslconfig=${etxssldir}/etxssl_config.cnf
	etxeccparam=${etxssldir}/ecparam

	thisUname=`uname`
	isSparc=`uname -a | ${GREP} -c sparc`
}

export_globals()
{
	export bSilent
	export bBootStart
}

set_platform_opts()
{

	find_good_ECHO
	find_good_grep
	find_good_AWK
	find_good_STAT
	find_good_TR

	if [ "${thisOS}" = "${osLinux}" ] ; then
		USERADDOPTS="-M"
		USERADDOPTS_WITHSHELL="-m"
	elif [ "${thisOS}" = "${osAix}" ] ; then
		USERADDOPTS=
		USERADDOPTS_WITHSHELL="-m"
	elif [ "${thisOS}" = "${osSolaris}" ] ; then
		USERADDOPTS=
		USERADDOPTS_WITHSHELL="-m"
	else
		USERADDOPTS=
	fi
	
	export USERADDOPTS
	export USERADDOPTS_WITHSHELL
}


init_log_file()
{ 
	if [ ! -d ${logDir} ] ; then
		mkdir ${logDir}
	fi
	
	logfile=${logDir}/install.log
	
	touch $logfile
	
	if [ ! "${bSilent}" = "1" ] ; then
		if [ ! -w "$logfile" ] ; then
			${ECHO} "${LOG_CANT_CREATE_LOG} $logfile. $Q_CONTINUE"
			
			if read_yesno ; then
				logfile=/dev/null
			else
				${ECHO} $ABORTING
				cd_and_exit 1
			fi
		fi
	fi
	
	${ECHO} "SSL Handling begins" >> $logfile
	logIncident "1" "${logfile}" "${LOG_DATE}"
}

areYouRoot()
{
	wai=whoami
	noWhoAmI=`which ${wai} | ${GREP} -c "no ${wai}"`
	
	if [ "${noWhoAmI}" = "1" -a  -x /usr/ucb/${wai} ] ; then
		wai=/usr/ucb/${wai}
		noWhoAmI=0
	fi
	
	if [ "${noWhoAmI}" = "0" -a ! "`${wai}`" = "root" ] ; then
		${ECHO}
		${ECHO} "Please login as 'root' to properly configure ssl for ${PROD_NAME}."
		
		cd_and_exit 1
	fi

}


readThisSectionKeyValueForThisVariable()
{
	thisPropFile=$1
	thisSection=$2
	thisKey=$3
	thisKeyFullName=${thisSection}.${thisKey}
	
	tmp_value=`${GREP} "${thisKeyFullName}=" "${thisPropFile}" 2> /dev/null | cut -f2- -d=`
	ret_value=`echo ${tmp_value}|${TR} -d '\011\012\015'`
	eval ${thisKey}="${ret_value}"
}

readThisSectionKeys()
{
	thisPropFile="$1"
	thisSection="$2"
	theseKeys="$3"
	
	for thisKey in ${theseKeys}
	do
		readThisSectionKeyValueForThisVariable "${thisPropFile}" "${thisSection}" ${thisKey}
	done
}



readResponseFile()
{
	thisResponseFile="$1"
	PWD=`pwd`
	checkthisResponseFile=`echo ${thisResponseFile}|awk '{print substr($0,1,1)}'`
	
	if [ ! -f "${thisResponseFile}" ] ; then
		${ECHO} "FATAL ERROR: Silent mode response file '${thisResponseFile}' does not exist!"
		cd_and_exit 1
	fi
	
	if [ "${PWD}" != "${InstallDir}/bin"  -a "${checkthisResponseFile}" != "/" ] ; then
		${ECHO} "FATAL ERROR: Full path to response file is required to run silent install!"
		cd_and_exit 1
	fi
	
	theseKeys="SSLHostName SSLOrgUnit SSLxxxx"
	readThisSectionKeys "${thisResponseFile}" "install.etxcn" "${theseKeys}"
}


get_params()
{
	builtinResponseFile="${InstallDir}/conf/builtin.resp"
	
	bFromInstall="0"
	while [ ! -z "${1}" ] 
	do
		
		case "${1}" in
		--help )
			${ECHO} "Usage: $0 [-s reponsefile ]"
			${ECHO} "Option: -s fullpath/responsefile : Silent install of ETX Node."
			cd_and_exit 1
			;;
			
		-install )
			bFromInstall="1"
			;;
			
		-s )
			if [ -z "$2" ] ; then
				usage
				cd_and_exit 1
			fi
			shift
			bSilent="1"
			readResponseFile "$1"
			;;
		* )
			${ECHO} "Invalid option: ${1}"
			cd_and_exit 1
			;;
		esac
		
		shift
	done
}


doIt()
{
	getThisPlatform
	set_message_strings
	set_platform_opts
	getInstallDir
	get_params $*
	initialize
	cd ${InstallDir}/bin
	handle_ssl
	finalize
}

doIt $*

