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

# master install script for Exceed TurboX Connection Node, start install log, 
# check for essential files and permissions then call component install scripts

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"
	LOG_CANT_CREATE_LOG="Cannot create log file"
	LOG_DATE="Started on `date` by $USER"
	PROD_INSTALL_OK="$PROD_NAME installed successfully"
	PROD_INSTALL_TIME="Installation finished on `date`"
	PROD_INSTALL_LAST_WORDS1="$PROD_NAME installed successfully."
	PROD_INSTALL_LAST_WORDS2="Check log file for information and warnings:"
	LAUNCHING_TITLE="Launching $SRV_NAME"
	QUERY_LAUNCH_MGR="Would you like to start this Connection Node now?"
	QUERY_CREATE_USER="Would you like to create local fallback account"
	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"
	QUERY_LAUNCH_SSRCONFIG="Configure GPU-enabled server-side OpenGL rendering?"
	SERVER_LISTEN_PORT_ENTER="Please enter Connection Node port number  ["
	SERVER_LISTEN_PORT_ENTER2="]: \c"
	SERVER_LISTEN_PORT_BAD1="Please enter a port number between "
	SERVER_LISTEN_PORT_BAD2=" and "
	SERVER_LISTEN_PORT_WARNINUSE1="Warning! Port number"
	SERVER_LISTEN_PORT_WARNINUSE2="may already be in use,"
	SERVER_LISTEN_PORT_WARNINUSE3="use this port anyway? [y]es or [n]o (<Enter> for no): \c"
	ASK_SERVER_WEB_PORT="Would you like to allow ETX Web Clients to connect to this node?"
	SERVER_WEB_PORT_ENTER="Please enter Web Adaptor port number [%d]: "
	SERVER_WEB_PORT_BAD="Please enter a port number between %d and %d\n"
	SERVER_WEB_PORT_WARNINUSE1="Warning! Port number %d may already be in use,"
	SERVER_WEB_PORT_WARNINUSE2="use this port anyway? [y]es or [n]o: "
	EXPLAIN_MIGRATE="If you have an existing installation of Connection Node on this machine\nyou can choose to migrate it here.\nAs part of this process, the Connection Node identity for the existing\ninstallation will be taken over by this new installation.  Any sessions\nrunning will be stopped and the existing installation will be removed."
	ASK_TO_MIGRATE="Would you like to migrate an existing installation?"
	ASK_OLD_MIGRATE_DIR="Please enter the complete path to the existing install directory of the\nConnection Node on this machine you want to migrate:"
	ASK_TO_REMOVEMIGRATE="Would you like to uninstall the existing installation?"	
	ASK_REGISTERNODE_SERVERNOW="Would you like to register this node with a site now?"
	ASK_REGISTERNODE_SERVERURL="Please enter the server URL to register with"
	ASK_REGISTERNODE_SERVERURL2="in form http[s]://server_hostname[:port]: \c"
	ASK_REGISTERNODE_TOKENAUTH="Connect to this server using API key authentication?"
	ASK_REGISTERNODE_ENABLEAUTHROLE="Use this node for Native/PAM authentication of ETX users?"
	ASK_REGISTERNODE_ENABLEPROXYMGR="Use this node as a Proxy Manager for remote sessions?"
	ASK_REGISTERNODE_ADVANCEDOPTS="Configure advanced options now?"
	ASK_REGISTERNODE_APPSCANNING="Turn on application scanning?"
	ASK_REGISTERNODE_FIRSTDISPLAY="Please enter starting display ID [1]: \c"
	ASK_REGISTERNODE_FIRSTDISPLAY_BAD="Starting display ID must be between 1 and 59535"
	ASK_REGISTERNODE_HOSTNAME="Would you like to provide a different hostname?"
	ASK_REGISTERNODE_ALTNAMESERVER="Would you like to provide an alternative node address(es) for server connections?"
	ASK_REGISTERNODE_ENTERALTNAME="Please enter the address(es) to use:  \c"
	ASK_REGISTERNODE_ALTNAMECLIENT="Would you like to provide an alternative node address(es) for client connections?"
	ASK_REGISTERNODE_SSHCOMMAND="Would you like to provide an SSH command?"
	ASK_REGISTERNODE_ENTERSSHCMD="Please enter the SSH command:  \c"
	ASK_REGISTERNODE_MAXSESSIONS="Would you like to limit the total number of sessions?"
	ASK_REGISTERNODE_ENTERMAXSESSIONS="Please enter the maximum total number of sessions [1]: \c"
	ASK_REGISTERNODE_MAXSESSIONS_BAD="Maximum total number of sessions must be between 1 and 999999"
	ASK_REGISTERNODE_MAXSESSPERUSER="Would you like to limit the number of sessions per user?"
	ASK_REGISTERNODE_ENTERMAXSESSPERUSER="Please enter the maximum number of sessions per user [1]: \c"
	ASK_REGISTERNODE_MAXSESSPERUSER_BAD="Maximum number of sessions per user must be between 1 and %d\n"
	ASK_REGISTERNODE_ALLOWNEWSESS="Allow launching new sessions?"
	ASK_REGISTERNODE_NOTES="Would you like to enter notes for this node?"
	ASK_REGISTERNODE_ENTERNOTES="Please enter notes:  \c"
	ASK_REGISTERNODE_AREYOUSURE="Are you sure you want to register this node with these settings?"
	SERVER_WHY_FALLBACK="If this node is configured with different authentication settings than the\nETX server, this node may be asked to launch sessions on behalf of a user\nthat is not recognized. The following fallback accounts will be used to\nlaunch the ETX proxy and startup commands in this situation:\n1) Exceed TurboX Proxy fallback account 'etxproxy'\n2) Exceed TurboX Xstart fallback account 'etxstart'"
	SERVER_ASK_FALLBACK="Would you like to create these fallback user accounts?"
	FAIL_PREREQUISITE_WARNING="One or more binaries required to run during the installation have\nfailed a prerequisite check and will not succeed on this machine.\nFor more details examine contents of ${InstallDir}/installlogs/prereqs-failed"
}

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

test_PRINTF()
{
    ${PRINTF} "Hello" | grep "Hello" > /dev/null
    if [ $? -eq 0 ]; then
	return 0
    else
	return 1
    fi
}

find_good_printf()
{
    PRINTF=`which printf`
    test_PRINTF
    if [ $? -ne 0 ]; then
	PRINTF=/usr/bin/printf
	test_PRINTF
	if [ $? -ne 0 ]; then
	    ${ECHO} "FATAL ERROR: Cannot find a suitable version of printf."
	    cd_and_exit 1
	fi
    fi
    export PRINTF
    return
}

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
}

getETXFeatures()
{
    if [ ! -f "${binetxpmcontrol}" ] ; then
	${ECHO} "FATAL ERROR: ${binetxpmcontrol} does not exist.  Cannot retrieve ETX features."
	cd_and_exit 1
    fi
    if [ -z "$etxFeatures" ]; then
	etxFeatures=`${binetxpmcontrol} getfeatures`
    export etxFeatures
    fi
}

isWebAdaptorAvailable()
{
	isWebAdaptorAvailableResult=1
	export isWebAdaptorAvailableResult;
    if [ -z "${etxFeatures}" ] ; then
		return 1
    fi
    eq=`echo $etxFeatures | ${GREP} "feature_web_adaptor,1" 2>/dev/null`
    isWebAdaptorAvailableResult=$?
	return ${isWebAdaptorAvailableResult}
}

getOldNodePorts()
{
    oldListenPort=`${binetxpmcontrol} cli getconfig -n | ${GREP} "ListenPort," | cut -d, -f 2 2>/dev/null`
    oldWebPort=`${binetxpmcontrol} cli getconfig -n | ${GREP} "WebAdaptorPort," | cut -d, -f 2 2>/dev/null`
    oldWebAdaptorEnable=`${binetxpmcontrol} cli getconfig -n | ${GREP} "WebAdaptor," | cut -d, -f 2 2>/dev/null`
	export oldListenPort
	export oldWebPort
	export oldWebAdaptorEnable
}

initialize()
{
	init_variables $*
	export_globals
	init_log_file
	get_params $*
	display_install_banner
	areYouRoot
}

getThisPort()
{
	${ECHO} "${SERVER_LISTEN_PORT_ENTER}"${deflistenport}${SERVER_LISTEN_PORT_ENTER2}
	read _deflistenport_
	
	if [ ! "${_deflistenport_}xxxx" = "xxxx" ]; then
		ListenPort=${_deflistenport_}
	else
		ListenPort=${deflistenport}
	fi
}

getWebPort()
{
    ${PRINTF} "${SERVER_WEB_PORT_ENTER}" ${defwebport}
    read _defwebport_

    if [ ! -z "${_defwebport_}" ]; then
	WebPort=${_defwebport_}
    else
	WebPort=${defwebport}
    fi
}

get_netstat()
{
	if [ -x /usr/bin/netstat ]; then
		nstat="/usr/bin/netstat"
	else
		nstat="/bin/netstat"
	fi
}


thisIsNotNaturalNumber()
{
	if [ ! "${1}x" = "x" ] ; then
		THISGREP="${GREP} -c -e [^0123456789]"
		retVal=`echo ${1} | ${THISGREP}`
		if [ "${retVal}" = "0" ] ; then
			return 1
		fi
	fi
	return 0
}

thisPortIsValidAndNotInUse()
{
	if  thisIsNotNaturalNumber ${ListenPort} ; then
		if [ ! "${bSilent}" = "1" ] ; then
			${ECHO} "${SERVER_LISTEN_PORT_BAD1} ${portmin} ${SERVER_LISTEN_PORT_BAD2} ${portmax}"  
		fi
		return 1
	fi
	
	${InstallDir}/bin/nodecmds maint checkport ${ListenPort} > /dev/null 2>&1
	retval=$?

	#${ECHO} ${retval}

	if [ ${retval} -eq 5 ] ; then
		if [ ! "${bSilent}" = "1" ] ; then
			${ECHO} "${SERVER_LISTEN_PORT_WARNINUSE1} ${ListenPort} ${SERVER_LISTEN_PORT_WARNINUSE2}"
			${ECHO} "${SERVER_LISTEN_PORT_WARNINUSE3}"
			
			if read_noyes ; then
			return 1
			fi
		fi
	fi

	if [ ${retval} -eq 1 ] ; then
		if [ ! "${bSilent}" = "1" ] ; then
			${ECHO} "${SERVER_LISTEN_PORT_BAD1} ${portmin} ${SERVER_LISTEN_PORT_BAD2} ${portmax}"
		fi
		return 1
		
	fi


	deflistenport=${ListenPort}
	return 0

}

thisWebPortIsValid()
{
    if thisIsNotNaturalNumber ${WebPort} ; then
	if [ ! "${bSilent}" = "1" ] ; then
	    ${PRINTF} "${SERVER_WEB_PORT_BAD}" ${webmin} ${webmax}
	fi
	return 1
    fi

    if [ ${WebPort} -ne 0 ]; then
	${InstallDir}/bin/nodecmds maint checkport ${WebPort} > /dev/null 2>&1
	retval=$?
    else
	retval=0
    fi
 
    if [ ${retval} -eq 5 ] ; then
	if [ ! "${bSilent}" = "1" ] ; then
	    ${PRINTF} "${SERVER_WEB_PORT_WARNINUSE1}\n" ${WebPort}
	    ${PRINTF} "${SERVER_WEB_PORT_WARNINUSE2}"

	    if read_noyes ; then
		return 1
	    fi
	fi
    fi

    if [ ${retval} -eq 1 ]; then
	if [ ! "${bSilent}" = "1" ]; then
	    ${PRINTF} "${SERVER_WEB_PORT_BAD}" ${webmin} ${webmax}
	fi
	return 1
    fi

    defwebport=${WebPort}
    return 0
}

thisPortIsValid()
{
	if  thisIsNotNaturalNumber ${ListenPort} ; then
		if [ ! "${bSilent}" = "1" ] ; then
			${ECHO} "${SERVER_LISTEN_PORT_BAD1} ${portmin} ${SERVER_LISTEN_PORT_BAD2} ${portmax}"  
		fi
		return 1
	fi
	
	if [ "${ListenPort}" -lt "${portmin}"  -o "${ListenPort}" -gt "${portmax}" ] ; then
		if [ ! "${bSilent}" = "1" ] ; then
			${ECHO} "${SERVER_LISTEN_PORT_BAD1} ${portmin} ${SERVER_LISTEN_PORT_BAD2} ${portmax}"
		fi
		return 1
		
	elif [ -x "${nstat}" ] && ( "${nstat}" -na 2> /dev/null | ${GREP} "[.:]${ListenPort} " > /dev/null 2>&1) ; then
		if [ ! "${bSilent}" = "1" ] ; then
			${ECHO} "${SERVER_LISTEN_PORT_WARNINUSE1} ${ListenPort} ${SERVER_LISTEN_PORT_WARNINUSE2}"
			${ECHO} "${SERVER_LISTEN_PORT_WARNINUSE3}"
			
			if read_noyes ; then
				return 1
			fi
		fi
		
	fi
	
	deflistenport=${ListenPort}
	return 0
}

get_etxcnlistenportnumber()
{
	if [ "${bSilent}" = "1" ] ; then
		if [ -z "${ListenPort}" ] ; then
			ListenPort=${deflistenport}
		fi
		return
	fi
	${ECHO}
	printsectmessage "TCP Port Number"
	
	get_netstat
	
	portmin=1
	portmax=65535
	
	while [ 1 ] 
	do
		getThisPort
		if thisPortIsValidAndNotInUse ; then
			break
		fi
	done
}

get_etxcnwebadaptornumber()
{
    webadaptorenabled=0
    if [ "${bSilent}" = "1" ]; then
		if [ ! -z ${r_WebAdaptor} ] ; then
			webadaptorenabled=${r_WebAdaptor}
		fi
		defwebport=${ListenPort}
        if [ -z "${WebAdaptorPort}" ]; then
            WebPort=${ListenPort}
			WebAdaptorPort=${ListenPort}
		else
			WebPort=${WebAdaptorPort}
        fi
		# ensure on unsupported platforms we disable webadaptor
	    isWebAdaptorAvailable
    	if [ ${isWebAdaptorAvailableResult} -gt 0 ]; then
			webadaptorenabled=0
        fi
        return
    fi

    isWebAdaptorAvailable
    if [ ${isWebAdaptorAvailableResult} -gt 0 ]; then
        # we always pass port (defaulting to 0)
        defwebport=0
        WebPort=0
        return
    fi

    ${ECHO}
    printsectmessage "Web Adaptor Support"

    webmin=0
    webmax=65535

    ${ECHO} ${ASK_SERVER_WEB_PORT}
    ${ECHO} ${YES_OR_NO_DEFAULT_YES}
    if ! read_yesno y; then
        # we always pass port (defaulting to 0)
        defwebport=0
        WebPort=0
        return
    fi

    defwebport=${ListenPort}
    while [ 1 ]; do
	getWebPort
	if [ "${WebPort}" -eq "${ListenPort}" ]; then
	    break
	fi
	if thisWebPortIsValid ; then
	    break
	fi
    done

    webadaptorenabled=1
}

printfirewallportwarning()
{
    portsstring=${ListenPort}
    if [ ${webadaptorenabled} -gt 0 ] && [ "${ListenPort}" -ne "${WebPort}" ] && [ "${WebPort}" -ne "0" ]; then
	portsstring="${portsstring}, ${WebPort}"
    fi
    
    ${ECHO}
    ${PRINTF} "Please ensure that the following TCP port(s) are open in the firewall\non this system: %s\n" "${portsstring}"
    ${ECHO}
}
 
getFirstDisplay()
{
    ${ECHO} "${ASK_REGISTERNODE_FIRSTDISPLAY}"
    read _firstdisplay_

    if [ ! "${_firstdisplay_}xxx" = "xxx" ]; then
	AskFirstDisplay=${_firstdisplay_}
    else
	AskFirstDisplay=1
    fi
}

thisFirstDisplayIsValid()
{
    if thisIsNotNaturalNumber ${AskFirstDisplay} ; then
	if [ ! "${bSilent}" = "1" ]; then
	    ${ECHO} ${ASK_REGISTERNODE_FIRSTDISPLAY_BAD}
	fi
	return 1
    fi

    if [ "${AskFirstDisplay}" -lt "1" -o "${AskFirstDisplay}" -gt "59535" ]; then
	if [ ! "${bSilent}" = "1" ]; then
	    ${ECHO} ${ASK_REGISTERNODE_FIRSTDISPLAY_BAD}
	fi
	return 1
    fi
    
    return 0
}
	
get_firstdisplay()
{
    while [ 1 ]; do
	getFirstDisplay
	if thisFirstDisplayIsValid ; then
	    break
	fi
    done
}

getMaxTotalSessions()
{
    ${ECHO} ${ASK_REGISTERNODE_ENTERMAXSESSIONS}
    read _maxtotalsessions_

    if [ ! "${_maxtotalsessions_}xxx" = "xxx" ]; then
	AskMaxTotalSessions=${_maxtotalsessions_}
    else
	AskMaxTotalSessions=1
    fi
}

thisMaxTotalSessionsIsValid()
{
    if thisIsNotNaturalNumber ${AskMaxTotalSessions} ; then
	if [ ! "${bSilent}" = "1" ]; then
	    ${ECHO} ${ASK_REGISTERNODE_MAXSESSIONS_BAD}
	fi
	return 1
    fi

    if [[ "${AskMaxTotalSessions}" -lt 1 || "${AskMaxTotalSessions}" -gt "999999" ]] ; then
	if [ ! "${bSilent}" = "1" ]; then
	    ${ECHO} ${ASK_REGISTERNODE_MAXSESSIONS_BAD}
	fi
	return 1
    fi
    
    return 0
}

get_maxtotalsessions()
{
    while [ 1 ]; do
	getMaxTotalSessions
	if thisMaxTotalSessionsIsValid ; then
	    break
	fi
    done
}

getMaxSessionsPerUser()
{
    ${ECHO} ${ASK_REGISTERNODE_ENTERMAXSESSPERUSER}
    read _maxsessionperuser_

    if [ ! "${_maxsessionperuser_}xxx" = "xxx" ]; then
	AskMaxSessPerUser=${_maxsessionperuser_}
    else
	AskMaxSessPerUser=1
    fi
}

thisMaxSessionsPerUserIsValid()
{
    maxmaxsessuser=999999
    if [[ "${AskMaxTotalSessions}" -gt 0 && "${AskMaxTotalSessions}" -lt $maxmaxsessuser ]] ; then
	maxmaxsessuser=${AskMaxTotalSessions}
    fi
	
    if thisIsNotNaturalNumber ${AskMaxSessPerUser} ; then
	if [ ! "${bSilent}" = "1" ]; then
	    ${PRINTF} "${ASK_REGISTERNODE_MAXSESSPERUSER_BAD}" ${maxmaxsessuser}
	fi
	return 1
    fi

    if [[ "${AskMaxSessPerUser}" -lt 1 || "${AskMaxSessPerUser}" -gt $maxmaxsessuser ]] ; then
	if [ ! "${bSilent}" = "1" ]; then
	    ${PRINTF} "${ASK_REGISTERNODE_MAXSESSPERUSER_BAD}" ${maxmaxsessuser}
	fi
	return 1
    fi
    
    return 0
}

get_maxsessperuser()
{
    while [ 1 ]; do
	getMaxSessionsPerUser
	if thisMaxSessionsPerUserIsValid ; then
	    break
	fi
    done
}

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
		hostname=`/usr/sbin/check-hostname | awk '{ print $NF }'`
	else
		# 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
	fi
}

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

	if [ "${bSilent}" = "1" ] ; then
		logIncident "1" "${logfile}" "${binDir}/sslcertupdate -install -s ${thisResponseFile} was run."
		${binDir}/sslcertupdate -install -s "${thisResponseFile}"
	else
		logIncident "1" "${logfile}" "${binDir}/sslcertupdate -install  was run."
		${binDir}/sslcertupdate -install
	fi
	retval=$?

	if [ "${retval}" -gt 0 ] ; then
		cd_and_exit ${retval}
	fi
}


addSectionHeader()
{
	if [ "${bSilent}" = "1" ] ; then
		return
	fi
	
	${ECHO} ""
	${ECHO} "${1}"
	${ECHO} "${2}"
	${ECHO} ""
}

getInstallCompleteFlag()
{
	alreadyInstalled=""
	
	if [ -f "${ETXCNProps}" ] ; then  
		alreadyInstalled=`${GREP} -c "${InstallCompleteFlag}"  "${ETXCNProps}"`
	fi
	
	if [ -z "${alreadyInstalled}" ] ; then
		return
	fi
	
	if [ "${alreadyInstalled}" -gt 0 ] ; then
		${ECHO} "${PROD_NAME} has already been installed."
		cd_and_exit 1
	fi
}

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

	getInstallCompleteFlag

	logDir=${InstallDir}/installlogs
	initFile=${logDir}/init.d
	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
}

chmodThisDir()
{
	if [ ! "${bSilent}" = "1" ] ; then
		${ECHO} ".\c" 
	fi
	
	chmod $2 "$1" > /dev/null 2>&1
	
	for f in `ls "$1"` ;
	do
		chmodThisFile "$1/$f" $2 $3
	done
}

chmodThisFile()
{
	if [ -f "$1" ] ; then
		chmod $3 "$1" > /dev/null 2>&1
	elif [ -d "$1" ] ; then
		chmodThisDir "$1" $2 $3
	fi
}

set_platform_opts()
{

	find_good_ECHO
	find_good_grep
	find_good_AWK
	find_good_STAT
	find_good_TR
	find_good_printf

	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
}

display_install_banner()
{
	if [ "${bSilent}" = "1" ] ; then
		return
	fi
	
	${ECHO} ""
	${ECHO} "=================================================="
	${ECHO} "     INSTALL - Exceed TurboX Connection Node      "
	${ECHO} "=================================================="
}

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} > $logfile
	${ECHO} "${PROD_NAME} Installation Log" >> $logfile
	${ECHO} "#####################################################" >> $logfile
	${ECHO} "" >> $logfile
	${ECHO} "" >> $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 install ${PROD_NAME}."
		
		cd_and_exit 1
	fi

}


getCreateService()
{
	BOOTSTART_TITLE="Bootstart Exceed TurboX Connection Node"
	printsectmessage "${BOOTSTART_TITLE}"
	
	createservice=1
}

run_boottime()
{
	logIncident "1" "${logfile}" "Running ${PROD_NAME} install script"
	
	otetxcn_initd_dir="${InstallDir}/runtime/init.d/"
	export otetxcn_initd_dir
	
	getCreateService
	
	if [ "${createservice}" = 1 ] ; then
	
		logIncident "1" "${logfile}" "Registering ${PROD_NAME} as service"
		
		export ListenPort
		${InstallDir}/bin/sys/boottime "++${InstallDir}"
		
		if [ ! -r ${initFile} ] ; then
			cd_and_exit 1
		fi
	fi
}

display_warning_message()
{
	${ECHO}
	${ECHO} "Warning: ${this_msg}"
}

show_this_warning()
{
	this_log="$1"
	
	if [ -r ${this_log} ] ; then
		rm -f ${this_log}
	else
		this_msg="$2"
		display_warning_message
	fi
}

showLastWords()
{
	if [ "${bSilent}" = "1" ] ; then
		return
	fi
	
	printsectmessage "Installation Status"
	
	${ECHO} "${PROD_INSTALL_LAST_WORDS1}"
	
	${ECHO} ""
	${ECHO} "${PROD_INSTALL_LAST_WORDS2}"
	${ECHO} "${logfile}"
	${ECHO} ""
	
}

setInstallCompleteFlag()
{
	${ECHO} "${InstallCompleteFlag}" >> "${ETXCNProps}"
}

change_owner()
{
	chown $*
}

wrap_it_up()
{
	if [ "${thisUname}" = "HP-UX" -o "${isSparc}" = "1" ] ; then
		change_owner "root:root" "${logfile}" "${initFile}"
	fi
	
	# we call this to update the date in the messages below
	set_message_strings
	
	logIncident "1" "${logfile}" "${PROD_INSTALL_OK}" "${PROD_INSTALL_TIME}"
	
	showLastWords
	setInstallCompleteFlag
}

launch_the_server()
{
	otetxcn="${InstallDir}/bin/otetxcn"
	local systemdUnitFile="${InstallDir}/installlogs/systemd.unit.name"
	local systemdUnit=
	local startcmd="${otetxcn} start"
	if [ -f "$systemdUnitFile" ]; then
		systemdUnit=`cat "$systemdUnitFile"`
		startcmd="systemctl start $systemdUnit"
	fi

	if [ "${bSilent}" = "1" ] ; then
		if [ "${StartNow}" = "1" ] ; then
			${ECHO} Starting Exceed TurboX Connection Node now
			export NODESTARTED_OKTOREGISTER=1
			${startcmd}
		else
			${ECHO} Will not start Exceed TurboX Connection Node now
		fi
		return
	fi
	
	${ECHO}
	printsectmessage "${LAUNCHING_TITLE}"
	
	${ECHO} "${QUERY_LAUNCH_MGR}"
	${ECHO} "${YES_OR_NO_DEFAULT_YES}"
	
	if read_yesno y ; then
		export NODESTARTED_OKTOREGISTER=1
		${startcmd}
		if [ -n "$systemdUnit" ]; then
			systemctl status "$systemdUnit"
		fi
	fi
}

create_internal_pam_file()
{
    local connNodeFile="/etc/pam.d/exceed-connection-node"
    local pamdSshFile="/etc/pam.d/sshd"
    local pamdLoginFile="/etc/pam.d/login"

    ${ECHO}
    if [ ! -e "${connNodeFile}" ] ; then
	if [ -f "${pamdSshFile}" ] ; then
	    cp -f ${pamdSshFile} ${connNodeFile}
	    ${ECHO} "PAM configuration ${connNodeFile} created from ${pamdSshFile}"
	elif [ -f "${pamdLoginFile}" ] ; then
	    cp -f ${pamdLoginFile} ${connNodeFile}
	    ${ECHO} "PAM configuration ${connNodeFile} created from ${pamdLoginFile}"
	else
	    ${ECHO} "No PAM configuration ${connNodeFile} created"
	fi
    else
	${ECHO} "PAM configuration already exists: ${connNodeFile}"
    fi
    ${ECHO}
}

ssr_config()
{
	ssrconfig="${InstallDir}/bin/ssrconfig"
	copyssrtosyslib="${InstallDir}/bin/copyssrtosyslib"
	
	if [ -f "${ssrconfig}" ]; then
		${ECHO}
		printsectmessage "SSR Configuration"
		if [ ! "${bSilent}" = "1" ] ; then
			${ECHO} "${QUERY_LAUNCH_SSRCONFIG}"
			${ECHO} "${YES_OR_NO_DEFAULT_NO}"
			if read_yesno ; then
				${ssrconfig} config
			else
				if [ -f "${copyssrtosyslib}" ]; then
					${copyssrtosyslib} updateonly
				fi
			fi
		else
			if [ -f "${copyssrtosyslib}" ]; then
				${copyssrtosyslib} updateonly
			fi
		fi
	fi
}

handle_controlscripttemplates()
{
	thiscontrolfile=$1
	thiscontrolfiletemplate=$2.template
	OurInstallDir=$3
	# Use etxpmctl.template to create etxpmctl script
	if [ -f ${thiscontrolfile} ] ; then
		#${ECHO} "${thiscontrolfile} exists and will not be updated."
		return
	fi

	if [ ! -f ${thiscontrolfiletemplate} ] ; then
		${ECHO} "error ${thiscontrolfiletemplate} does not exist. Verify install package."
		${ECHO} $ABORTING
		cd_and_exit 1
	fi

	# - copy to start to preserve attributes
	rm -f sed_in1.tmp
	rm -f tmp.sh
	cp -f ${thiscontrolfiletemplate} ${thiscontrolfile}
	cat > "sed_in1.tmp" << _sed_in1_EOF_
ETXCN_HOME=${OurInstallDir}
_sed_in1_EOF_

	cat > "tmp.sh" << _tmp_EOF_
#!/bin/sh

InstallDir=${OurInstallDir}

cat ${thiscontrolfiletemplate} | sed '/^ETXCN_HOME=*$/ {
 r sed_in1.tmp
 d
}'
rm -f sed_in1.tmp
_tmp_EOF_

	# mark new file as executable and run it
	chmod +x tmp.sh
	./tmp.sh > ${thiscontrolfile}
	chmod 744 ${thiscontrolfile}
	rm -f tmp.sh

}

create_etxcn_properties()
{
	cat > "${ETXCNProps}" << _ETXCN_PROPERTIES_
ETXCN_HOME=${InstallDir}

_ETXCN_PROPERTIES_
}

handle_etxpmctl_init()
{
	logIncident "1" "${logfile}" "Initialize Connection Node." "`date`"
	
	if [ ! -f "${binetxpmcontrol}" ] ; then
		${ECHO} "FATAL ERROR: ${binetxpmcontrol} does not exist.  The installation cannot continue."
		cd_and_exit 1
	fi
	if [ ! -f "${InstallDir}/runtime/etxpm/etxpmdb" ] ; then
		use_existing_settings=0
	else
	
		# in non-silent install we will handle case of existing settings (silent will always reuse)
		use_existing_settings=1
		getOldNodePorts
		if [ "a${oldWebPort}" = "a" ]; then
			# no WebAdaptorPort so default to 0
			oldWebPort=0
		fi
		if [ "a${oldWebAdaptorEnable}" = "a" ]; then
			# no WebAdaptorEnable so default to off
			oldWebAdaptorEnable=0
		fi
		if [ 0${oldListenPort} -eq 0 ]; then
			# bad database can't use it
			${ECHO} "Existing node settings are invalid and cannot be used (missing Port)."
			use_existing_settings=0
		else
			purgeoldsettings=0
			if [ ! -z ${MIGRATEneedsinit} ] ; then
				if [ ${MIGRATEneedsinit} -gt 0 ] ; then
					purgeoldsettings=1
					use_existing_settings=0
				else
					ListenPort=${oldListenPort}
					export ListenPort
					WebPort=${oldWebPort}
					export WebPort
					webadaptorenabled=${oldWebAdaptorEnable}
					export webadaptorenabled
				fi
			else
				if [ ! "${bSilent}" = 1 ] ; then
					${ECHO}
					${ECHO} "${PROD_NAME} has already been initialized."
					${ECHO} "Would you like to use existing settings (i.e. Port)?"
					${ECHO} "[y]es or [n]o (<Enter> for no) \c"
					if read_yesno ; then
						ListenPort=${oldListenPort}
						export ListenPort
						WebPort=${oldWebPort}
						export WebPort
						webadaptorenabled=${oldWebAdaptorEnable}
						export webadaptorenabled
					else
						purgeoldsettings=1
					fi
				fi
			fi
			if [ ${purgeoldsettings} -gt 0 ] ; then
				rm -f "${InstallDir}/runtime/etxpm/etxpmdb.old" 2> /dev/null
				rm -f "${InstallDir}/runtime/etxpm/etxpmdb-shm.old" 2> /dev/null
				rm -f "${InstallDir}/runtime/etxpm/etxpmdb-wal.old" 2> /dev/null
				mv -f "${InstallDir}/runtime/etxpm/etxpmdb" "${InstallDir}/runtime/etxpm/etxpmdb.old" 2> /dev/null
				mv -f "${InstallDir}/runtime/etxpm/etxpmdb-shm" "${InstallDir}/runtime/etxpm/etxpmdb-shm.old" 2> /dev/null
				mv -f "${InstallDir}/runtime/etxpm/etxpmdb-wal" "${InstallDir}/runtime/etxpm/etxpmdb-wal.old" 2> /dev/null
				use_existing_settings=0
			fi
		fi
	fi
	export use_existing_settings

	if [ ${use_existing_settings} -gt 0 ] ; then
		# if it's existing settings from migration update the last version we were running
		logIncident "1" "${logfile}" "Skipped Connection Node initialization using Existing settings." "`date`"		
	else
		# if migration has a port we should use it if we need to initialize
		if [ ! -z "${MIGRATEneedsport}" ] ; then
			if [ ${MIGRATEneedsport} -lt 1 ] ; then
				if [ ${migListenPort}0 -gt 0 ] ; then
					ListenPort=${migListenPort}
					export ListenPort
				fi
			fi
		fi
		if [ ! -z "${MIGRATEneedswebport}" ] ; then
			if [ ${MIGRATEneedswebport} -lt 1 ] ; then
				if [ ! "a${migWebAdaptorEnable}" = "a" ] ; then
					if [ -z "${migWebAdaptorPort}" ] ; then
						WebPort=${migWebAdaptorPort}
					else
						WebPort=0
					fi
					export WebPort
					webadaptorenabled=${migWebAdaptorEnable}
					export webadaptorenabled
				fi
			fi
		fi
		# Node requires new initialization
		tmp_wapParam=
		if [ ! -z ${WebPort} ]; then
		    tmp_wapParam="WebAdaptorPort=${WebPort}"
		fi
		${binnodecmds} proxymgr init ListenPort=${ListenPort} WebAdaptor=${webadaptorenabled} ${tmp_wapParam} > init_inst_tmp 2>&1
		retVal=$?
		if [ "${retVal}" -gt 0 ] ; then
			logIncident "3" "${logfile}" "Initialize Connection Node failed - code ${retVal}." "`date`"
			${ECHO} "Initialize Connection Node failed"
			cat init_inst_tmp
			${ECHO} "Installation did not complete successfully."
			logIncident "3" "${logfile}" "Installation did not complete successfully." "`date`"
			rm -f init_inst_tmp 2> /dev/null
			cd_and_exit ${retVal}
		else
			rm -f init_inst_tmp 2> /dev/null
		fi
		logIncident "1" "${logfile}" "Initialize Connection Node success." "`date`"
		if [ ! "x${ConnectionNodeMigratedFrom}" = "x" ] ; then
			# save the value (will start/stop server if not already running)
			 ${binnodecmds} setmigratedfrom ${ConnectionNodeMigratedFrom}
		fi

	fi

}

handle_auto_registration_with_server()
{
	${ECHO}
	printsectmessage "Node Registration"
	${ECHO} This node is ready to become part of an Exceed TurboX Site.
	${ECHO} 
	${ECHO} Node registration details:
	${ECHO} Host: ${hostname}
	${ECHO} Port: ${ListenPort}
	## As for 11.0.1 we no longer need IDs for registration
	
	if [ "${bSilent}" = "1" ] ; then
		if [ "${bAutoRegister}" = "1" -a "${NODESTARTED_OKTOREGISTER}" = "1" ] ; then
			if [ ! "${NODESTARTED_OKTOREGISTER}" = "1" ] ; then
				logIncident "3" "${logfile}" "AutoRegister requested but Node was not started so will not take place!"
				return
			fi
			if [ ! -z ${r_serverurl} ] ; then
				ServerPortURL=${r_serverurl}
			else
				logIncident "3" "${logfile}" "AutoRegister failed because r_serverurl value was not provided."
				return
			fi
			
			if [ ! -z ${r_resttoken} ] ; then
				export ETXSVRRESTTOKEN=${r_resttoken}
			fi
			# check env var separately because they may set that before running script instead of embedding in response file
			if [ ! "${ETXSVRRESTTOKEN}z" = "z" ] ; then
				TokenParam="-token "
			fi
			if [ ! -z ${r_overridehostname} ] ; then
				overridehostname="hostname:${r_overridehostname}"
				usethishostnameforregistration=${r_overridehostname}
			fi
			if [ ! -z ${r_auth} ] ; then
				authrole="auth:${r_auth}"
			fi
			if [ ! -z ${r_proxy} ] ; then
				proxymgrrole="proxy:${r_proxy}"
			fi
			if [ ! -z ${r_WebAdaptor} ] ; then
			        webportenableParam="webportenable:${r_WebAdaptor}"
			fi
			if [ ! -z ${WebAdaptorPort} ] ; then
			        webportnumParam="webport:${WebAdaptorPort}"
			fi
			if [ ! -z ${r_appscan} ] ; then
				appscanning="appscan:${r_appscan}"
			fi
			if [ ! -z ${r_altnameserver} ] ; then
				altservername="altnameserver:${r_altnameserver// /}"
			fi
			if [ ! -z ${r_altnameclient} ] ; then
				altclientname="altnameclient:${r_altnameclient// /}"
			fi
			if [ ! -z ${r_firstdisplay} ] ; then
				firstdisplay="firstdisplay:${r_firstdisplay}"
			fi
			if [ ! -z ${r_maxtotalsessions} ] ; then
				maxtotalsessions="maxtotalsessions:${r_maxtotalsessions}"
			fi
			if [ ! -z ${r_maxsessperuser} ] ; then
				maxsessperuser="maxsessperuser:${r_maxsessperuser}"
			fi
			if [ ! -z ${r_allownewsess} ] ; then
				allownewsess="allownewsession:${r_allownewsess}"
			fi
			if [ ! -z ${r_sshcommand} ] ; then
				sshcommand="sshcommand:${r_sshcommand}"
			fi
			if [ ! -z ${r_notes} ] ; then
			        tmpnotes="${r_notes}"
			        notes="notes:${tmpnotes// / }"
			fi
			if [ ! -z ${r_kerberoslib} ] ; then
				kerberoslib="kerberoslib:${r_kerberoslib}"
			fi
			if [ ! -z ${r_gsslib} ] ; then
				gsslib="gsslib:${r_gsslib}"
			fi

			logIncident "1" "${logfile}" "Using host for node registration: ${hostname}"
			if [ -z $TokenParam ] ; then
				logIncident "1" "${logfile}" "Using basic authentication to connect to ${ServerPortURL}"
			else
				logIncident "1" "${logfile}" "Using key authentication to connect to ${ServerPortURL}"
			fi
			if [ -n "${r_ssrconfig}" ] && [ "${r_ssrconfig}" -ne 0 ] ; then
			    local ssrconfig="${InstallDir}/bin/ssrconfig"
			    if [ -f "${ssrconfig}" ] ; then
				${ECHO}
				${ssrconfig} config
				if [ $? -eq 0 ] ; then
				    logIncident "1" "${logfile}" "Completed server-side rendering configuration"
				else
				    logIncident "3" "${logfile}" "Server-side redering configuration failed"
				fi
			    fi
			fi
			logIncident "1" "${logfile}" "Host: ${usethishostnameforregistration}"
			logIncident "1" "${logfile}" "Port: ${ListenPort}"
			logIncident "1" "${logfile}" "Attempting to register ${usethishostnameforregistration}:${ListenPort} with server ${ServerPortURL}"
			${ECHO} "Attempting to register ${usethishostnameforregistration}:${ListenPort}\nwith server ${ServerPortURL}"
			logIncident "1" "${logfile}" "${InstallDir}/bin/nodecmds maint registernode ${ServerPortURL} ${TokenParam} ${ListenPort} enable:1 ${overridehostname} ${authrole} ${proxymgrrole} ${webportenableParam} ${webportnumParam} ${appscanning} ${altservername} ${altclientname} ${firstdisplay} ${r_additionaloptions} ${maxtotalsessions} ${maxsessperuser} ${allownewsess} ${sshcommand} ${notes} ${kerberoslib} ${gsslib}"
			${InstallDir}/bin/nodecmds maint registernode ${ServerPortURL} ${TokenParam} ${ListenPort} enable:1 ${overridehostname} ${authrole} ${proxymgrrole} ${webportenableParam} ${webportnumParam} ${appscanning} ${altservername} ${altclientname} ${firstdisplay} ${r_additionaloptions} ${maxtotalsessions} ${maxsessperuser} ${allownewsess} ${sshcommand} ${notes} ${kerberoslib} ${gsslib}
			if [ $? -eq 0 ] ; then
				logIncident "1" "${logfile}" "Completed registration."
			else
				##  for now silent install registration failure is not an install fail (since user can register after the fact)
				logIncident "3" "${logfile}" "Registration failed."
			fi
			return
		else
			logIncident "1" "${logfile}" "AutoRegister was not enabled"
			return
		fi
	fi

	if [ ! "${NODESTARTED_OKTOREGISTER}" = "1"  ] ; then
		${ECHO}
		${ECHO} "Once this node is started, you can register this node with a running" 
		${ECHO} "site in several ways:"
		${ECHO}
		${ECHO} "1. Access the Server Manager and use the Register node capability;"
		${ECHO} "2. Run 'nodecmds registernode' command at a later time."
		${ECHO}
		return
	fi

	while [ 1 ]
	do
		${ECHO}
		${ECHO} "You can register this node with a running site in several ways:"
		${ECHO}
		${ECHO} "1. Access the Server Manager and use the Register node capability;"
		${ECHO} "2. Run 'nodecmds registernode' command at a later time; or"
		${ECHO} "3. You can register node now."
		${ECHO}
		${ECHO} "NOTE: If you have not established authentication settings yet"
		${ECHO} "      you can use the built-in administration account to"
		${ECHO} "      register the node now."
		${ECHO}
		${ECHO} ${ASK_REGISTERNODE_SERVERNOW}
		${ECHO} ${YES_OR_NO_DEFAULT_NO}
	
	
		if read_yesno ; then

			ServerPortURL=
			${ECHO} ${ASK_REGISTERNODE_SERVERURL}
			${ECHO} ${ASK_REGISTERNODE_SERVERURL2}
			read ServerPortURL
			${ECHO}
			if [ "${ServerPortURL}" != ""  ] ; then

				overridehostname=
				usethishostnameforregistration=
				${ECHO} Using hostname for node registration: ${hostname}
				${ECHO} ${ASK_REGISTERNODE_HOSTNAME}
				${ECHO} ${YES_OR_NO_DEFAULT_NO}
				if read_yesno ; then
					${ECHO} ${ASK_REGISTERNODE_ENTERALTNAME}
					read usethishostnameforregistration
					${ECHO}
					overridehostname="hostname:${usethishostnameforregistration}"
				else
					overridehostname="hostname:${hostname}"
					usethishostnameforregistration=${hostname}
				fi
				authrole=
				${ECHO} ${ASK_REGISTERNODE_ENABLEAUTHROLE}
				${ECHO} ${YES_OR_NO_DEFAULT_NO}
				if read_yesno ; then
					authroleenabled=1
					authrole="auth:1"
				else
					authrole="auth:0"
				fi
				proxyroleenabled=
				${ECHO} ${ASK_REGISTERNODE_ENABLEPROXYMGR}
				${ECHO} ${YES_OR_NO_DEFAULT_YES}
				if read_yesno y ; then
				    proxyroleenabled=1
				    proxymgrrole="proxy:1"
				else
				    proxymgrrole="proxy:0"
				fi
				webportenableParam="webportenable:0"
				webportnumParam=
				if [ ${webadaptorenabled} -gt 0 ]; then
				    if [ ! -z ${proxyroleenabled} ]; then
					webport=${WebPort}
					webportenableParam="webportenable:1"
					webportnumParam="webport:${WebPort}"
				    else
					# Cannot use Web Adaptor without
					# Proxy Manager
					webadaptorenabled=0
				    fi
				fi
				appscanningenabled=0
				if [ ! -z ${proxyroleenabled} ]; then
				    ${ECHO} ${ASK_REGISTERNODE_APPSCANNING}
				    ${ECHO} ${YES_OR_NO_DEFAULT_NO}
				    if read_yesno ; then
					appscanningenabled=1
					appscanning="appscan:1"
				    else
					appscanning="appscan:0"
				    fi
				fi
				advoptionsenabled=0
				${ECHO} ${ASK_REGISTERNODE_ADVANCEDOPTS}
				${ECHO} ${YES_OR_NO_DEFAULT_NO}
				if read_yesno ; then
				    advoptionsenabled=1
				fi
				allownewsessenabled=1
				allownewsess="allownewsession:1"
				if [ ! -z ${proxyroleenabled} ] &&
				   [ ${advoptionsenabled} -ne 0 ]; then
				    ${ECHO} ${ASK_REGISTERNODE_ALLOWNEWSESS}
				    ${ECHO} ${YES_OR_NO_DEFAULT_YES}
				    if read_yesno y ; then
				        allownewsess="allownewsession:1"
				        allownewsessenabled=1
				    else
				        allownewsess="allownewsession:0"
					allownewsessenabled=
				    fi
				fi
				maxtotalsessions=
				if [ ! -z ${allownewsessenabled} ] &&
				   [ ! -z ${proxyroleenabled} ] &&
				   [ ${advoptionsenabled} -ne 0 ]; then
				    ${ECHO} ${ASK_REGISTERNODE_MAXSESSIONS}
				    ${ECHO} ${YES_OR_NO_DEFAULT_NO}
				    if read_yesno ; then
					get_maxtotalsessions
					maxtotalsess="${AskMaxTotalSessions}"
					maxtotalsessions="maxtotalsessions:${AskMaxTotalSessions}"
					${ECHO}
				    fi
				fi
				maxsessperuser=
				if [ ! -z ${allownewsessenabled} ] &&
				   [ ! -z ${proxyroleenabled} ] &&
				   [ ${advoptionsenabled} -ne 0 ]; then
				    ${ECHO} ${ASK_REGISTERNODE_MAXSESSPERUSER}
				    ${ECHO} ${YES_OR_NO_DEFAULT_NO}
				    if read_yesno ; then
					get_maxsessperuser
					maxsesspu="${AskMaxSessPerUser}"
					maxsessperuser="maxsessperuser:${AskMaxSessPerUser}"
					${ECHO}
				    fi
				fi
				firstdisp=1
				if [ ${advoptionsenabled} -ne 0 ] &&
				   [ ! -z ${proxyroleenabled} ]; then
				    get_firstdisplay
				    firstdisp="${AskFirstDisplay}"
				    firstdisplay="firstdisplay:${AskFirstDisplay}"
				    ${ECHO}
				fi
				if [ ${advoptionsenabled} -ne 0 ] &&
				   [ ! -z ${proxyroleenabled} ]; then
				    ${ECHO} ${ASK_REGISTERNODE_SSHCOMMAND}
				    ${ECHO} ${YES_OR_NO_DEFAULT_NO}
				    if read_yesno ; then
				        ${ECHO} ${ASK_REGISTERNODE_ENTERSSHCMD}
					read tmpsshcommand
					${ECHO}
					sshcommand="sshcommand:${tmpsshcommand}"
				    else
				        sshcommand=
				    fi
				fi
				if [ ${advoptionsenabled} -ne 0 ]; then
				   ${ECHO} ${ASK_REGISTERNODE_ALTNAMESERVER}
				   ${ECHO} ${YES_OR_NO_DEFAULT_NO}
				   if read_yesno ; then
				       ${ECHO} ${ASK_REGISTERNODE_ENTERALTNAME}
				       read tmpaltservername
				       ${ECHO}
				       altservername="altnameserver:${tmpaltservername// /}"
				   else
				       altservername=
				   fi
				fi
				if [ ${advoptionsenabled} -ne 0 ]; then
				    ${ECHO} ${ASK_REGISTERNODE_ALTNAMECLIENT}
				    ${ECHO} ${YES_OR_NO_DEFAULT_NO}
				    if read_yesno ; then
					${ECHO} ${ASK_REGISTERNODE_ENTERALTNAME}
					read tmpaltclientname
					${ECHO}
					altclientname="altnameclient:${tmpaltclientname// /}"
				    else
					altclientname=
				    fi
				fi
				if [ ${advoptionsenabled} -ne 0 ]; then
				    ${ECHO} ${ASK_REGISTERNODE_NOTES}
				    ${ECHO} ${YES_OR_NO_DEFAULT_NO}
				    if read_yesno ; then
					${ECHO} ${ASK_REGISTERNODE_ENTERNOTES}
					read tmpnotes
					${ECHO}
					notes="notes:${tmpnotes// / }"
				    else
					notes=
				    fi
				fi
				${ECHO}
				###   Tell them what we are about to do...
				${ECHO} "Registration options selected:"
				${ECHO} "------------------------------"
				${ECHO} ETX Server URL: ${ServerPortURL}
				${ECHO} Host: ${usethishostnameforregistration}
				${ECHO} Connection Node port: ${ListenPort}
				if [ -z ${authroleenabled} ] ; then
					${ECHO} Authenticator role: not enabled
				else
					${ECHO} Authenticator role: enabled
				fi
				if [ -z ${proxyroleenabled} ] ; then
					${ECHO} Proxy Manager role: not enabled
				else
					${ECHO} Proxy Manager role: enabled
				fi
				isWebAdaptorAvailable
				if [ ${webadaptorenabled} -lt 1 -o ${isWebAdaptorAvailableResult} -gt 0 ] ; then
				    ${ECHO} Web Adaptor: not enabled
				else
				    ${ECHO} Web Adaptor: enabled
				    ${ECHO} Web Adaptor port: ${webport}
				fi
				if [ ${appscanningenabled} -lt 1 ] ; then
				    ${ECHO} Application scanning: not enabled
				else
				    ${ECHO} Application scanning: enabled
				fi
				if [ -z ${allownewsessenabled} ] ; then
				    ${ECHO} Allow launching new sessions: not enabled
				else
				    ${ECHO} Allow launching new sessions: enabled
				    if [ ! -z ${maxtotalsessions} ] ; then
					${ECHO} Maximum total number of sessions: ${maxtotalsess}
				    fi
				    if [ ! -z ${maxsessperuser} ] ; then
					${ECHO} Maximum number of sessions per user: ${maxsesspu}
				    fi
				fi				    
				${ECHO} Starting display ID: ${firstdisp}
				if [ -z ${sshcommand} ] ; then
				    ${ECHO} SSH Command: not provided
				else
				    ${ECHO} SSH Command: ${tmpsshcommand}
				fi
				if [ -z ${altservername} ] ; then
				    ${ECHO} "Alternative node address(es) for server connections: not provided"
				else
				    ${ECHO} "Alternative node address(es) for server connections: ${tmpaltservername}"
				fi
				if [ -z ${altclientname} ] ; then
				    ${ECHO} "Alternative node address(es) for client connections: not provided"
				else
				    ${ECHO} "Alternative node address(es) for client connections: ${tmpaltclientname}"
				fi
				if [ -z "${notes}" ] ; then
				    ${ECHO} Notes: not provided
				else
				    ${ECHO} Notes: ${tmpnotes}
				fi
				${ECHO}
				
				## are you sure you want to register as this?
				${ECHO} ${ASK_REGISTERNODE_AREYOUSURE}
				${ECHO} ${YES_OR_NO_DEFAULT_NO}
				if read_yesno ; then
					
					TokenParam=
					${ECHO} ${ASK_REGISTERNODE_TOKENAUTH}
					${ECHO} ${YES_OR_NO_DEFAULT_NO}
					if read_yesno ; then
						TokenParam="-token "
					fi
					
					${ECHO} "Attempting to register ${usethishostnameforregistration}:${ListenPort}\nwith server ${ServerPortURL}"
					${ECHO}
					${InstallDir}/bin/nodecmds maint registernode ${ServerPortURL} ${TokenParam} ${ListenPort} enable:1 ${overridehostname} ${authrole} ${proxymgrrole} ${webportenableParam} ${webportnumParam} ${appscanning} ${firstdisplay} ${altservername} ${altclientname} ${sshcommand} ${allownewsess} ${maxtotalsessions} ${maxsessperuser} ${notes}
					if [ $? -eq 0 ] ; then
						${ECHO}
						break
					fi
				fi
			fi
		else
			break
		fi
	done

}

verify_existing_folder()
{
	thisFolder=`echo ${1} | sed 's/\/$//'`

	if [ "${InstallDir}" = "${thisFolder}" ] ; then
		${ECHO} "The existing installation directory is the same as the current one.\nYou cannot migrate from this location."
		return 1
	fi
	# -- Starting from 11.0 we no longer need etxcn.ini to migrate since Database is all on server side now
	if [ ! -f "${thisFolder}/bin/otetxcn" ] ; then
		${ECHO} "The existing installation directory is not properly configured.\nThe otetxcn script is missing.  You cannot migrate from this location."
		return 1
	fi
	doubleCheck=`${thisFolder}/bin/otetxcn home`
	resolveDir ${thisFolder} thisFolder CD
	
	if [ "${doubleCheck}" != "${thisFolder}" ] ; then
		${ECHO} "The existing installation directory is not properly configured.\nThe otetxcn script home location is wrong. You cannot migrate from this location."
		return 1
	fi 
	
	# ok 
	bMigrate="1"
	MIGRATEInstallDir=${thisFolder}
	MIGRATEOtexcn=${MIGRATEInstallDir}/bin/otetxcn
	
	# get the current cnpkg-version value
	# in 10.5 the location moved to installlogs
	MIGRATEOLDVER=`cat ${MIGRATEInstallDir}/installlogs/.cnpkg-version 2>/dev/null`
	if [ ! -n "${MIGRATEOLDVER}" ] ; then
		MIGRATEOLDVERSSLBAD=1
		MIGRATEOLDVER=`cat ${MIGRATEInstallDir}/bin/.cnpkg-version 2>/dev/null`
		if [ ! -n "${MIGRATEOLDVER}" ] ; then
			MIGRATEOLDVER="10.0.0.850"
		fi
	fi
	
	# ETX-6792 - migration floor 11.x
	`echo ${MIGRATEOLDVER} | grep 10\.[0-9]\.[0-9][0-9]*\.[0-9][0-9]*  > /dev/null 2>&1`
	result=$?
	if [ ${result} -eq 0 ] ; then
		bMigrate=
		${ECHO} "The existing installation directory is too old to migrate. You cannot migrate from this location."
		return 1
	fi
	
	cnpkgversion=`cat ${InstallDir}/installlogs/.cnpkg-version  2>/dev/null`
	if [ ! -n "${cnpkgversion}" ] ; then
		${ECHO} "FATAL ERROR: Cannot obtain connection Node version value from .cnpkg-version file.  The installation cannot continue."
		cd_and_exit 1
	fi
	
	`echo ${MIGRATEOLDVER} | grep 12\.0\.[0-9][0-9]*\.[0-9][0-9]*  > /dev/null 2>&1`
	result=$?
	if [ ${result} -eq 0 ] ; then
		bMigrate=
		${ECHO} "Connection Node installed in this directory cannot be migrated."
		${ECHO} "Instead apply equivalent patch tar and run the patch script."
		return 1
	fi
	
	return 0
}


ask_about_migrate()
{
	if [ "${bSilent}" = "1" ] ; then
		if [ "${AllowMigrate}" = "1" ] ; then
			verify_existing_folder "${MigrateFromThisFolder}"
			if [ $? -eq 0 ] ; then
				${ECHO}
				${ECHO} Beginning settings migration from ${MIGRATEInstallDir}
				logIncident "1" "${logfile}" "Beginning settings migration from ${MIGRATEInstallDir}"
				return
			else
				# fail - 
				logIncident "3" "${logfile}" "Migration failed to verify existing directory ${MigrateFromThisFolder}"
				cd_and_exit 1
			fi
		else
			logIncident "1" "${logfile}" "Migration not enabled"
			migrate_disable
			return
		fi
	fi
	printsectmessage "Migration"
	${ECHO} "${EXPLAIN_MIGRATE}"

	while [ 1 ]
	do

		${ECHO}
		${ECHO} "${ASK_TO_MIGRATE}"
		${ECHO} "${YES_OR_NO_DEFAULT_NO}"

		if read_yesno ; then
			# Now get the path and validate it
			${ECHO} "${ASK_OLD_MIGRATE_DIR}"

			read existingDir
			verify_existing_folder "${existingDir}"
			if [ $? -eq 0 ] ; then
				${ECHO}
				${ECHO} "${ASK_TO_REMOVEMIGRATE}"
				${ECHO} "${YES_OR_NO_DEFAULT_NO}"			
				if read_yesno ; then
					MIGRATEremoveold=1
				else
					MIGRATEremoveold=0
				fi
				export MIGRATEremoveold
				${ECHO}
				${ECHO} Beginning settings migration from ${MIGRATEInstallDir}
				break
			fi
			# -ask again until we get directory we want
		else
			migrate_disable
			break
		fi
	done
}

migrate_disable()
{
        MIGRATEneedsinit=
        MIGRATEneedsport=
		MIGRATEneedswebport=
        MIGRATEshouldasktoregister=
        MIGRATEOLDVER=
        MIGRATEInstallDir=
		MIGRATEremoveold=

        export MIGRATEneedsinit
        export MIGRATEneedsport
		export MIGRATEneedswebport
        export MIGRATEOLDVER
        export MIGRATEInstallDir
        export MIGRATEshouldasktoregister
		export MIGRATEremoveold
}

migrate_stop_old_node_completely()
{
	${ECHO}
	${MIGRATEOtexcn} fullstop
	if [ $? -gt 0 ] ; then
		${ECHO} The existing node running at ${MIGRATEInstallDir} could not be stopped.  Please try to stop manually before attempting to upgrade.
		logIncident "3" "${logfile}" "The existing node running at ${MIGRATEInstallDir} could not be stopped.  Please try to stop manually before attempting to upgrade."
		cd_and_exit 1
	fi
}

migrate_ssl()
{
	# if we are migrating from a version prior to 10.5 then we need to regenerate our SSL keys
	#
	if [ "${MIGRATEOLDVERSSLBAD}" = "1" ] ; then
		# don't migrate SSL from version 10 because certificate is not generated fully
		handle_ssl
	else
		MIGRATEetxssldir=${MIGRATEInstallDir}/runtime/keys
		MIGRATEetxcertpem=${MIGRATEetxssldir}/etxcert.pem
		MIGRATEetxprivpem=${MIGRATEetxssldir}/etxpriv.pem
		MIGRATEetxsslconfig=${MIGRATEetxssldir}/etxssl_config.cnf
		cp -f ${MIGRATEetxprivpem} ${etxprivpem}
		cp -f ${MIGRATEetxcertpem} ${etxcertpem}
		cp -f ${MIGRATEetxsslconfig} ${etxsslconfig}
		
		# we need FQDN hostname this all the time
		gethostnamefqdn
	fi
}

removeThisLinkOrFile()
{
	if [ -f "${1}" -o -h "${1}" -o ${optionL} "${1}" ] ; then
		rm -f "${1}"
	fi
}

removeTheseRcLinks()
{
	theseLinks=`ls ${1} 2>&1`
	
	for eachLink in ${theseLinks} ; do
		removeThisLinkOrFile ${eachLink}
	done
}

migrate_remove_old_node_completely()
{
	# don't give them the option to do anything
	if [ 0${MIGRATEremoveold} -lt 1 ] ; then
		logIncident "1" "${logfile}" "Preserving existing node at:\n${MIGRATEInstallDir}"
		return
	fi

	# -- we will do this manually now...
	# figure out what service name is from old Migration location
	tmp_value=`${GREP} "thisInitScript=" "${MIGRATEOtexcn}" 2> /dev/null | cut -f2- -d=`
	tmp_value2=`echo ${tmp_value}|${TR} -d '\011\012\015'`
	thisETXCNService=`basename ${tmp_value2}`
	export thisETXCNService

	if [ "x${thisETXCNService}" = "x" ] ; then
		# nothing to do since we cannot determine service name
		${ECHO} The existing service from node ${MIGRATEInstallDir} was not registered so it will not be removed.
		logIncident "1" "${logfile}" "The existing service from node ${MIGRATEInstallDir} was not registered so it will not be removed."
	else
		# Now do removeService()
		thisChkConfig="/sbin/chkconfig"
		
		if [ -x "${thisChkConfig}" ] ; then
		${thisChkConfig} --del ${thisETXCNService} > /dev/null 2>&1
		fi
		
		thisUpdateRcD="/usr/sbin/update-rc.d"
		
		if [ -x "${thisUpdateRcD}" ] ; then
		${thisUpdateRcD} -f ${thisETXCNService} remove > /dev/null 2>&1
		${thisUpdateRcD} ${thisETXCNService} remove > /dev/null 2>&1
		fi
		
		if [ "${thisOS}" = "${osSolaris}" ] ; then
			thisSvcAdm="/usr/sbin/svcadm"
			
			removeTheseRcLinks "/etc/rc?.d/*${thisETXCNService}"
			
			if [ -x "${thisSvcAdm}" ] ; then
				${thisSvcAdm} disable -t ${thisETXCNService} > /dev/null 2>&1
			fi
			
			removeThisLinkOrFile "/etc/init.d/${thisETXCNService}"
		fi
		
		if [ "${thisOS}" = "${osHPUX}" ] ; then
			removeTheseRcLinks "/sbin/rc?.d/*${thisETXCNService}"
			removeThisLinkOrFile "/sbin/init.d/${thisETXCNService}"
		fi
		
		if [ "${thisOS}" = "${osAix}" ] ; then
			removeTheseRcLinks "/etc/rc.d/rc?.d/*${thisETXCNService}"
			removeThisLinkOrFile "/etc/rc.d/init.d/${thisETXCNService}"
		fi
		
		if [ "${thisOS}" = "${osLinux}" ] ; then
			removeThisLinkOrFile "/etc/rc.d/init.d/${thisETXCNService}"
			removeThisLinkOrFile "/etc/init.d/${thisETXCNService}"
		fi
	fi

	# now remove directory structure
	sleep 1
	
	${ECHO} "Removing existing node at:\n ${MIGRATEInstallDir}"
	logIncident "1" "${logfile}" "Removing existing node at:\n${MIGRATEInstallDir}"
	rm -rf ${MIGRATEInstallDir}

	if [ -d "${MIGRATEInstallDir}" ] ; then
		${ECHO} "Warning the installation directory at:\n${MIGRATEInstallDir}"
		${ECHO} "could not be completely removed. Manual cleanup is required."
	else
		${ECHO} "Removal complete."
	fi
	${ECHO}
}


migrate_handle_db_registration()
{
	MIGRATEneedsport=1
	MIGRATEneedswebport=1
	MIGRATEneedsinit=1
	MIGRATEshouldasktoregister=0	
	`echo ${MIGRATEOLDVER} | grep 11\.[0-5]\.[0-9][0-9]*\.[0-9][0-9]*  > /dev/null 2>&1`
	result=$?
	if [ ${result} -eq 0 ] ; then
		# it is 11.0+ and we do not have database access in node
		# in Server database already for now and copy etxpmdb over from old location to here

		# peform some db queries 
		# performing a tricky operation here
		if [ -f ${MIGRATEInstallDir}/runtime/etxpm/etxpmdb ] ; then
		
			# check if we are registered with a server
			migServerReg=`echo "SELECT VAL from SYSTEM WHERE KEY='RegisteredServerToken';" | ${MIGRATEInstallDir}/bin/etxpmctl -s dbshell 2>/dev/null | grep -v "^WARNING"`
			if [ "x${migServerReg}" = "x" ] ; then
				MIGRATEshouldasktoregister=1
			fi

			# retrieve old port information
			migListenPort=`echo "SELECT VAL from CONFIG WHERE KEY='ListenPort';" | ${MIGRATEInstallDir}/bin/etxpmctl -s dbshell 2>/dev/null |grep -v "^WARNING"`
			if [ ${migListenPort}0 -gt 0 ] ; then
				MIGRATEneedsport=0
			fi
			migWebAdaptorEnable=`echo "SELECT VAL from CONFIG WHERE KEY='WebAdaptor';" | ${MIGRATEInstallDir}/bin/etxpmctl -s dbshell 2>/dev/null |grep -v "^WARNING"`
			if [ "a${migWebAdaptorEnable}" = "a" ] ; then
				MIGRATEneedswebport=1
				migWebAdaptorPort=0
			else
				migWebAdaptorPort=`echo "SELECT VAL from CONFIG WHERE KEY='WebAdaptorPort';" | ${MIGRATEInstallDir}/bin/etxpmctl -s dbshell 2>/dev/null |grep -v "^WARNING"`
			fi



			ConnectionNodeMigratedFrom=${MIGRATEOLDVER}
			export ConnectionNodeMigratedFrom
		# else
		#  -- no etxpmdb means we never have been initialized so ask for port and initialize
		fi
		result=0
	fi
	export MIGRATEneedsinit
	export MIGRATEneedsport
	export MIGRATEshouldasktoregister
	export MIGRATEneedswebport

}


migrate_save_additional_content()
{
	#
	`echo ${MIGRATEOLDVER} | grep 11\.[0-5]\.[0-9][0-9]*\.[0-9][0-9]*  > /dev/null 2>&1`
	result=$?
	if [ ${result} -eq 0 ] ; then
		# copy custom font directory
		cp -f ${MIGRATEInstallDir}/conf/font/user/* ${conf_dir}/font/user/  > /dev/null 2>&1
	fi
}


function swap_LANG_to_C()
{
	OLDLANG=$LANG
	export OLDLANG
	OLDLC_ALL=$LC_ALL
	export OLDLC_ALL
	LANG=C
	export LANG
	LC_ALL=C
	export LC_ALL
}

function swap_LANG_to_OLD()
{
	LANG=$OLDLANG
	export LANG
	LC_ALL=$OLDLC_ALL
	export LC_ALL
}

function perm_statify()
{
	swap_LANG_to_C
	thisperm=`${STAT} $1 | grep Access | head -1| ${AWK} 'BEGIN{FS="[(/]"} {print $2}'`
	swap_LANG_to_OLD
	perm_user=${thisperm:1:1}
	if [ -e ${perm_user} ] ; then
		perm_user=0
	fi
	perm_group=${thisperm:2:1}
	if [ -e ${perm_group} ] ; then
		perm_group=0
	fi
	perm_all=${thisperm:3:1}
	if [ -e ${perm_all} ] ; then
		perm_all=0
	fi
}

function permcheck_uptree()
{
	perm_statify $PWD
	good_perm=5
	if [ ${perm_all} = 5 -o ${perm_all} = 7 ] ; then
		good_perm=0
	fi
	if [ ${good_perm} -gt 0 ] ; then
		${ECHO} "Checking for necessary directory permissions"
		logIncident "3" "${logfile}" "FATAL ERROR:  Directory $PWD has permission (${perm_user}${perm_group}${perm_all}) but needs Global READ + EXECUTE permissions for this ETX Node installation to function properly."
		${ECHO}  "FATAL ERROR:  Directory $PWD\nhas permission (${perm_user}${perm_group}${perm_all}) but needs Global READ + EXECUTE permissions\nfor this ETX Node installation to function properly."
		cd_and_exit 1
	fi
	if [ "$PWD" = '/' ] ; then
		return ${good_perm}
	fi
	cd .. > /dev/null
	permcheck_uptree
	return $?
}

checkfolderpermissions()
{
	if [ "${STAT}x" = "x" ] ; then
		${ECHO} "Checking for necessary directory permissions"
		${ECHO} "Unable to check permissions on ${InstallDir}.  Please manually ensure that all users have READ + EXECUTE access to it and all parent directories."
		return
	fi
	# new 11.0.2 - check if all parent directories starting from CWD have global Read/Execute permissions
	permcheck_uptree
	# restore proper location now
	cd ${InstallDir}/bin
}

doprequisitescheck()
{
	rm -f ${InstallDir}/installlogs/prereqs-failed
	if [ "${bSilent}" = "1" ] ; then
		${InstallDir}/bin/prereqcheck -s ${thisResponseFile}
	else
		${InstallDir}/bin/prereqcheck -e
	fi
	missing_count=$?
	if [ $missing_count -gt 0 ] ; then
		# ${InstallDir}/installlogs/prereqs-failed has essential content if key components don't work
		if [ -f ${InstallDir}/installlogs/prereqs-failed ] ; then
			logIncident "3" "${logfile}" "One or more binaries required to run during the installation have failed a prerequisite check and will not succeed on this machine. For more details examine contents of ${InstallDir}/installlogs/prereqs-failed"
			# reset message strings because InstallDir is now populated and this affects error strings
			set_message_strings
			${ECHO} "${FAIL_PREREQUISITE_WARNING}"
			if [ "${bSilent}" = "1" ] ; then
				${ECHO} "The following installation critical binaries failed their prerequisites:"
				cat ${InstallDir}/installlogs/prereqs-failed
				${ECHO}
				${ECHO} "The installation cannot continue until these are resolved."
			fi
			cd_and_exit 1
		fi
	fi
	${ECHO}
}

main_install()
{
	cd ${InstallDir}/bin
	doprequisitescheck
	checkfolderpermissions
	ask_about_migrate
	create_etxcn_properties
	handle_controlscripttemplates  ${binetxpmcontrol}  ${binsysetxpmcontrol}  ${InstallDir}
	handle_controlscripttemplates  ${binnodemaintcontrol} ${binsysnodemaintcontrol} ${InstallDir}
	getETXFeatures
	whyfallbackuser
	createfallbackuser etxproxy "Exceed TurboX Proxy fallback account" "0" ${CreateETXProxyUser}
	createfallbackuser etxstart "Exceed TurboX Xstart fallback account" "1" ${CreateETXXstartUser}
	if [ "${bMigrate}" = "1" ] ; then
		# migration stuff
		migrate_stop_old_node_completely
		migrate_ssl
		migrate_handle_db_registration
		migrate_save_additional_content
		migrate_remove_old_node_completely
		if [ ${MIGRATEneedsport} -gt 0 ] ; then
			${ECHO} "Failed to determine Port information from old installation."
			# ask user for new port
			get_etxcnlistenportnumber
		fi
		if [ ${MIGRATEneedswebport} -gt 0 ] ; then
			get_etxcnwebadaptornumber
		fi
		run_boottime
		handle_auto_patch
		handle_etxpmctl_init
		ssr_config
		create_internal_pam_file
		launch_the_server
		# if we think old node was not registered then we should show registration otherwise skip it
		if [ ${MIGRATEshouldasktoregister} -gt 0 ] ; then
			handle_auto_registration_with_server
		else
			logIncident "1" "${logfile}" "Skipping node registration because it appears the existing node installation folder is registered with a server already."
		fi
	else
	        get_etxcnlistenportnumber
	        get_etxcnwebadaptornumber
		printfirewallportwarning
		handle_ssl
		run_boottime
		handle_auto_patch
		handle_etxpmctl_init
		ssr_config
		create_internal_pam_file
		launch_the_server
		handle_auto_registration_with_server
	fi
	wrap_it_up
}

readThisSectionKeyValueForThisVariable()
{
	thisPropFile=$1
	thisSection=$2
	thisKey=$3
	thisKeyFullName=${thisSection}.${thisKey}
	if [ "${thisKey}" == "r_resttoken" ] ; then
		protected=1
	else
		protected=0
	fi
	
	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}"
	if [ ! -z "${tmp_value}" ] ; then
		if [ 0${protected} -gt 0 ] ; then
			logIncident "1" "${logfile}" "Silent protected value: ${thisKeyFullName}=..............................."
		else
			logIncident "1" "${logfile}" "Silent value: ${thisKeyFullName}=${ret_value}"
		fi
	else
		${ECHO} "Silent value missing: ${thisKeyFullName}"
		logIncident "1" "${logfile}" "Silent value missing: ${thisKeyFullName}"
	fi
	
}

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="ListenPort StartNow SaveConnectionNodeIdToFile CreateETXProxyUser CreateETXXstartUser AllowMigrate MigrateFromThisFolder"
	readThisSectionKeys "${thisResponseFile}" "install.etxcn" "${theseKeys}"
	
	theseKeys="bBootStart createservice" 
	readThisSectionKeys "${thisResponseFile}" "install.service" "${theseKeys}"
	
	theseKeys="bAutoRegister r_serverurl r_resttoken r_overridehostname r_proxy r_WebAdaptor WebAdaptorPort r_auth r_appscan r_firstdisplay r_altnameserver r_altnameclient r_additionaloptions r_maxtotalsessions r_maxsessperuser r_allownewsess r_sshcommand r_notes r_ssrconfig"
	readThisSectionKeys "${thisResponseFile}" "install.register" "${theseKeys}"
}


get_params()
{
	builtinResponseFile="${InstallDir}/conf/builtin.resp"
	
	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
			;;
		-s )
			if [ -z "$2" ] ; then
				usage
				cd_and_exit
			fi
			shift
			bSilent="1"
			readResponseFile "$1"
			;;
		* )
			${ECHO} "Invalid option: ${1}"
			cd_and_exit 1
			;;
		esac
		
		shift
	done
	
	# set default port
	if [ "z${deflistenport}" = "z" ] ; then
		deflistenport=5510
	fi
	
	export deflistenport
}

whyfallbackuser()
{
	if [ "${bSilent}" = "1" ] ; then
		return `expr ${CreateETXProxyUser}0 + ${CreateETXXstartUser}0`
	fi
	printsectmessage "Configuring Fallback Accounts"
	${ECHO} "${SERVER_WHY_FALLBACK}"
}

createfallbackuser()
{
	account=$1
	description=$2
	shellaccess=$3
	silent_flag=$4
	# if not exist etxstart, create etxstart fallback account
	id ${account} > /dev/null 2>&1
	retVal=$?
	
	${ECHO}
	if [ "${retVal}" = "0" ] ; then
		${ECHO} "Using existing account '${account}'."
	else

		if [ "${bSilent}" = "1" ] ; then
			if [ "${silent_flag}" = "0" ] ; then
				${ECHO} "Will not create ${description} '${account}'."
				return
			fi
			resp=0
		else
			${ECHO} "${QUERY_CREATE_USER} '${account}'?:"
			${ECHO} "${YES_OR_NO_DEFAULT_NO}"
			read_yesno
			resp=$?
		fi
		
		if [ "${resp}" = "0" ] ; then
			${ECHO} "Configuring ${description} '${account}'"
			# In solaris 10, default home location used is /home yet no permissions must be /export/home
			if [ "${thisOS}" = "${osSolaris}" -a "${solarisVersion}" = "10" ] ; then
				USERADDOPTS_WITHSHELL="${USERADDOPTS_WITHSHELL} -d /export/home/${account}"
			fi
			
			if [ "${shellaccess}" = "0" ] ; then
				if [ "${thisOS}" = "${osAix}" ] ; then
					cp /etc/security/login.cfg /etc/security/login.cfg.bak
					sed "s/\(shells =.*\)/\1,\/bin\/false/" /etc/security/login.cfg.bak > /etc/security/login.cfg
				fi
				useradd -c "${description}" ${USERADDOPTS} -s /bin/false ${account} > /dev/null 2>&1
			else
				useradd -c "${description}" ${USERADDOPTS_WITHSHELL} ${account} > /dev/null 2>&1
			fi
			if [ $? -gt 0 ] ; then
				${ECHO} "WARNING: '${account}' could not be created.  Please manually create '${account}'"
				${ECHO} "or ${description} functionality will be broken."
				return
			else
				${ECHO} "${description} '${account}' was created."
			fi
		else
			${ECHO} "${description} '${account}' was not created."
			return
		fi
	fi
	
	# At this point we either created the account or it already exists so validate basics
	if [ "${shellaccess}" = "0" ] ; then
		# verify that account can access InstallDir
		${ECHO} "Checking if '${account}' has required directory access."
		${InstallDir}/bin/nodecmds maint checkuser ${account} ${InstallDir} > /dev/null 2>&1
		if [ $? -gt 0 ] ; then
			${ECHO} "FATAL ERROR: ${description} '${account}' does not have access to ${InstallDir}."
			cd_and_exit 1
		fi
	else
		${ECHO} "Checking if '${account}' has required home directory."
		account_home=`grep "${account}:" /etc/passwd | cut -d ":" -f6`
		if [ -z "${account_home}" ] ; then
			${ECHO} "WARNING: Cannot locate home directory for '${account}'.  Please ensure that"
			${ECHO} "home directory exists or '${description}' functionality"
			${ECHO} "will be broken."
		else
			if [ ! -d ${account_home} ] ; then
				${ECHO} "WARNING: The home directory for '${account}' does not exist."
				${ECHO} "It should be located at '${account_home}'."
				${ECHO} "Please create this directory or '${description}'"
				${ECHO} "functionality will be broken."
			fi
		fi
	fi

}

handle_auto_patch()
{
	# if we see bin/patch file we will run it automatically
	if [ ! -x "${binDir}/patch" ] ; then
	return
	fi

	# either we run it silently passing our own responsefile for answers or
	# we run it in patch apply mode (since we are not installed it will
	# not ask to reboot the server)
	if [ "${bSilent}" = "1" ] ; then
		logIncident "1" "${logfile}" "${binDir}/patch -install -s ${thisResponseFile} was run."
		${binDir}/patch -install -s "${thisResponseFile}"
	else
		PATCHING_TITLE="Patching"
		printsectmessage "${PATCHING_TITLE}"
		logIncident "1" "${logfile}" "${binDir}/patch -install  was run."
		${binDir}/patch -install
	fi
}

doIt()
{
	getThisPlatform
	set_message_strings
	set_platform_opts
	getInstallDir
	initialize $*
	main_install
	finalize
}

doIt $*

