#! /usr/dt/bin/dtksh
#
# ident "@(#)utselect.sh	1.51 04/10/19 SMI"
#
# Copyright 1999-2002,2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms
#

SUNWUT=$(/etc/opt/SUNWut/basedir/lib/utprodinfo -r SUNWuto)/SUNWut
SUNWUTBIN=${SUNWUT}/bin
SUNWUTLIB=${SUNWUT}/lib
UTACTION=${SUNWUTBIN}/utaction
UTXPROP=${SUNWUTLIB}/utxprop
UTXCONFIG=${SUNWUTBIN}/utxconfig
SUNWUTR=$(/etc/opt/SUNWut/basedir/lib/utprodinfo -r SUNWutr)
SUNWUTETC=${SUNWUTR}/etc/opt/SUNWut
ME=$0
export TEXTDOMAIN="utselect"
export TEXTDOMAINDIR=${SUNWUTLIB}/locale

Usage() {
	print "
Usage: $ME [ -X ] [ -L ] [ -R | -S ] [ -- X-Windows parameters ]
where:
      -X 	exit after selection is made
      -L 	run in "login" mode, before login dialog
      -R	enable text field to enter explicit host name
      -S	disable text field to enter explicit host name
"
exit 1
}

shortname() {
	printf "%-16.16s " "$@"
}

DoAccept() {
	server=
	if [ "$remote" = "true" ]
	then
		XmTextFieldGetString tserver $ENTER_TEXT
	else
		tserver=
	fi

	XtGetValues $CHOOSER_LIST selectedItems:SELECT
	if [ -z "$SELECT" -a -n "$tserver" ]
	then
		server=$tserver
	else
		tserver=$(print $SELECT | nawk '{print $1}')

		# Make sure that the selected server is up
		let i=0
		while [ $i -lt $lines ]
		do
			# The first field of the selection contains a
			# possibly-truncated server shortname, so compare
			# against the similarly-truncated shortname.
			#
			if [ "$tserver" = `shortname "${sysname[$i]}"` -a \
				"${updown[$i]}" = "U" ]
			then
				server=${sysname[$i]}
			fi
			let "i = i + 1"
		done
	fi
	if [ -n "$server" ]
	then
		if [ "$server" != $thishost ]
		then
			$SUNWUTBIN/utswitch -h $server
		else
			if [ $mode = "login" ]
			then
				exit
			fi
			XBell $(XtDisplay - $CHOOSER_LIST) 1
		fi
		if [ $exitmode = "yes" ]
		then
			exit
		fi
	else
		XBell $(XtDisplay - $CHOOSER_LIST) 1
	fi
}

EnterFocusIn() {
	XmListDeselectAllItems $CHOOSER_LIST
}

DoCancel() {
	exit
}

maxwidth() {
	XtGetValues $1 width:WIDTH
	if [ $WIDTH -gt $maxwidth ]
	then
		maxwidth=$WIDTH
	fi
}

MakeEntry() {
	# The 'Server' field.  This contains the servername, truncated as
	# necessary to fit into a fixed-width column.
	#
	shortname "$1"

	# The 'Session' field, either a display number or "None".
	#
	if [ $2 -ge 0 ]
	then
		printf ":%-10s " $2
	else
		printf "%-11s " "$none_text"
	fi

	# Padding.  Why isn't this part of the 'Session' printf?
	#
	printf "  "

	# The 'Status' field.  "Offline", "Up", "No path" or "No Response".
	#
	if  [ $3 -ge -1 ]
	then
		if [ $4 -ne 0 ]
		then
			printf "%s" "$offline_text"
		else
			printf "%s" "$up_text"
		fi
	elif [ $3 -eq  -2 ]
	then
		printf "%s" "$response_text"
	elif [ $3 -eq -3 ]
	then
		printf "%s" "$path_text"
	fi
	printf "\n"
}

RemoveCopyright() {
	XtSetValues $CR_LABEL labelString:""
}

LayoutCB() {
	XmListDeleteAllItems $CHOOSER_LIST
	let lines=0

	# Wait until auth manager knows about this session
	OUT="$($SUNWUTBIN/utswitch -l)"
	while [ "${OUT#*no token*}" != "$OUT" ]
	do
		# If we're currently disconnected, block until we are
		# connected so that refresh occurs immediately upon
		# connecting and shows any change in status
		$UTACTION -e -i -c "true"
		OUT="$($SUNWUTBIN/utswitch -l)"
	done

	# Reregister to run every 5 minutes to detect disconnection
	XtAddTimeOut RefreshTO 300000 LayoutCB

	# If utswitch failed for some reason bail out now
	if [ -z "$OUT" ]
	then
		return
	fi

	updown[1]=N
	print "$OUT" | (export LC_ALL=C; sort +2nr) | \
		while read sys dpy state offline rest
		do
			if [ $state -le -3 ]
			then
				continue
			fi

			if [ "$offline" = "" ]
			then
				offline=0
			fi

			if [ $offline -eq 0 -o $dpy -ge 0 ]
			then
				updown[$lines]=U
			else
				updown[$lines]=N
			fi
			sysname[$lines]=$sys
			dpys[$lines]=$dpy
			states[$lines]=$state

			if [ $sys = $thishost ]
			then
				let "selected = lines + 1"
			fi

			XmListAddItemUnselected $CHOOSER_LIST 0 \
				"$(MakeEntry $sys $dpy $state $offline)"

			let "lines = lines + 1"
		done

	# Pass through if there's only one choice, and remote = false
	if [ $mode = "login" -a $lines -le 1 -a $remote = "false" ]
	then
		exit
	fi

	if [ $lines -ge 2 -a $mode = "normal" -a ${updown[1]} = "U" ]
	then
		selected=2
	fi

	XmListSelectPos $CHOOSER_LIST $selected False
	XtGetValues $MATTE1 width:WIDTH
	XtGetValues $OK_BUTTON width:BUTWIDTH
	spacing=$(($WIDTH / 3 - $BUTWIDTH))
	XtSetValues $OK_BUTTON leftOffset:$((spacing/2))
	XtSetValues $CLEAR_BUTTON leftOffset:$spacing
	XtSetValues $REFRESH_BUTTON leftOffset:$spacing
	XtGetValues $LOGIN_SHELL width:wd
	XtGetValues $LOGIN_SHELL height:ht
}

maxwidth=0
thishost=`hostname`

XSETROOT=/bin/false
for XSETROOTPATH in /usr/openwin/bin /usr/X11R6/bin /usr/bin ; do
	if [ -x $XSETROOTPATH/xsetroot ] ; then
		XSETROOT=$XSETROOTPATH/xsetroot
		break
	fi
done

# Set mode for being run by login
mode=normal
exitmode=no
remote=`sed -n '/^remoteSelect=/s///p' $SUNWUTETC/auth.props`
i=1
while [ $i -le $# ]
do
    ARGNAME=$1
    case $ARGNAME in
      -X)  exitmode=yes;;
      -L)  mode=login
	  $XSETROOT -cursor_name left_ptr;;
      -R)  remote=true;;
      -S)  remote=false;;
      --)  shift; break;;
      *)  print -u2 "`gettext 'Error: arguments not recognized:'`" "$*"
	  Usage;;
    esac
    let "i = i + 1"
    shift
done

# Make sure this is a Sunray session
sidhost=`$UTXPROP -s 2>/dev/null | sed 's/:.*//'`
if [ -z "$sidhost" -o "$sidhost" != "$thishost" ]
then
	print -u2 "`gettext 'Error: cannot select from a non-Sun Ray or remote login session'`"
	exit 1
fi

if [ "$mode" = "login" ]
then
	d=`echo $DISPLAY | sed -n '/.*:\([0-9][0-9]*\).*/s//\1/p'`
	if [ -r /var/dt/sdtlogin/lastlang_$d ]
	then
		export LANG=`cat /var/dt/sdtlogin/lastlang_$d`
	fi
	xrdb -merge /usr/dt/config/$LANG/sys.font
fi

# Japanese and Chinese locales don't work with fixed fonts
LANG_BASE=`echo $LANG | sed 's/^\(..\).*/\1/'`
case $LANG_BASE in
	ja | zh | ko)	FONTLIST="" ;;
	*)		FONTLIST=fontList:fixed ;;
esac
LC_ALL=

# localized variables
title_text="`gettext 'Server Selection'`"
header_text="`gettext 'Server          Session         Status'`"
ok_text="`gettext OK`"
cancel_text="`gettext Cancel`"
refresh_text="`gettext Refresh`"
none_text="`gettext None`"
up_text="`gettext '   Up      '`"
response_text="`gettext 'No Response'`"
path_text="`gettext '  No path  '`"
offline_text="`gettext ' Offline   '`"
enter_text="`gettext 'Enter server: '`"

. /usr/dt/lib/dtksh/DtFuncs.dtsh
XtInitialize TOPLEVEL utselect Utselect "$thishost" "$@"

XtCreateApplicationShell LOGIN_SHELL "$thishost" TopLevelShell \
	allowShellResize:True \
	mappedWhenManaged:False

XtCreateManagedWidget TABLE table XmDrawingArea $LOGIN_SHELL #background:black

XtDisplay DISP $LOGIN_SHELL
XmInternAtom CLOSE_ATOM $DISP WM_DELETE_WINDOW false
XmAddWMProtocolCallback $LOGIN_SHELL $CLOSE_ATOM DoCancel

XmCreateForm MATTE $TABLE matte
XtManageChild $MATTE

XmCreateFrame MATTE_FRAME $MATTE matte_frame \
	shadowThickness:2 \
	topAttachment:ATTACH_FORM \
	bottomAttachment:ATTACH_FORM \
	leftAttachment:ATTACH_FORM \
	rightAttachment:ATTACH_FORM
#	shadowType:SHADOW_OUT
XtManageChild $MATTE_FRAME

XmCreateForm MATTE1 $MATTE_FRAME matte1
XtManageChild $MATTE1

XmCreateLabel GREETING $MATTE1 "greeting" \
	labelString:"$title_text" \
	topAttachment:ATTACH_FORM \
	topOffset:10 \
	leftAttachment:ATTACH_FORM \
	rightAttachment:ATTACH_FORM \
	alignment:ALIGNMENT_CENTER \
	traversalOn:False
XtManageChild $GREETING

cr_text="`gettext 'Copyright %s Sun Microsystems, Inc.\nAll rights reserved.'`"
cr_text=`printf "$cr_text" "1999 - 2004"`


XmCreateLabel CR_LABEL $MATTE1 "cr_label" \
	labelString:"$cr_text" \
	bottomAttachment:ATTACH_FORM \
	leftAttachment:ATTACH_FORM \
	rightAttachment:ATTACH_FORM \
	alignment:ALIGNMENT_CENTER \
	traversalOn:False \
	$FONTLIST
XtManageChild $CR_LABEL

XmCreateLabelGadget LIST_HEAD $MATTE1 "list_head" \
	traversalOn:False \
	topAttachment:ATTACH_WIDGET \
	topWidget:$GREETING \
	topOffset:10 \
	leftAttachment:ATTACH_FORM \
	leftOffset:13 \
	$FONTLIST
XtSetValues $LIST_HEAD labelString:"$header_text"
XtManageChild $LIST_HEAD

XmCreatePushButtonGadget OK_BUTTON $MATTE1 "ok_button" \
	bottomAttachment:ATTACH_WIDGET bottomWidget:$CR_LABEL \
	traversalOn:True labelString:$ok_text \
	leftOffset:15 \
	leftAttachment:ATTACH_FORM 
XtAddCallback $OK_BUTTON activateCallback DoAccept
XtManageChild $OK_BUTTON
maxwidth $OK_BUTTON

XmCreatePushButtonGadget CLEAR_BUTTON $MATTE1 "clear_button" \
	bottomAttachment:ATTACH_WIDGET bottomWidget:$CR_LABEL \
	traversalOn:True leftAttachment:ATTACH_WIDGET leftWidget:$OK_BUTTON \
	labelString:$cancel_text
XtAddCallback $CLEAR_BUTTON activateCallback DoCancel
XtManageChild $CLEAR_BUTTON
maxwidth $CLEAR_BUTTON

XmCreatePushButtonGadget REFRESH_BUTTON $MATTE1 "refresh_button" \
	bottomAttachment:ATTACH_WIDGET bottomWidget:$CR_LABEL \
	traversalOn:True leftAttachment:ATTACH_WIDGET leftWidget:$CLEAR_BUTTON \
	labelString:$refresh_text
XtAddCallback $REFRESH_BUTTON activateCallback LayoutCB
XtManageChild $REFRESH_BUTTON
maxwidth $REFRESH_BUTTON

XtSetValues $OK_BUTTON width:$maxwidth recomputeSize:False
XtSetValues $CLEAR_BUTTON width:$maxwidth recomputeSize:False
XtSetValues $REFRESH_BUTTON width:$maxwidth recomputeSize:False

if [ "$remote" = "true" ]
then
	XmCreateLabel ENTER_LABEL $MATTE1 "enter_label" \
		traversalOn:False \
		bottomAttachment:ATTACH_WIDGET \
		bottomWidget:$OK_BUTTON \
		bottomOffset:12 \
		leftAttachment:ATTACH_FORM \
		leftOffset:13
	XtSetValues $ENTER_LABEL labelString:"$enter_text"
	XtManageChild $ENTER_LABEL

	XmCreateTextField ENTER_TEXT $MATTE1 "enter_text" \
		traversalOn:True \
		bottomAttachment:ATTACH_WIDGET \
		bottomWidget:$OK_BUTTON \
		bottomOffset:10 \
		leftAttachment:ATTACH_WIDGET \
		leftWidget:$ENTER_LABEL \
		$FONTLIST
	XtAddCallback $ENTER_TEXT focusCallback EnterFocusIn
	XtAddCallback $ENTER_TEXT activateCallback DoAccept
	XtManageChild $ENTER_TEXT
	under_choose=$ENTER_LABEL
else
	under_choose=$OK_BUTTON
fi

XmCreateScrolledList CHOOSER_LIST $MATTE1 "chooser_list" \
	leftAttachment:ATTACH_FORM \
	leftOffset:10 \
	rightAttachment:ATTACH_FORM \
	rightOffset:10 \
	topAttachment:ATTACH_WIDGET \
	topWidget:$LIST_HEAD \
	topOffset:1 \
	bottomAttachment:ATTACH_WIDGET \
	bottomWidget:$under_choose \
	bottomOffset:10 \
	listSizePolicy:RESIZE_IF_POSSIBLE \
	scrollBarDisplayPolicy:AS_NEEDED \
	visibleItemCount:5 \
	$FONTLIST
XtAddCallback $CHOOSER_LIST defaultActionCallback DoAccept
XtManageChild $CHOOSER_LIST

XWidthOfScreen RW $(XtScreen - $LOGIN_SHELL)
XHeightOfScreen RH $(XtScreen - $LOGIN_SHELL)

XtRealizeWidget $LOGIN_SHELL

XtGetValues $LOGIN_SHELL width:wd height:ht
if [ "$mode" = "login" ]
then
	# Fix positioning for Xinerama
	set -A dims `$UTXCONFIG -l | nawk -F '=' -v W=$RW -v H=$RH '
		$1 == "RESOLUTION" {
			split($2, dim, "x")
		}
		$1 == "SCREEN_GEOMETRY" {
			split($2, wh, "x")
		}
		$1 == "ENABLE_XINERAMA" {
			xinerama = $2
		}
		$1 == "ENABLE_AUTO_SIZING" {
			auto = $2
		}
		END {
			if (xinerama == "yes") {
				if (auto == "no")
					print dim[2], dim[2]
				if (W > dim[1] || H > dim[2])
					print W / wh[1], H / wh[2]
			}
		}'`
	if [ -n "$dims" ]
	then
		RW=${dims[0]}
		RH=${dims[1]}
	fi
	let "x = ($RW - $wd) / 2"
	let "y = ($RH - $ht) / 2"
	XtSetValues $LOGIN_SHELL x:$x y:$y
fi
LayoutCB
XtMapWidget $LOGIN_SHELL
XtAddTimeOut CopyrightTO 2000 RemoveCopyright
XtMainLoop
