#!/bin/bash
#
# Copyright (c) 1997-2000 SuSE GmbH Nuernberg, Germany.
#
# Author: Werner Fink, <werner@suse.de>
#
umask 077
#
# Common programs and variables
#
   term="/usr/bin/X11/xterm -ls"
  xauth="/usr/bin/X11/xauth"
    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 [ -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 [ -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 [ -z "${HOSTNAME}" ]; then
    HOSTNAME=`hostname -f`
fi
#
# Set an unique DISPLAY
#
case ${DISPLAY} in
:*) DISPLAY=${HOSTNAME}${DISPLAY}
esac
#
# We need ~/.Xauthority
#
if [ -z "${XAUTHORITY}" ]; then
    XAUTHORITY="${HOME}/.Xauthority"
    [ -e ${XAUTHORITY} ] || touch ${XAUTHORITY}
fi
#
# Do some checks on ~/.Xauthority
#
chksum="no local check"
if [ -x $md5 ]; then
    chksum=`$md5 < ${XAUTHORITY}`
    rmd5="test -x $md5 -a -r ${XAUTHORITY} && \
          $md5 < ${XAUTHORITY} || echo 'no remote check'"
fi
#
# Programs and variables
#
remote_xauth="exec ${xauth} -i merge -"
 local_xauth="${xauth} -i -f ${XAUTHORITY} extract - ${DISPLAY}"
        term="exec ${term} -display ${DISPLAY}"
#
# 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
    rchksum="no remote check"
    xterm="${term} -T ${h} -n ${h} ${iconic} ${redi}"
    [ -x $md5 ] && rchksum=`${rsh} ${opt} ${h} "$rmd5"`
    if [ "$chksum" != "$rchksum" ]; then
	#
	# different local and remote ~/.Xauthority
	# ... export our magic cookie
	# 
	${local_xauth} | ${rsh} ${h} "${remote_xauth}"
    fi
    #
    # Start the remote xterm
    #
    case "$rsh" in
	ssh*) ${rsh} ${opt} -f ${h} "${xterm}"   ;;
	*)    ${rsh} ${opt}    ${h} "${xterm}" & ;;
    esac
done

exit 0
