#!/bin/dash
# start a remote X desktop connection using ssh
SCREEN_SIZE=${SCREEN_SIZE:-1024x768}

case "$1" in
	-h|--help|"")
		cat << EOF
ssh to remote host and launch its desktop inside Xephyr.
Close Xephyr window to finish. Pass SCREEN_SIZE env to change Xephyr
window size from the default of $SCREEN_SIZE.
Usage: ${0##*/} ssh-parameters
EOF
	exit
esac

ok=
for disp in $(seq 1 20); do
	[ ! -e /tmp/.X{$disp}-lock ] && ok=yes && break
done

if [ $ok ]; then
	Xephyr -screen $SCREEN_SIZE -keybd ephyr,,xkbmodel=evdev,xkbrules=evdev :$disp 2>/dev/null &
	XPID=$!
	export DISPLAY=:$disp
	sleep 1 # give time for Xephyr to start
	xmessage -center -timeout 10 "Close window to end session."
	if [ -e /usr/bin/ssh-askpass ]; then
		SSH_ASKPASS=/usr/bin/ssh-askpass setsid ssh -Y "$@" /bin/sh -l -c "\$HOME/.xinitrc"
	else
		xmessage -center -timeout 10 "Enter ssh password in original terminal window." &
		ssh -Y "$@" /bin/sh -l -c "\$HOME/.xinitrc"
	fi
	kill $XPID 2>/dev/null
else
	echo "Unable to start Xephyr "
fi
