#! /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 Spice
# 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 Spice 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 'spiceserver'; then
	set 'spiceserver'
    else
	PROMPT_SERVER=yes
    fi
fi

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

OUTFILE="/tmp/`basename $0`.$$.out"
echo -e 'Spice session output:\n' >$OUTFILE
spicec -f -p 1923 -h `echo ${SPICESERVER:-$1} | sed 's/:/ -p /'` 2>&1 \
	>>$OUTFILE

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

if [ -u /sbin/init -a "$PPID" -eq 1 ]; then
    [ "`xwChoice -title 'Spice 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
