#!/bin/ksh -p
#
# ident "@(#)utxlock.ksh	1.11 04/05/26 SMI"
#
# Copyright 2002,2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

#
# This command is intended to be run by utaction on a disconnect
# event.  It will issue an appropriate screen lock for the current
# windowing environment.
#
# Environments supported (and their default lock programs) are:
# CDE/"dtaction LockDisplay"
# Gnome/"xscreensaver-command -lock"
# other/xlock
#
# If an environment variable SUN_SUNRAY_UTXLOCK_PREF is set,
# if its value is "none" or empty/NULL, no utaction will not be
#       launched to invoked this program at all
# if its value is some other string, that string will be executed on
#       a disconnect instead of the default programs listed above, in
#       order to execute a user's preferred screen lock
#
# The safe/correct place to set this environment variable is in
# $HOME/.dtprofile
#

function notfndhndlr {
    print -u2 "${CMD} not found!"
    logger "$0($(whoami)): ${CMD} not found!"
}

# defaults

OS=`/bin/uname -s`
case "$OS" in
	SunOS)	XBINDIRS=/usr/openwin/bin
		;;
	Linux)	XBINDIRS="/usr/X11R6/bin /usr/bin"
		;;
	*)	print -u2 "$0: unrecognised OS \"$OS\""
		logger "$0($(whoami)): OS ${OS} not recognised!"
		exit 1
		;;
esac

# xscreensaver is the typical screenlock for Gnome.  Unfortunately
# different Linux distros install it in different places.

for XSS_DIR in $XBINDIRS ; do
	XSS_LOCK=${XSS_DIR}/xscreensaver-command
	if [ -x "$XSS_LOCK" ] ; then
		break
	fi
done
XSS_LOCKARGS="-lock"

CDE_LOCK=/usr/dt/bin/dtaction
CDE_LOCKARGS="LockDisplay"

# xlock is our last resort.  Again the loop to deal with it being in
# places on different Linux distros

for XLOCK_DIR in $XBINDIRS ; do
	X_LOCK=$XLOCK_DIR/xlock
	if [ -x "$X_LOCK" ] ; then
		break
	fi
done
X_LOCKARGS="-mode blank"

CDE_ATOM=_DT_SM_PREFERENCES

if [ -n "${SUN_SUNRAY_UTXLOCK_PREF+foo}" ]
then
    if [ -z "${SUN_SUNRAY_UTXLOCK_PREF}" ]
    then
	exit 0
    else
	CMD="${SUN_SUNRAY_UTXLOCK_PREF}"
    fi
    trap notfndhndlr ERR
    set -e
    ${CMD}
    exit 0
else
    # No override - do the defaults

    # Is it Gnome?
    if [ -x ${XSS_LOCK} ]
    then
	${XSS_LOCK} ${XSS_LOCKARGS} > /dev/null 2>&1
	# if lock front-end returns good status, we were able to get
	# xscreensaver to do the job.  This case combines the test
	# and the lock
	if [ $? = 0 ]
	then
	    exit 0
	fi
    fi

    # Is it CDE?
    if /etc/opt/SUNWut/basedir/lib/utxprop -p ${CDE_ATOM} >/dev/null 2>/dev/null
    then
	# if the property exists, this is CDE
        if [ -x ${CDE_LOCK} ]
	then
	    ${CDE_LOCK} ${CDE_LOCKARGS}
	    exit 0
	fi
    fi

    # We dont know what it is, use generic X lock
    if [ -x ${X_LOCK} ]
    then
	${X_LOCK} ${X_LOCKARGS} &
	exit 0
    fi

    # We didn't find xlock?!?
    COMPLAINT="no screenlock program available"
    print -u2 "$0: ${COMPLAINT}"
    logger "$0($(whoami)): ${COMPLAINT}"
    exit 2
fi

exit 0
