#!/bin/bash

########################################################################
#
#PROJECT:      Unified Sessions Manager
#AUTHOR:       Arno-Can Uestuensoez - acue@UnifiedSessionsManager.org
#MAINTAINER:   Arno-Can Uestuensoez - acue_sf1@sourceforge.net
#SHORT:        ctys
#CALLFULLNAME: Commutate To Your Session
#LICENCE:      GPL3
#VERSION:      01_02_007a17
#
########################################################################
#
# Copyright (C) 2007 Arno-Can Uestuensoez (UnifiedSessionsManager.org)
#
########################################################################

_myPKGNAME_XEN_CREATE="${BASH_SOURCE}"
_myPKGVERS_XEN_CREATE="01.01.001a00"
hookInfoAdd $_myPKGNAME_XEN_CREATE $_myPKGVERS_XEN_CREATE
_myPKGBASE_XEN_CREATE="`dirname ${_myPKGNAME_XEN_CREATE}`"


#FUNCBEG###############################################################
#NAME:
#  createConnectXEN
#
#TYPE:
#  bash-function
#
#DESCRIPTION:
#  Creates a session and/or connects to the server.
#  
#
#EXAMPLE:
#
#PARAMETERS:
#
#
#OUTPUT:
#  RETURN:
#
#  VALUES:
#
#FUNCEND###############################################################
function createConnectXEN () {
  local OPMODE=$1;shift
  local ACTION=$1;shift
  local cache=1;
  local poll=1;
  local _consoleType=VNC;

  case ${OPMODE} in
      CHECKPARAM)
          #
          #Just check syntax drafts, the expansion of labels etc. could just be
          #expanded on target machine.
          #

          if [ -n "$CTRL_MODE_ARGS" ];then
              A=`echo ${CTRL_MODE_ARGS}|sed 's/,/ /g'`
              printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "XEN($A)"

              #guarantee unambiguity of EXOR: (label|l)  (fname|f)  (pname|p)
              local _unambig=0;
              local _unambigCON=0;
              for i in $A;do
		  KEY=`echo ${i}|awk -F':' '{print $1}'|tr '[:lower:]' '[:upper:]'`
		  ARG=`echo ${i}|awk -F':' '{print $2}'`

		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "KEY=${KEY}"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "ARG=${ARG}"
                  #handle keywords
                  if [ -n "${ARG}" \
                      -o -z "${ARG}" -a "${KEY}" == "REUSE" \
		      -o -z "${ARG}" -a "${KEY}" == "RECONNECT" \
		      -o -z "${ARG}" -a "${KEY}" == "CONNECT" \
		      -o -z "${ARG}" -a "${KEY}" == "RESUME" \
		      -o -z "${ARG}" -a "${KEY}" == "NOCACHE" \
		      -o -z "${ARG}" -a "${KEY}" == "NOPOLL" \
                      ];then
		      case $KEY in

			  CONNECT)
			      let _unambigCON+=1;
                              local _reuse=1;
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "CONNECT"
			      ;;

			  REUSE)
			      let _unambigCON+=1;
                              local _reuse=1;
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "REUSE="
			      ;;

			  RECONNECT)
                              local _reuse=1;
                              local _reconnect=1;
			      let _unambigCON+=1;
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "RECONNECT"
			      ;;


			  RESUME)
                              local _resume=1;
			      let _unambigCON+=1;
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "RESUME"
			      ;;


                     #####################
                     # <machine-address> #
                     #####################
			  NOCACHE)
                              local _cache=0;
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "NOCACHE"
			      ;;
			  NOPOLL)
			      local _poll=0;
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "NOPOLL"
			      ;;


			  BASEPATH|BASE|B)
                              local _base="${ARG}";
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "BASE=${_base}"
			      ;;
			  TCP|T)
			      local _tcp="${ARG}";
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "TCP=${_tcp}"
			      let _unambig+=1;
			      ;;
			  MAC|M)
			      local _mac="${ARG}";
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "MAC=${_mac}"
			      let _unambig+=1;
			      ;;
			  UUID|U)
                              local _uuid="${ARG}";
 			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "UUID=${_uuid}"
			      let _unambig+=1;
			      ;;
			  LABEL|L)
                              local _label="${ARG}";
 			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "LABEL=${_label}"
			      let _unambig+=1;
			      ;;
			  FILENAME|FNAME|F)
                              local _fname="${ARG}";
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "FILENAME=${_fname}"
			      let _unambig++;
			      ;;
			  ID|I|PATHNAME|PNAME|P)
                              if [ -n "${ARG##/*}" ]; then
				  ABORT=1;
				  printERR $LINENO $BASH_SOURCE ${ABORT} "PNAME has to be an absolute path, use fname else."
				  printERR $LINENO $BASH_SOURCE ${ABORT} " PNAME=${ARG}"
 				  gotoHell ${ABORT}
                              fi
                              local _idgiven=1;
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "PATHNAME=${ARG}"
			      ;;


                     #######################
                     # Specific attributes #  
                     #######################
			  CALLOPTS|C)
                              local _callopts="${ARG//\%/ }";
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "CALLOPTS=${_callopts}"
			      ;;
			  XOPTS|X)
                              local _xopts="${ARG//\%/ }";
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "XTOOLKITOPTS=${_xopts}"
			      ;;


                        ###########
			  CONSOLE)
			      local _conty="`echo ${ARG}|tr '[:lower:]' '[:upper:]'`";
			      case ${_conty} in
				  CLI)
				      CTRL_ASYNC=0
				      if [ "${CTRL_CLIENTLOCATION}" ==  "-L ConnectionForwarding" ];then
					  ABORT=1;
					  printERR $LINENO $BASH_SOURCE ${ABORT} "\"ConnectionForwarding\" is not supported for ${_conty}"
 					  gotoHell ${ABORT}
				      fi

				      ;;

				  XTERM|GTERM)
				      if [ "${CTRL_CLIENTLOCATION}" ==  "-L ConnectionForwarding" ];then
					  ABORT=1;
					  printERR $LINENO $BASH_SOURCE ${ABORT} "\"ConnectionForwarding\" is not supported for ${_conty}"
 					  gotoHell ${ABORT}
				      fi
				      if [ "${CTRL_ASYNC}" == 0 ];then
					  ABORT=1;
					  printWNG $LINENO $BASH_SOURCE ${ABORT} "for ${_conty} the use of option \"-b 1\" is recommended"
				      fi
				      ;;

				  VNC)
				      ;;

				  *)
				      ABORT=1;
				      printERR $LINENO $BASH_SOURCE ${ABORT} "UNKNOWN ARG=${ARG}"
 				      gotoHell ${ABORT}
				      ;;				  
			      esac
			      if [ -n "${_console}" ];then
				  ABORT=1;
				  printERR $LINENO $BASH_SOURCE ${ABORT} "CONSOLE has to be unique."
 				  gotoHell ${ABORT}
			      fi
			      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "CONSOLE=${ARG}"
			      local _console=$_conty;
			      ;;

			  *)
			      ABORT=1;
			      printERR $LINENO $BASH_SOURCE ${ABORT} "Unknown sub-opts for XEN:${KEY}"
 			      gotoHell ${ABORT}
			      ;;
		      esac
                  else
		      ABORT=1;
		      printERR $LINENO $BASH_SOURCE ${ABORT} "Erroneous KEY:<${KEY}>"
 		      printERR $LINENO $BASH_SOURCE ${ABORT} "  Required syntax :<KEY>:<ARG>";
 		      printERR $LINENO $BASH_SOURCE ${ABORT} "  Given systax    :<${KEY}>:<${ARG}>";
 		      gotoHell ${ABORT}               
		  fi
	      done


              #
              #handle remote options for actual execution...
              #
              #...trust the correctness, or better the checks of actual final tool,
              #these options are destined for, thus nothing to do her.
              #

              #0. validate ambiguity
              if [ "${_unambig}" -gt 1 ];then
		  ABORT=1;
		  printERR $LINENO $BASH_SOURCE ${ABORT} "ambiguous sub-opts have to be EXOR"
 		  gotoHell ${ABORT}
              fi

              #1. validate ambiguity
              if [ "${_unambigCON}" -gt 1 ];then
		  ABORT=1;
		  printERR $LINENO $BASH_SOURCE ${ABORT} "The following sub-opts are EXOR applicable only:"
		  printERR $LINENO $BASH_SOURCE ${ABORT} "  (CONNECT|JOIN|REUSE) EXOR (RECONNECT|REPLACE)"
 		  gotoHell ${ABORT}
              fi

              #2. validate data source
              if((cache==0 && poll==0));then
		  ABORT=1;
		  printERR $LINENO $BASH_SOURCE ${ABORT} "All data sources are excluded by NOCACHE and NOPOLL???"
 		  gotoHell ${ABORT}
              fi
          fi

          #3. Least required parameters
          if((_unambig!=1&&_idgiven!=1));then
	      ABORT=1;
	      printERR $LINENO $BASH_SOURCE ${ABORT} "Missing parameter for target entity of action"
 	      gotoHell ${ABORT}
          fi
	  ;;


      ACTION)
	  if [ -n "${R_TEXT}" ];then
	      echo "${R_TEXT}"
	  fi
	  if [ -z "${CTRL_EXECLOCAL}" ];then
	      assembleExeccall
	  else
              #
              #Doing local semantical correctness evaluation now.
              #
              if [ -n "$CTRL_MODE_ARGS" ];then
		  A=`echo ${CTRL_MODE_ARGS}|sed 's/,/ /g'`
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "XEN($A)"

                  #guarantee unambiguity of EXOR: (label|l)  (fname|f)  (pname|p)
		  local _unambig=0;
		  for i in $A;do
		      KEY=`echo ${i}|awk -F':' '{print $1}'|tr '[:lower:]' '[:upper:]'`
		      ARG=`echo ${i}|awk -F':' '{print $2}'`

		      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "KEY=${KEY}";
		      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "ARG=${ARG}";
                      #handle keywords
                      if [ -n "${ARG}" \
			  -o -z "${ARG}" -a "${KEY}" == "REUSE" \
			  -o -z "${ARG}" -a "${KEY}" == "RECONNECT" \
  			  -o -z "${ARG}" -a "${KEY}" == "CONNECT" \
			  -o -z "${ARG}" -a "${KEY}" == "RESUME" \
			  -o -z "${ARG}" -a "${KEY}" == "NOCACHE" \
			  -o -z "${ARG}" -a "${KEY}" == "NOPOLL" \
			  ];then
			  case $KEY in

 			      CONNECT)
                                  local _reuse=1;
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "REUSE=>try CONNECT before CREATE"
				  ;;

 			      REUSE)
                                  local _reuse=1;
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "REUSE=>try CONNECT before CREATE"
				  ;;

			      RECONNECT)
                                  local _reuse=1;
                                  local _reconnect=1;
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "RECONNECT=>CANCEL running clients first"
				  ;;

			      RESUME)
				  local _resume=1;
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "RESUME"
				  ;;


                     #####################
                     # <machine-address> #
                     #####################
			      NOCACHE)
				  local _cache=0;
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "NOCACHE"
				  ;;
			      NOPOLL)
				  local _poll=0;
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "NOPOLL"
				  ;;


			      BASEPATH|BASE|B)
                                  #can be checked now
                                  local _base="${ARG}";
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "BASE=${_base}"
                                  for i in ${_base//\%/ };do
                                      if [ ! -d "${i}" ];then
					  ABORT=1;
					  printERR $LINENO $BASH_SOURCE ${ABORT} "Missing given base-path";
					  printERR $LINENO $BASH_SOURCE ${ABORT} "  i  = ${i}";
					  printERR $LINENO $BASH_SOURCE ${ABORT} "  PWD= ${PWD}";
					  printERR $LINENO $BASH_SOURCE ${ABORT} "Check your actual PWD when providing a relative base-path";
 					  gotoHell ${ABORT};
                                      fi
				  done
				  ;;

			      TCP|T)
				  local _tcp="${ARG}";
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "TCP=${_tcp}"
				  ;;
			      MAC|M)
				  local _mac="${ARG}";
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "MAC=${_mac}"
				  ;;
			      UUID|U)
                                  #has to be checked later
				  local _uuid="${ARG}";
 				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "UUID=${_uuid}"
				  ;;

			      LABEL|L)
                                  #has to be checked later due to probable following base-prefix
                                  local _label="${ARG}";
 				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "LABEL=${_label}"
				  ;;
			      FILENAME|FNAME|F)
                                  #has to be checked later due to probable following base-prefix
                                  local _fname="${ARG}";
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "FILENAME=${_fname}"
				  ;;
			      ID|PATHNAME|PNAME|P)
                                  #can be checked now, no additional combination check required 
                                  #due to previous CHECKPARAM.
                                  if [ -n "${_pname}" ];then
				      ABORT=1;
				      printERR $LINENO $BASH_SOURCE ${ABORT} "This version supports just ONE ${KEY} for each ${ACTION}  call"
				      printERR $LINENO $BASH_SOURCE ${ABORT} "  ID(1)=${_pname}"
				      printERR $LINENO $BASH_SOURCE ${ABORT} "  ID(2)=${ARG}"
				      printERR $LINENO $BASH_SOURCE ${ABORT} "Will be extended soon."
 				      gotoHell ${ABORT}
                                  fi
                                  if [ ! -f "${ARG}" ];then
				      ABORT=1;
				      printERR $LINENO $BASH_SOURCE ${ABORT} "Missing given file or access permission for ID/PNAME"
				      printERR $LINENO $BASH_SOURCE ${ABORT} "  ID=${ARG}"
 				      gotoHell ${ABORT}
                                  fi
                                  local _pname="${_pname:+$_pname|}${ARG}";
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "PATHNAME=${_pname}"
				  ;;


			      CALLOPTS|C)
                                  #trust the user for now, and let the target call check it
				  local _callopts="${ARG//\%/ }";
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "CALLOPTS=${_callopts}"
                                  CTRL_SESSIONIDARGS="${_callopts}"
				  ;;
			      XOPTS|X)
                                  #trust the user for now, and let the target call check it
				  local _xopts="${ARG//\%/ }";
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "XTOOLKITOPTS=${_xopts}"
                                  CTRL_XTOOLKITOPTS="${_xopts}"
				  ;;

			      CONSOLE)
				  local _conty="`echo ${ARG}|tr '[:lower:]' '[:upper:]'`";
				  case  ${_conty} in
				      CLI|XTERM|GTERM)
					  _consoleType=${_conty};
					  ;;
				      VNC)_consoleType=${_conty};;
				      *)
					  ABORT=1;
					  printERR $LINENO $BASH_SOURCE ${ABORT} "UNKNOWN ARG=${ARG}"
 					  gotoHell ${ABORT}
					  ;;
				  esac
				  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "CONSOLE=${ARG}"
				  local _console=1;
				  ;;

			      *)
				  ABORT=1;
				  printERR $LINENO $BASH_SOURCE ${ABORT} "Unexpected sub-opts for XEN:${KEY}"
 				  gotoHell ${ABORT}
				  ;;
			  esac
		      fi
		  done
	  case "${_conty}" in
	      CLI|XTERM|GTERM)
		  if [ "${CTRL_CLIENTLOCATION//ConnectionForwarding}" != "${CTRL_CLIENTLOCATION}" ];then
		      ABORT=1;
		      printERR $LINENO $BASH_SOURCE ${ABORT} "\"ConnectionForwarding\" is not supported for ${_conty}"
 		      gotoHell ${ABORT}
		  fi
		  ;;
	  esac

                  #shortcut for pass-through
 		  local _dbg1=${CTRL_VERBOSE:+ -d $CTRL_VERBOSE}

                  #pathname for configuration file has to be  evaluated
                  if [ -z "${_pname}" ];then
		      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "Missing, try to get:_pname=${_pname}"

                      #search cache first
		      if((__nocache==0));then
			  _matchKey="${_pname} ${_base} ${_tcp} ${_mac} ${_uuid} ${_label} ${_fname}"

			  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "Use cache by ctys-vhost:_matchKey=${_matchKey}"
                          #try ctys-vhost with it's cache first
                          #OF COURSE - MUST NOT be disguiding from reality, but could be empty.
                          #
			  local _VHOST="${MYCALLPATH}/ctys-vhost $_dbg1 -C MACMAP -o IDS -p ${DBPATHLST} "

                          #we match as much as given, that's for unambiguity, for now 
                          # 1. ignore ambiguous input, just take first
                          # 2. mismatch, due to database err-content or excluding parameters, just try poll than.
			  _pname=`${_VHOST} ${_matchKey}`
			  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "Cache-Result:_pname=${_pname}"
		      fi

                      #if no match - only than - and poll is enabled, try it.
                      if [ -z "${_pname}" -a ${_nopoll} -eq 0 ];then
                          #pathname still not availbale and poll is still released for application.
			  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "Use poll ENUMERATE"

			  if [ -n "${_uuid}" ];then
                                #UUID to be "grepped" from vmx-files
			      _pname=`enumerateMySessionsVMW MACHINE,TERSE,${_base}|awk -F';' -v d="${_uuid}" '
                                      BEGIN{firstX="";};$4~d{if(!firstX)firstX=$4;};END{print firstX}'`
			      printVerboseDebug ${DBG_LVL_MAINT} $LINENO $BASH_SOURCE "_pname=${_pname}"
			  else
			      if [ -n "${_label}" ];then
                                    #displayName to be "grepped" from vmx-files
		 		  _pname=`enumerateMySessionsVMW MACHINE,TERSE,${_base}|awk -F';' -v d="${_label}" '
                                          BEGIN{firstX="";};$2~d{if(!firstX)firstX=$4;};END{print firstX}'`
				  printVerboseDebug ${DBG_LVL_MAINT} $LINENO $BASH_SOURCE "_pname=${_pname}"
			      else
				  if [ -n "${_tcp}" ];then
                                        #displayName to be "grepped" from vmx-files
				      _pname=`enumerateMySessionsVMW MACHINE,TERSE,${_base}|awk -F';' -v d="${_tcp}" '
                                              BEGIN{firstX="";};$6~d{if(!firstX)firstX=$4;};END{print firstX}'`
				      printVerboseDebug ${DBG_LVL_MAINT} $LINENO $BASH_SOURCE "_pname=${_pname}"
				  else
	 			      if [ -n "${_mac}" ];then
                                            #displayName to be "grepped" from vmx-files
					  _pname=`enumerateMySessionsVMW MACHINE,TERSE,${_base}|awk -F';' -v d="${_mac}" '
                                                  BEGIN{firstX="";};$5~d{if(!firstX)firstX=$4;};END{print firstX}'`
					  printVerboseDebug ${DBG_LVL_MAINT} $LINENO $BASH_SOURCE "_pname=${_pname}"

				      else
                                            #has to be a relative vmx-file name, the absolute path has to be found
					  _pname=`enumerateMySessionsVMW MACHINE,TERSE,${_base}|awk -F';' -v d="${_fname}" '
                                                  BEGIN{firstX="";};$3~d{if(!firstX)firstX=$4;};END{print firstX}'`
					  _label=${_pname//:*}
					  _pname=${_pname//*:}
					  printVerboseDebug ${DBG_LVL_MAINT} $LINENO $BASH_SOURCE "_pname=${_pname}"
				      fi
				  fi
			      fi
			  fi
		      fi
		  fi


                  #should have find one
                  if [ -z "${_pname}" ];then
		      ABORT=1;
		      printERR $LINENO $BASH_SOURCE ${ABORT} "Missing a valid identifier, transformation may have failed."
		      printERR $LINENO $BASH_SOURCE ${ABORT} "  BASE    =${_base}"
		      printERR $LINENO $BASH_SOURCE ${ABORT} "  PNAME   =${_pname}"
 		      printERR $LINENO $BASH_SOURCE ${ABORT} "  TCP     =${_tcp}"
		      printERR $LINENO $BASH_SOURCE ${ABORT} "  MAC     =${_mac}"
		      printERR $LINENO $BASH_SOURCE ${ABORT} "  UUID    =${_uuid}"
		      printERR $LINENO $BASH_SOURCE ${ABORT} "  LABEL   =${_label}"
		      printERR $LINENO $BASH_SOURCE ${ABORT} "  FNAME   =${_fname}"
		      printERR $LINENO $BASH_SOURCE ${ABORT} "Data source:"
		      printERR $LINENO $BASH_SOURCE ${ABORT} "  NOCACHE =${_nocache}"
		      printERR $LINENO $BASH_SOURCE ${ABORT} "  NOPOLL  =${_nopoll}"
 		      gotoHell ${ABORT}
		  fi


                  #####
                  #do some validation and postprocessing
                  #####

                  #Make it absolute, if not yet.
                  #If relative, it could just result from a "find $HOME ..."
                  if [ -n "${_pname##/*}" ]; then
		      _pname=${HOME}/${_pname}
		  fi

                  local _labelX=`getLABEL_XEN "${_pname}"`
                  #LABEL=DOMAIN-NAME
                  if [ -z "${_label}" -a -z "${_labelX}" ];then
		      ABORT=1;
		      printERR $LINENO $BASH_SOURCE ${ABORT} "Missing LABEL, which is the mandatory DomainName for Xen."
		      printERR $LINENO $BASH_SOURCE ${ABORT} "Defined as user defined pre-requisite for Xen."
 		      gotoHell ${ABORT}
                  fi 

                  #consistency of CLI and config
                  if [ -n "${_label}" -a "${_label}" == "${_labelX}"  ];then
		      ABORT=1;
		      printERR $LINENO $BASH_SOURCE ${ABORT} "Different LABELs detected:\"${_label}\" == \"${_labelX}\""
 		      gotoHell ${ABORT}
                  fi 
                  _label="${_labelX}"


                  #consistency of CLI and config
                  local _tcpX=`getIP "${_pname}"`
                  if [ -n "${_tcp}" -a "${_tcp}" == "${_tcpX}"  ];then
		      ABORT=1;
		      printERR $LINENO $BASH_SOURCE ${ABORT} "Different TCPs detected:\"${_tcp}\" == \"${_tcpX}\""
 		      gotoHell ${ABORT}
                  fi 
                  _tcp="${_tcpX}"

                  #consistency of CLI and config
                  local _macX=`getMAC_XEN "${_pname}"`
                  if [ -n "${_mac}" -a "${_mac}" == "${_macX}"  ];then
		      ABORT=1;
		      printERR $LINENO $BASH_SOURCE ${ABORT} "Different MACs detected:\"${_mac}\" == \"${_macX}\""
 		      gotoHell ${ABORT}
                  fi 
                  _mac="${_macX}"

                  #consistency of CLI and config
                  local _uuidX=`getUUID_XEN "${_pname}"`
                  if [ -n "${_uuid}" -a "${_uuid}" == "${_uuidX}"  ];then
		      ABORT=1;
		      printERR $LINENO $BASH_SOURCE ${ABORT} "Different UUIDs detected:\"${_uuid}\" == \"${_uuidX}\""
 		      gotoHell ${ABORT}
                  fi 
                  _uuid="${_uuidX}"


                  #####
                  #So, essential IDs are unambiguous now!
                  #####

                  #I guess we have a valid _pname and a _label now.
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "Current ident-data:"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  BASE     =${_base}"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  PNAME    =${_pname}"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  TCP      =${_tcp}"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  MAC      =${_mac}"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  UUID     =${_uuid}"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  LABEL    =${_label}"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  FNAME    =${_fname}"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "Console:"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  TYPE     =${_consoleType}"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "Data source:"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  NOCACHE  =${_nocache}"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  NOPOLL   =${_nopoll}"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "Parameters:"
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  CALLOPTS =\"${_callopts}\""
		  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE  "  XOPTS    =\"${_xopts}\""



          ###########################
           #    So, ... let's go!    #
          ###########################


                  #check whether a mediating wormhole is required. 
                  #In any case find the entry for peer.
		  if [ "${CTRL_CLIENTLOCATION}" !=  "-L ConnectionForwarding" \
                      -a "${CTRL_CLIENTLOCATION}" !=  "-L LocalOnly" \
 		      ];then

                      #Seems to be executed on remote host, not the calling station
		      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "CTRL_CLIENTLOCATION=${CTRL_CLIENTLOCATION}"

                      #check for running local server...
                      #...remember, this part is actually running local-on-remote site!
 		      local _IDx=`fetchID4Label ${_label}`
                      _pname=${_pname:-$_IDx}
                  else
                      #Is executed on the calling station
                      #so is to be executed completely locally or a local client to be tunneled.
                      #
		      printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "CTRL_CLIENTLOCATION=${CTRL_CLIENTLOCATION}"

                      #find local entry for SSH-tunnel with generic LABEL as marker for proxying to remote server.
		      local _IDx=`digGetLocalPort ${_label}`
                      _pname=${_pname:-`fetchID4Label ${_label}`}

		  fi
		  printVerboseDebug ${DBG_LVL_MAINT} $LINENO $BASH_SOURCE " Session-Identifier: ${_label} ->${_IDx}"



                  #check whether server is already running(local or remote)
                  #therefore a peer must be present
		  if [ -n "${_IDx}" ];then
                      #Server is already running, so it is a potential CONNECT.

                      #perform only if REUSE is present
                      #so practically this could only be LocalOnly or DisplayForwarding,
                      #ConnectionForwarding is normally impossible, due to timeout of connection(One-Shot-Mode)
		      if [ -n "${_reuse}" ];then
                          #only something to do when anything else than the server is running
                          #server is defined not to be reused
			  if [ "${CTRL_CLIENTLOCATION}" !=  "-L ServerOnly" ];then
                              #if to be reused
			      printVerboseDebug ${DBG_LVL_MAINT} $LINENO $BASH_SOURCE "REUSE: \"${_pname}\" \"${_label}\" \"${_IDx}\""

                              #check now for reconnect, if so kill whole competition
                              if [ -n "${_reconnect}" ];then
                                  #So it is all to be killed: ID might be available here.


				  _history=`${MYCALLPATH}/ctys -T CLI,X11,VNC -a list=CLIENT,FULLPATH,TERSE,LABEL,ID,PID,SITE \
                                                     -b 0 $_dbg1 ${_dbg1:+"-- ($_dbg1)"}|\
                                              awk -F';' -v l="${_label}" '$1~l{print $0 }'`

                                  #kill clients, guess the caller knows what he is doing, particularly
                                  #has assured a stateless server!!!
  				  printVerboseDebug ${DBG_LVL_MAINT} $LINENO $BASH_SOURCE "MODE=RECONNECT($_history)"
				  for _i in ${_history};do
				      [ "${_i##*;}" != CLIENT ]&&continue; #OK, not really required, but for safety
				      printVerboseDebug ${DBG_LVL_MAINT} $LINENO $BASH_SOURCE "kill:${_i}"
				      local _pid=${_i%;*}
				      _pid=${_pid##*;}
				      echo -n "Session:\"${_i%%;*}\":PID=$_pid"
				      kill $_pid
				      echo
				  done
                              fi

                              #trust for now - any garbage is removed
#			      local _myDisp=`fetchDisplay4Label ${_label}`
			      local _myDisp=`fetchCport4Label ${_label}`
			      connectSessionXEN "${_consoleType}" "${_label}" "${_pname}" "${_myDisp}" 
			  fi
                      else
			  printVerboseDebug ${DBG_LVL_MAINT} $LINENO $BASH_SOURCE "Session already exists ID=${_IDx} - LABEL=${_label}"
			  ABORT=1
			  printERR $LINENO $BASH_SOURCE ${ABORT} "Session already exists ID=${_IDx} - LABEL=${_label}"
			  printERR $LINENO $BASH_SOURCE ${ABORT} "  Choose \"REUSE\" if you want connect-only when existing"
			  gotoHell ${ABORT}
		      fi

		  else
                      #Server not yet running, so it is a CREATE, or a remote connection has to be established,
                      #which must be a server-split of an ConnectionForwarding.
		      if [ "${CTRL_CLIENTLOCATION}" !=  "-L ConnectionForwarding" ];then
                          #
                          #So, this is executed on server site, it is a DisplayForwarding
                          #
 			  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "CTRL_CLIENTLOCATION=${CTRL_CLIENTLOCATION}"
			  startSessionXEN "${_label}" "${_pname}" "${_consoleType}"
		      else
                          #
                          #So, this is executed on the client site, different from server site,
                          #it is ConnectionForwarding to a remote server.
                          #So, dig the tunnel and connect myself.
                          #
 			  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "CTRL_CLIENTLOCATION=${CTRL_CLIENTLOCATION}"
                          echo -n "remote cport="
                          digLocalPort XEN $R_HOSTS $_label $_pname

                          #check it once again
 			  local _lport=`digGetLocalPort ${_label}`
                          if [ -z "$_lport" ];then
                              #Something went wrong!!!???                                      
			      ABORT=1
			      printERR $LINENO $BASH_SOURCE ${ABORT} "Cannot allocate ConnectionForwarding"
			      printERR $LINENO $BASH_SOURCE ${ABORT} "  digLocalPort <XEN> <$RHOSTS> <$i>"
			      gotoHell ${ABORT}
			  fi

 			  printVerboseDebug ${DBG_LVL_UID} $LINENO $BASH_SOURCE "_lport=${_lport} i=${i}"
			  connectSessionXEN "${_consoleType}" "${_label}" "${_pname}" "${_lport}"  
		      fi
		  fi
		  gotoHell 0
	      fi
	  fi
	  ;;
  esac

}

