#! /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 an ICA
# service, rather than connect to a default service automatically.  This will
# only work for simple connections: connections to named servers, or to
# published applications in the default farm.  For anything more complicated,
# use wfcmgr instead of this script.
[ "$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 ICA mode (i.e. this script was spawned by
# init), the user will also be given a workstation shutdown option.
[ "$PROMPT_POSTMORTEM" ] || PROMPT_POSTMORTEM=yes

# N.B. The global variable icaservice (possibly set via /etc/profile) and the
# local variable ICASERVICE are two different things!  The literal "icaservice"
# might also be a valid host alias.

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

if [ "$PROMPT_SERVER" = 'yes' ]; then
    if checkhostname -q "$1"; then
	CANONICAL="`checkhostname -n \"$1\"`/`checkhostname -i \"$1\"`"
    else
	CANONICAL="${1:-None}"
    fi
    ICASERVICE=`xwChoice -title 'Select ICA Target' -question \
	    'Enter ICA server or published application name' -input -cancel \
	    "Default ($CANONICAL)" "$1" -ok 'Custom'`
    [ "$ICASERVICE" ] || exit 1
    if [ "`echo \"$ICASERVICE\" | tr -cd '[0-9][A-Z][a-z]_\-.'`" != \
	    "$ICASERVICE" ]; then
	xwChoice -error OK \
		'Please use letters, digits, underscores, hyphens and periods only.'
	exit 1
    fi
fi

OUTFILE="/tmp/`basename $0`.$$.out"
echo -e 'ICA session output:\n' >$OUTFILE
# If published applications don't work, you could add "-p" and/or "-A" options
# here (see output of "ica --help"), but it would be better to change
# ICA_BROWSER_PROTO and ICA_BROWSER_ADDR in the "ica" script.
#
# Add "-S" to inhibit seamless mode if your application is a published desktop.
#
# You may wish to add "-quiet" once you have resolved any initial difficulties.
#
ica ${ICASERVICE:-$1} -F >>$OUTFILE 2>&1

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

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