#! /bin/ksh

#
# Name		: ${HOME}/bin/RemoteXterm.ksh
#
# Version	: 1.0
#
# Author	: Gerard van Wageningen
#
# Description	: Start xterm locally or remote (/usr/bin/X11/xterm hard coded)
#
# 1.0	First version
#

function Die
{
  print -u2 "\n$@\n"
  exit 1
}

function saveMethod
{
  # Save the method of connecting to $1
  [[ -n "${DEBUG:-}" ]] && set -x

  touch "${HOME}/.${progName}"
  grep -v "^${1} " < "${HOME}/.${progName}" > "${HOME}/.${progName}.$$"
  print "${1} ${2}" >> "${HOME}/.${progName}.$$"
  mv "${HOME}/.${progName}.$$" "${HOME}/.${progName}"

  return
} # function saveMethod

alias die='Die "(${progName},${LINENO})" '

typeset tmpFile result targetHost targetUser progName

\whence set_debug 1> /dev/null 2>&1 && eval $( set_debug ${0##*/} )

if \whence -p XOpenDisplay 1>/dev/null 2>&1
then
  XOpenDisplay -d ${DISPLAY} \
  || die "DISPLAY: ${DISPLAY} not reachable"
fi

(( $# == 1 )) || die "Usage: remoteXterm [<targetUser>@]<targetHost>."

progName="${0##*/}"

targetHost="${1#*@}"
[[ -n "${targetHost}" ]] || die 'No remote host found.'
targetUser="${1%@*}"
[[ -z "${targetUser}" || "${targetUser}" = "${targetHost}" ]] \
&& targetUser="${LOGNAME:-${USER}}"

if [[ "${targetHost}" = "${HOSTNAME}" && "${targetUser}" = "${LOGNAME:-${USER}}" ]]
then
  nohup /usr/bin/X11/xterm -vb -display ${DISPLAY} -title \"$@\" -fn 6x13 -sb -ls -geometry 132x24 0</dev/null 1>/dev/null 2>&1 &
  saveMethod "${targetUser}@${targetHost}" 'localXterm'
  exit 0
fi

ping -c 1 "${targetHost}" 1>/dev/null 2>&1 || die "Could not ping ${targetHost}" 

tmpFile=$( mkstemp /tmp/${HOSTNAME}_XXXXXX 2>&1 ) \
|| die "Error in mkstemp call (${tmpFile})"

result=$( \scp -B ${tmpFile} ${1}:${tmpFile}_scp 2>&1 )
if (( $? == 0 ))
then
  # ssh works, now check is X11 forwarding is enabled!
  rm -f "${tmpFile}"
  result=$( \ssh -X -f "$1" "rm ${tmpFile}_scp; /usr/bin/X11/xterm -vb -title \"$@\" -fn 6x13 -sb -ls -geometry 132x24" 2>&1 )
  case "${result}" in
    *denied\ X11\ forwarding*) ;;
    */usr/bin/X11/xterm:\ Command\ not\ found.) ;;
    *)
      saveMethod "${targetUser}@${targetHost}" 'sshXterm'
      exit 0
      ;;
  esac
fi

result=$( rcp ${tmpFile} ${1}:${tmpFile}_rcp 2>&1 )
if (( $? == 0 ))
then
  # rsh works!
  rm -f "${tmpFile}"
  case ${DISPLAY:-'unix:0.0'} in
    unix:0.0|:0.0) export DISPLAY="${HOSTNAME:-$( uname -n )}:0.0" ;;
    *) ;;
  esac

  rsh "${targetHost}" -l "${targetUser}" "rm ${tmpFile}_rcp; nohup /usr/bin/X11/xterm -vb -display ${DISPLAY} -title \"$@\" -fn 6x13 -sb -ls -geometry 132x24 1>/dev/null 2>&1 & sleep 1"
  saveMethod "${targetUser}@${targetHost}" 'rshXterm'
  exit 0
fi

rm -f "${tmpFile}"
nohup /usr/bin/X11/xterm -vb -title \"$@\" -fn 6x13 -sb -ls -geometry 132x24 -e \ssh "$1" 1>/dev/null 2>&1 &
saveMethod "${targetUser}@${targetHost}" 'xtermRsh'

exit 0  

############# EOF #############
