#!/bin/bash
#
# Copyright (c) 1997-2000 SuSE GmbH Nuernberg, Germany.
#
# Author: Werner Fink, <werner@suse.de>
#
umask 077
#
# Common programs and variables
#
if test -x /usr/bin/X11/xauth ; then
  xauth="/usr/bin/X11/xauth"
else
  xauth="/usr/bin/xauth"
fi
    md5="/usr/bin/md5sum"
    opt=""
case "$XLOGINRSH" in
    "")   rsh="rsh";        opt="-n" ;;
    ssh*) rsh="$XLOGINRSH"; opt="-x" ;;
    *)    rsh="$XLOGINRSH"; opt=""   ;;
esac
   redi="< /dev/null > /dev/null"

#
# Usage
#
usage ()
{
    echo -e "$0: Usage\n  $0 [-iconic] [-s] host [host ...]" 1>&2
    exit 1
}
#
# Parse options
#
while test -n "$1" ; do
    case $1 in
    -i|-iconic) iconic="-iconic"   ; shift ;;
    -s|-secure) rsh="ssh"; opt="-x"; shift ;;
    -*)         usage ;;
    *)          hosts="$hosts $1"  ; shift ;;
    esac
done

#
# Hey ... without local DISPLAY we will not start
#
if test -z "${DISPLAY}" ; then
    echo "No DISPLAY variable" 1>2&
    exit 1
else
    #
    # Strip of some seldom notations
    #
    DISPLAY=${DISPLAY##*/unix}
fi

#
# Where we come from: the local system
#
if test -z "${HOSTNAME}" ; then
    HOSTNAME=$(hostname -f)
fi

#
# Set an unique DISPLAY
#
case ${DISPLAY} in
:*) DISPLAY=${HOSTNAME}${DISPLAY}
esac

#
# We need ~/.Xauthority
#
if test -z "${XAUTHORITY}" ; then
    XAUTHORITY="${HOME}/.Xauthority"
    test -e ${XAUTHORITY} || touch ${XAUTHORITY}
fi
#
# Do some checks on ~/.Xauthority
#
chksum="no local check"
if test -x $md5 ; then
    chksum=$($md5 < ${XAUTHORITY})
    rmd5="test -x $md5 -a -r ${XAUTHORITY} && \
          $md5 < ${XAUTHORITY} || echo 'no remote check'"
fi
#
# Programs and variables
#
local_xauth="${xauth} -i -f ${XAUTHORITY} extract - ${DISPLAY}"

#
# Test on remote system
#
checkpath ()
{
    echo "$(${rsh} ${opt} ${1+"$@"} "test -d /usr/bin/X11/ && echo /usr/bin/X11 || echo /usr/bin")"
}

#
# First check if local and remote ~/.Xauthority are identical
# ... if not we should export our magic cookie.
# And start the xterm
#
for h in $hosts; do

    rpath=$(checkpath $h)
    remote_xauth="exec $rpath/xauth -i merge -"
    term="exec $rpath/xterm -ls -display ${DISPLAY}"

    rchksum="no remote check"
    test -x $md5 && rchksum=$(${rsh} ${opt} ${h} "$rmd5")
    if test "$chksum" != "$rchksum" ; then
	#
	# different local and remote ~/.Xauthority
	# ... export our magic cookie
	# 
	${local_xauth} | ${rsh} ${h} "${remote_xauth}"
    else
	case "$rsh" in
	    ssh*) opt="-q"
	esac
    fi
    xterm="${term} -T ${h} -n ${h} ${iconic} ${redi}"
    #
    # Start the remote xterm
    #
    case "$rsh" in
	ssh*) ${rsh} ${opt} -f ${h} "${xterm}" &> /dev/null  ;;
	*)    ${rsh} ${opt}    ${h} "${xterm}" & ;;
    esac
done

exit 0
