#! /bin/sh

DISPLAY=${DISPLAY:-:0}
PATH='/bin:/usr/bin:/usr/local/bin'
export DISPLAY PATH

# If you wish to have Num Lock on by default, uncomment the following line.
#enable_X11_numlock on

# Set to "yes" if you want to allow the user to interactively select a VNC
# server, rather than connect to a default service automatically.
[ "$PROMPT_SERVER" ] || PROMPT_SERVER=no
# To avoid needless network and server resource consumption for idle sessions,
# you can optionally force the user to acknowledge session exit, and thereby
# defer automatic reconnection (if the script is being [re]spawned by init).
# The post-mortem dialog will display the stdout and stderr output of the
# client (useful for debugging).  If /sbin/init is setuid root and the
# workstation is running in dedicated RFB mode (i.e. this script was spawned by
# init), the user will also be given a workstation shutdown option.
[ "$PROMPT_POSTMORTEM" ] || PROMPT_POSTMORTEM=yes

if [ $# -eq 0 ]; then
    if checkhostname -q 'rfbserver'; then
	set 'rfbserver'
    else
	PROMPT_SERVER=yes
    fi
fi

if [ "$PROMPT_SERVER" = 'yes' ]; then
    CANONICAL="`checkhostname -n \"$1\" || echo 'Unset'`/`checkhostname -I \
	    \"$1\"`"
    RFBSERVER=`xwChoice -title 'Select VNC Server' -question \
	    'Please enter VNC server[:port] ' -input -cancel \
	    "Default ($CANONICAL)" "$1" -ok 'Custom'`
    [ "$RFBSERVER" ] || exit 1
    checkhostname -q "`echo $RFBSERVER | cut -f1 -d:`" || {
	xwChoice -error OK "Unable to resolve \"$RFBSERVER\""
	exit 1
    }
fi

OUTFILE="/tmp/`basename $0`.$$.out"
echo -e 'VNC session output:\n' >$OUTFILE
# - To use a set password, add "-xrm '*passwordDialog: false'" and
# "-passwd /.vnc/passwd" or similar.
# - If your X driver uses a hardware cursor, using "-x11cursor" will remove
#   the remote cursor and therefore look nicer.  Don't do this if you have a
#   software cursor, or you will have strange side effects.
rfb -fullscreen ${RFBSERVER:-$1} >>$OUTFILE 2>&1

[ "$PROMPT_POSTMORTEM" != 'yes' ] && exit 0

if [ -u /sbin/init -a "$PPID" -eq 1 ]; then
    [ "`xwChoice -title 'VNC session terminated' -question '' -ok \
	    'New Session' -cancel 'Shutdown' 'Shutdown' -help \
	    'Show Session Output' 'OK' $OUTFILE`" = 'Shutdown' ] && \
	    exec /sbin/init 0
else
    xwChoice -title 'Disconnected' -log OK $OUTFILE
fi

rm $OUTFILE
exit 0
