#!/bin/sh
# Periodically manually:
# 	cp ~jhs/bin/.sh/xauth.sh /usr/local/bin/xauth.sh
# Script exports screen xauth permission to other trusted hosts.
# Can be called manually, but as it is now called by .xsession,
# you should only need to call it manually for other hosts that power up
# after your xsession has already started.

# Installed in /usr/local/bin/ so available to root user for
# system repair if ~jhs is not mounted

if [ "$#.x" != "0.x" ];
then
	# Arguments were supplied, so assume them to be a list of host names.
	hosts="$*"
else
	# No arguments were supplied, so use a standard list of host names.
	#	domain=hostname | sed s/`hostname -s`.//
	hfull=`hostname`
	hshort=`hostname -s`
	domain=`echo $hfull | sed s/$hshort.//`
	if [ "$domain" = "bsn.com" ]; then	# {
		hosts="flat.berklix.org tower.berklix.org cebulon gast"
	elif [ "$domain" = "js.berklix.net" ]; then	# }{
 		hosts="deli `hosts`"
	elif [ "$domain" = "berklix.org" ]; then	# }{
		hosts="slim flat tower temp"
	elif [ "$domain" = "no.net" ]; then	# }{ eg laptop roaming
		hosts="fire"
	else	# default }{
		echo "No domain recognised by $0"
		hosts=""
	fi	#}
	# echo "Hosts: $hosts"
fi

# Extract a record.
#	( This fails to extract, if X was started by hand with xinit rather
#	than from xdm, probably because only xdm calls X with -auth as here:
#		/usr/local/bin/X -auth \
#			/usr/local/lib/X11/xdm/authdir/authfiles/A:0-GiG361
#	whereas xinit does not.
#	)

# Example of host to host single xauth usage:
#	xauth extract - `hostname`:0 | rsh -t 8 $i xauth merge -

# Extract screen authority,
tmp=$HOME/tmp/.xauth.sh.$$

xauth extract - `hostname`:0 > $tmp
# Line above works on local hosts, but not if Im using the ncd:0.0 X terminal.

# xauth extract - `printenv DISPLAY` > $tmp
# Line above works on ncd, but not if Im using a local host.

# ls -l $tmp
for i in $hosts
	do
	# echo START $i
	# Export screen access authority to each trusted host.

	cat $tmp | ( rsh -t 200 $i xauth merge - ) 2> /dev/null &
	# echo -n "$i "
	# 2>		To hide EG	sunx: Operation timed out
	# '&':		Speeds up the results, and avoids hanging
	#		on some host that may be powered off.
	# Brackets:	Avoids subsequent hosts not being run, after a
	#		previous host rsh fails, perhaps from an
	#		rsh related permission problem.
	# rsh -t 200:	Change the wait per host (default ~75 seconds).
	#		If name $i is slow to resolve, EG if
	#		named is misconfigured, it can take 120 seconds
	#		just to do "rsh wall who".
	# Race Conditions:
	#		This:
	#			( cat $tmp | rsh $i xauth merge - ) &
	#		is no longer used, as I saw failures where the rm
	#		would run before the asynchronous process completed.
	#		This also failed sometimes:
	#			(rsh $i xauth merge - < $tmp > /dev/null ) &
	# echo Finishing $i
	done
# echo 	""	# Clear the line after printing host names.
# ( wait ; rm -f $tmp )
( sleep 60 ; rm -f $tmp ) &

