#!/bin/sh

# #################################################################################
# Exceed TurboX Connection Node
# Copyright (c) Open Text. All Rights Reserved. Trademarks owned by Open Text.
# #################################################################################
# nodecmds.sh
# File Version = 1
# #################################################################################


nodecmdsUsage()
{
	${ECHO}
	${ECHO} "Usage: ${thisScriptName} <command> <subcommand> [args]"
	${ECHO}
	${ECHO} "Commands:"
	${ECHO} " proxymgr      : call etxpmctl with given subcommand and args"
	${ECHO} "                 Type 'nodecmds proxymgr' to see all available subcommands"
	${ECHO}
	${ECHO} " maint         : call nodemaintctl with given subcommand and args"
	${ECHO} "                 Type 'nodecmds maint' to see all available subcommands"
	${ECHO}
	${ECHO} " registernode  : guides you through remote registration process"
	${ECHO}
	${ECHO} " sessions count: provide number of active and suspended sessions"
	${ECHO}
	${ECHO} " sessions stop : stop sessions"
	${ECHO}
	${ECHO} " getnodeinfo   : report node information"
	${ECHO}
	exit 1
}

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
}


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

getETXFeatures()
{
    if [ ! -f ${InstallDir}/bin/etxpmctl ] ; then
	${ECHO} "FATAL ERROR: ${InstallDir}/bin/etxpmctl does not exist.  Cannot retrieve ETX features."
	cd_and_exit 1
    fi
    if [ -z "$etxFeatures" ]; then
		etxFeatures=`${InstallDir}/bin/etxpmctl 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}
}

isWebAdaptorEnabled()
{
	webadaptorenabled=0
	export webadaptorenabled
    eq=`${InstallDir}/bin/etxpmctl cli getconfig -n | ${GREP} "WebAdaptor,1" 2>/dev/null`
	if [ $? -eq 0 ] ; then
		webadaptorenabled=1
	fi
    return $?
}

getWebAdaptorPort()
{
    webport=`${InstallDir}/bin/etxpmctl cli getconfig -n | ${GREP} "WebAdaptorPort," | cut -d, -f 2 2>/dev/null`
	export webport
    return $webport
}

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
}

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
}

getConnectionNodePort()
{
    ListenPort=`${InstallDir}/bin/etxpmctl cli getconfig -n | ${GREP} "ListenPort," | cut -d, -f 2 2>/dev/null`
	result=$?
	export ListenPort
    return $result
}

init()
{
	verbosecommand=0
	thisScriptName="`basename ${0}`"
	getThisPlatform
	find_good_ECHO
	find_good_grep
	find_good_TR
	find_good_printf
	for param in "$@" ; do
		case ${param} in
			proxymgr)
				commandname=runetxpmctl
				break
				;;
			maint)
				commandname=runnodemaintctl
				break
				;;
			sessions)
				commandname=sessions
				continue
				;;
			installcheck|checkinstall)
				commandname=checkinstall
				;;
			getnodeid|getnodeinfo)
				commandname=getNodeId
				;;
			setmigrationid)
				# undocumented install command
				commandname=setmigrationid
				break
				;;
			setmigratedfrom)
				# undocumented install command
				commandname=setmigratedfrom
				break
				;;
			register|registernode)
				commandname=registernode
				break
				;;
			*)
				if [ "${commandname}" = "sessions" ] ; then
					if [ "${param}" = "count" ] ; then
						commandname=sessionCount
						continue
					elif [ "${param}" = "stop" ] ; then
						commandname=sessionStop
						break
					else
						${ECHO} "Invalid argument to sessions."
					fi
				elif [ "${commandname}" = "sessionCount" ] ; then
					if [ "${param}" = "-v" ] ; then
						verbosecommand=1
					fi
					break
				elif [ "${commandname}" = "getNodeId" ] ; then
					if [ "${params}" = "-v" ] ; then
						verbosecommand=1
					fi
					break
				else
					${ECHO} "Invalid command line arguments."
				fi
				nodecmdsUsage
				;;
		esac
	done
	
	thisVersion=
	thisProductName="Exceed TurboX Connection Node"
	getInstallDir
	getETXFeatures
}

getInstallDir()
{
	# resolve links - $0 may be a softlink
	thisPRG="$0"
	
	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
	
	CDir=`pwd`
	thisPrgDirName="`dirname ${thisPRG}`"
	cd "${thisPrgDirName}" > /dev/null 2>&1
	# this script lives in bin folder so InstallDir is our parent
	cd .. > /dev/null 2>&1
	InstallDir=`pwd`
}

# set thisOS,  thisArch values

getThisPlatform()
{
	thisOS=unknown
	thisArch=unknown
	thisUname=`uname`
	thisOptionL="-L"

	osLinux="linux"
	osAix="aix"
	osSolaris="sunos"

	
	hasi86=`uname -a | grep -c -i i386`
	
	if [ ${hasi86} = "0" ] ; then
		hasi86=`uname -a | grep -c -i i686`
	fi
	
	isx86_64=`uname -a | grep -c -i x86_64`
	
	if [ ${hasi86} = "0" ] ; then
		if [ ! ${isx86_64} = "0" ] ; then
			thisArch=x86_64
		fi
	else
		thisArch=i586
	fi
	
	
	case ${thisUname} in
		AIX )
			thisOS=${osAix}
			thisArch=ppc
			;;
		Linux )
			thisOS=${osLinux}
			if [ -d "/etc/init.d" ] ; then
				isSUSE=1
			fi
			;;
		SunOS )
			thisOS=${osSolaris}
			if [ ${hasi86}=0 ] ; then
				thisArch=sparc
				# rm needs -h instead of -L on this platform
				thisOptionL="-h"
			fi
			;;
		HP-UX )
			thisOS=hpux
			thisArch=parisc
			;;
		* )
			;;
	esac
}



countRunningProxies_ImplSunOS()
{
	result=0
	runtimefldr=${1}/runtime/packages
	pslist=`/usr/ucb/ps  -auxwww|grep "${runtimefldr}"|awk '{ print $2 }'`
	for psitem in ${pslist} ; do
		pid=${psitem}
		pathcheck=`/usr/ucb/ps  -auxwww|grep "${runtimefldr}"|grep ${psitem}`
		if [ ! "${pathcheck}x" = "x" ] ; then
			pidpath=`echo ${pathcheck}|awk '{ print $9 }'`
		if [ ${verbosecommand} -gt 0 ] ; then
			${ECHO} "Process ${pid} (pid) running at ${pidpath}"
		fi
			result=`expr ${result} + 1`
		fi
	done
	return ${result}
}

countRunningProxies_Impl()
{
	result=0
	runtimefldr=${1}/runtime/packages
	pidlist=`ps -A|grep etxproxy|awk '{ print $1 }'`
	for psitem in ${pidlist} ; do
		pid=${psitem}
		pathcheck=`ps -p ${pid} -f|grep ${runtimefldr}|grep etxproxy`
		if [ ! "${pathcheck}x" = "x" ] ; then
			pidpath=`echo ${pathcheck}|awk '{ print $8 }'`
			if [ ${verbosecommand} -gt 0 ] ; then
				${ECHO} "Process ${pid} (pid) running at ${pidpath}"
			fi
			result=`expr ${result} + 1`
		fi
	done
	#if [ -e /proc/${pid}/exe ] ; then
	#	pidpath=`readlink /proc/${pid}/exe`
	#fi
	return ${result}
}

checkIfSunOSOldPS()
{
	if [ -x "/usr/ucb/ps" ] ; then
	return 1
	fi
	return 0
}

countRunningProxies()
{
	location=$1
	if [ $2 ] ; then
		silentprint=$2
	else
		silentprint=0
	fi
	if [ "${thisOS}" = "${osSolaris}" ] ; then
		checkIfSunOSOldPS
		if [ $? -gt 0 ] ; then
			countRunningProxies_ImplSunOS  ${location}
		else
			countRunningProxies_Impl ${location}
		fi
	elif [ "${thisOS}" = "${osLinux}" -o "${thisOS}" = "${osAix}" ] ; then
		 countRunningProxies_Impl ${location}
	fi
	retVal=$?
	# if we want silent behaviour then 2nd parameter will be > 0
	if [ ${silentprint} -gt 0 ] ; then
		return ${retVal}
	fi
	if [ ${retVal} -eq 1 ] ; then
		${ECHO} "There is ${retVal} etxproxy session running."
	else
		${ECHO} "There are ${retVal} etxproxy sessions running."
	fi
	return ${retVal}
}

killRunningProxies_Impl()
{
	result=0
	runtimefldr=${1}/runtime/packages
	if [ "${2}" = "" ] ; then
		killflag=-TERM
	else
		killflag=${2}
	fi 
	pidlist=`ps -A|grep etxproxy|awk '{ print $1 }'`
	for psitem in ${pidlist} ; do
		pid=${psitem}
		pathcheck=`ps -p ${pid} -f|grep ${runtimefldr}|grep etxproxy`
		if [ ! "${pathcheck}x" = "x" ] ; then
			pidpath=`echo ${pathcheck}|awk '{ print $8 }'`
			${ECHO} "killing Process ${pid} (pid) running at ${pidpath}"
			kill ${killflag} ${pid}
			result=`expr ${result} + 1`
			killedpidlist="${killedpidlist},${pid}"
		fi
	done
	return ${result}
}

killRunningProxies_ImplSunOS()
{
	result=0
	runtimefldr=${1}/runtime/packages
	if [ "${2}" = "" ] ; then
		killflag=-TERM
	else
		killflag=${2}
	fi 
	pslist=`/usr/ucb/ps  -auxwww|grep "${runtimefldr}"|awk '{ print $2 }'`
	for psitem in ${pslist} ; do
		pid=${psitem}
		pathcheck=`/usr/ucb/ps  -auxwww|grep "${runtimefldr}"|grep ${psitem}`
		if [ ! "${pathcheck}x" = "x" ] ; then
			pidpath=`echo ${pathcheck}|awk '{ print $9 }'`
			${ECHO} "killing Process ${pid} (pid) running at ${pidpath}"
			kill ${killflag} ${pid}
			result=`expr ${result} + 1`
			killedpidlist="${killedpidlist},${pid}"
		fi
	done
	return ${result}
}

killRunningProxies()
{
	killedpidlist=
	location=$1
	if [ ! "$2" = "nice" ] ; then
		killparam=-9
	else
		killparam=
	fi
	if [ "${thisOS}" = "${osSolaris}" ] ; then
		if [ checkIfSunOSOldPS -gt 0 ] ; then
			killRunningProxies_ImplSunOS   $1 ${killparam}
		else
			killRunningProxies_Impl $location ${killparam}
		fi
	 elif [ "${thisOS}" = "${osLinux}" -o "${thisOS}" = "${osAix}" ] ; then
		 killRunningProxies_Impl ${location} ${killparam}
	fi
}

cmd_CountSessions()
{
	countRunningProxies "${InstallDir}"
}

cmd_StopSessions()
{

	attempts=0 
	proxyCount=1
	while [ ${attempts} -lt 5 -a ${proxyCount} -gt 0 ]
	do
		countRunningProxies "${InstallDir}" 1
		proxyCount=$?
		if [ ${proxyCount} -gt 0 ] ; then
			#   first two attemps try to kill sessions using our script
			if [ ${attempts} -lt 2 ] ; then
				${InstallDir}/bin/etxpmctl killsessions
				retval=$?
				if [ ${retval} -gt 0 ] ; then
					${ECHO} "warning during session stop"
				fi
			elif [ ${attempts} -lt 4 ] ; then
				killRunningProxies ${InstallDir} nice
			else
				killRunningProxies ${InstallDir}
			fi
			attempts=`expr ${attempts} + 1`
		fi
	done
	
	# ensure that dbqeue is empty
	${ECHO} "Waiting for this Node's database transactions to complete."
	${InstallDir}/bin/etxpmctl dbqdump  > /dev/null 2>&1

}

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=`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
}

countRunningEtxpm_ImplSunOS()
{
	result=0
	runtimefldr=${1}/bin/sys
	pslist=`/usr/ucb/ps  -auxwww|grep "etxpm"|awk '{ print $2 }'`
	for psitem in ${pslist} ; do
		pid=${psitem}
		pathcheck=`/usr/ucb/ps  -auxwww|grep "${runtimefldr}"|grep ${psitem}`
		if [ ! "${pathcheck}x" = "x" ] ; then
			result=`expr ${result} + 1`
		fi
	done
	return ${result}
}

countRunningEtxpm_Impl()
{
	result=0
	runtimefldr=${1}/bin/sys
	pidlist=`ps -A|grep etxpm|awk '{ print $1 }'`
	for psitem in ${pidlist} ; do
		pid=${psitem}
		pathcheck=`ps -p ${pid} -f|grep ${runtimefldr}/etxpm`
		if [ ! "${pathcheck}x" = "x" ] ; then
			result=`expr ${result} + 1`
		fi
	done
	return ${result}
}

checkIfSunOSOldPS()
{
	if [ -x "/usr/ucb/ps" ] ; then
		return 1
	fi
	return 0
}

countRunningEtxpm()
{
	location=$1
	if [ "${thisOS}" = "${osSolaris}" ] ; then
		checkIfSunOSOldPS
		if [ $? -gt 0 ] ; then
			countRunningEtxpm_ImplSunOS  ${location}
		else
			countRunningEtxpm_Impl ${location}
		fi
	elif [ "${thisOS}" = "${osLinux}" ] ; then
		 countRunningEtxpm_Impl ${location}
	elif [ "${thisOS}" = "${osAix}" ] ; then
		 countRunningEtxpm_Impl ${location}
	fi
	retVal=$?
	return ${retVal}
}

etxcnIsRunning()
{
	countRunningEtxpm "${InstallDir}"
	retVal=$?
	if [ ${retVal} -gt 0 ] ; then
		retVal=0
	else
		retVal=1
	fi
	return ${retVal}
}

cmd_setmigratedfrom()
{
	MigratedFrom=$1
	export MigratedFrom
	# no need to start/stop now
	
	migoldval=`echo "SELECT val from config where key='MigratedFrom';" | ${InstallDir}/bin/etxpmctl -s dbshell 2>/dev/null | grep -v "^WARNING"`
	if [ ! -z "${migoldval}" ] ; then
		echo "UPDATE config set VAL='${MigratedFrom}' where KEY='MigratedFrom';" | ${InstallDir}/bin/etxpmctl -s dbshell > /dev/null
	else
		echo "INSERT into config ( KEY, VAL ) VALUES ('MigratedFrom', '${MigratedFrom}');" | ${InstallDir}/bin/etxpmctl -s dbshell  > /dev/null
	fi
}

cmd_registernode()
{
	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?"
	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"
	
	DONTSTOP=0
	if [ ! etxcnIsRunning ] ; then
		${ECHO} "This node must be running in order to register it"
		return
	fi

	internal_getNodeDetails
	result=$?
	if [ $result -gt 0 ] ; then
		${ECHO} "Error: Node has to be initialized before it can be registered with a site"
		return
	fi

	while [ 1 ]
	do
#		Future: If install will call directly then show this
#		${ECHO}
#		${ECHO} "You can register this node with a site in several ways:"
#		${ECHO}
#		${ECHO} "1. If you are just getting started for the first time, the Install Wizard"
#		${ECHO} "   provides a Register node option on the Authentication page."
#		${ECHO} "2. If your site is already running you can either:"
#		${ECHO} "   a) Access the Server Manager and use the Register node capability;"
#		${ECHO} "   b) Run 'nodecmds maint registernode' command at a later time; or"
#		${ECHO} "   c) You can register node now."
		${ECHO}
		${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
				isWebAdaptorEnabled
				webportenableParam="webportenable:${webadaptorenabled}"
				if [ ${webadaptorenabled} -gt 0 ]; then
				    getWebAdaptorPort
				    webportnumParam="webport:${webport}"
				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_YES}
				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
				###   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
				if [ ${webadaptorenabled} -lt 1 ]; then
				    ${ECHO} Web Adaptor: not enabled
				else
				    ${ECHO} Web Adaptor: enabled
				    ${ECHO} Web Adaptor port: ${webport}
				fi
				if [ 0"${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/nodemaintctl fromnodecmds 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
}

internal_getNodeDetails()
{
		gethostnamefqdn
		ListenPort=
		MigratedFrom=
		if [ -f "${InstallDir}/runtime/etxpm/etxpmdb" ] ; then
			getConnectionNodePort
			MigratedFrom=`echo "SELECT val from config where key='MigratedFrom';" | ${InstallDir}/bin/etxpmctl -s dbshell 2>/dev/null | grep -v "^WARNING"`
			result=0
		else
			result=1
		fi
		export ListenPort
		export MigratedFRom
		return $result
}


cmd_getNodeId()
{
		${ECHO} "Retrieving existing Connection Node information..."
		internal_getNodeDetails
		result=$?
		if [ $result -gt 0 ] ; then
			${ECHO}
			${ECHO} "Error: Node is not initialized."
			exit 2
		fi

		if [ "x${MigratedFrom}" = "x" ] ; then
			MigratedFrom="N/A (no migration performed)"
		fi

		${ECHO}
		${ECHO} Node registration details:
		${ECHO} Host:  ${hostname}
		${ECHO} Port: ${ListenPort}
		if [ ${verbosecommand} -gt 0 ] ; then
			## no longer need more for registration as of 11.0.1
			${ECHO} MigratedFrom: ${MigratedFrom}
		fi
}

runCmd()
{
	# check that our command tools exist before running our commands
	if [ ! -r "${InstallDir}/bin/etxpmctl" -o ! -x "${InstallDir}/bin/etxpmctl" ] ; then
		exit 2
	fi
	if [ ! -r "${InstallDir}/bin/nodemaintctl" -o ! -x "${InstallDir}/bin/nodemaintctl" ] ; then
		exit 2
	fi

	case ${commandname} in
		runetxpmctl)
			shift
			${InstallDir}/bin/etxpmctl $*
			exit $?
			;;
		runnodemaintctl)
			shift
			${InstallDir}/bin/nodemaintctl fromnodecmds $*
			exit $?
			;;
		sessionCount)
			cmd_CountSessions
			;;
		sessionStop)
			cmd_StopSessions
			;;
		getNodeId)
			cmd_getNodeId
			;;
		setmigratedfrom)
			shift
			cmd_setmigratedfrom $*
			;;
		setmigrationid)
			exit 1
			;;
		registernode)
			cmd_registernode
			;;
		checkinstall)
			exit 0
			;;
		*)
			nodecmdsUsage
		;;
	esac
}


init $*
runCmd $*
exit 0
