#! /bin/sh
# rex host [cmd] - run cmd on a pty on host
# Geoff Collyer, Mark Moraes, University of Toronto
opath="$PATH"
# Path needed for the right version of rsh, arch, ttymodes, and stty
# PATH=$HOME/bin:/local/bin:/usr/ucb:/usr/bsd:/bsd43/bin:/bin:/usr/bin
# export PATH
arch=`arch`

case $# in
0)	echo "usage: $0 hostname [command]" >&2; exit 1 ;;
1)	host=$1; shift; cmd=sh ;;
*)	host=$1; shift; cmd="$@" ;;
esac

modes=`ttymodes 2> /dev/null`	# save tty modes
stty raw -echo 2> /dev/null	# local side just sends bytes across.
				# this has a few disadvantages, alas.

# Some environment munging

# for X Windows
case "$DISPLAY" in
'')	;;
unix:*|:*)
	DISPLAY=${HOST-`hostname`}` expr "$DISPLAY" : "[^:]*\(:.*\)" `
	export DISPLAY
	;;
esac

# More environment munging to change the output of printenv to
# a form that can be fed back to the shell

rsh $host bin/mapenv -a $arch -m ${HOST-`hostname`} -h "$HOME" `
	(printenv; echo PATH="$opath") |
	sed	-e 's/[\`\"\$]/\\\\&/g' \
		-e 's/^\([^=]*\)=\(.*\)/\1=\"\2\"/' \
		-e '/^[^=]*()/,/^}$/d' \
		-e 's/^/-e /' |
	egrep -v '^-e (HOME|CWD|PWD|HOST|HOSTTYPE|REMOTEHOST|REMOTEUSER|RHOST|TERMCAP)='
    ` onpty -t \""$modes"\" "$cmd"

# this doesn't always work
# ttymodes $modes 2> /dev/null	# restore normalcy
stty -raw -cbreak cooked echo 2> /dev/null
