#! /bin/sh
# getdisplay
# Author: Noah Friedman <friedman@splode.com>
# Created: 1992-01-17
# Public domain

# $Id: getdisplay,v 1.2 1999/10/10 02:35:24 friedman Exp $

# Commentary:

# This script tries to figure out where we are connecting from, which is
# useful if we're in X-windows and our DISPLAY environment variable is
# unset because we've connected remotely to another machine.

# Instead of rlogging in to a machine, it's better (if possible) to use
# the "xon" shell script to run processes (including xterm) on that host,
# or to use X11 forwarding with ssh.

# Code:

# First try to get the remote host from SSH agent information.
# This variable only points to the most immediate remote host.
# If you perform multiple hops, you will not correctly identify the
# original display.  Better to use ssh X11 forwarding.
case "${SSH_CLIENT+set}" in
  set )
    set fnord $SSH_CLIENT
    shift
    # Try to get a name for the address if we can.
    name=`(perl -e '$addr = pack ("C4", split (/\./o, "'"$1"'"));
                    printf ("%s\n", gethostbyaddr($addr, 2));') 2> /dev/null`
    case "$name" in
      '' ) echo "$1:0.0" ;;
      *  ) echo "$name:0.0" ;;
    esac
    exit 0
   ;;
esac

# Try using the information in utmp.  This is unreliable.

# Strip out `/dev/' and quote any remaining `/' characters with a backslash
# so that we can use it in an expression to later on without the `/'
# characters confusing sed.
# sh does escaping in backquote substitutions in a funny way.  Later shells
# having the $() construct are less confusing, but we're sticking to sh here.
tty=`tty | sed -e 's/\/dev\///;s/\//\\\\\//g;'`

# Don't use `who am i' ... it seems to have a weird format on some
# machines.  The hairy regexp extracts the remote host from the `(...)'
# field of who, removing any "user@" prefix (which seems to be a symptom of
# systems running Kerberos).
rhost=`who | sed -ne '/'"$tty"'/{s/^[^(]*(*\([^:)]*\)[):.]*.*/\1/;s/[^.]*@//;p;q;}'`

case "$rhost" in
  *.* )
    # Sometimes the domain name is partially cut off; try to fully-resolve
    # the domain by looking up the local host name part and see if the
    # results match the partial text obtained.
    set fnord `echo "$rhost" | sed -e 's/^\([^.]*\)\.\(.*\)/\1 \2/'`
    host="$2"
    domain="$3"
    if (perl -v > /dev/null) 2> /dev/null; then
      fqdn=`perl -e '($name) = gethostbyname ("'"$host"'");
                     $name =~ s/^[^.]*\.//;
                     print "$name\n";'`

      case "$fqdn" in
        '' ) : ;;
        "$domain"* ) rhost="$host.$fqdn" ;;
      esac
    fi
   ;;
esac

if [ -n "$rhost" ]; then
  echo "$rhost:0.0"
else
  exit 1
fi

# getdisplay ends here
