#
# ident "@(#)preinstall	1.4 04/01/16 SMI"
#
# Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# preinstall script for SUNWsrcbp - Sun Ray PC/SC bypass smartcard APIs

# if PKG_INSTALL_ROOT is not assigned from the env then
# set it to an empty string, set -u in effect below
#
if [ -z "$PKG_INSTALL_ROOT" ]; then
	PKG_INSTALL_ROOT=""
fi

BASEDIR="`/usr/bin/pkgparam SUNWutscr BASEDIR`"

set -u

SUNWUTLIB="${PKG_INSTALL_ROOT}${BASEDIR}/SUNWut/lib"

OCF_CP_FILE="/etc/smartcard/ocf.classpath"
OCF_TERMADMIN="${SUNWUTLIB}/ocf_termadmin"
OCFSERVER="ocfserv"

CT_JAR="${SUNWUTLIB}/sunrayCTdriver.jar"
CT_JAR_BASE="`/bin/basename $CT_JAR`"

# XXX Wouldn't it be nice to get the factory package path from the
# XXX jar file?
CT_FACTORY="com.sun.opencard.terminal.sunray.SunRayCardTerminalFactory"
CT_MODEL="SunRayDTU"
CT_NAME="SunRayDTU-InternalReader"
CT_DEVICE="DTU@"
CT_TERM_LINE="$CT_FACTORY|$CT_MODEL|$CT_NAME|$CT_DEVICE"

TMP="/tmp/$$.SUNWsrcbp"

    #
    # Check to be sure that the OCF terminal administration
    # utility is present and executable.
    #
    if test ! -x $OCF_TERMADMIN ; then
	echo "Unable to remove: [$CT_MODEL] from OCF"
	echo "Missing terminal administration utility: $OCF_TERMADMIN"
	exit 1
    fi

    #
    # Remove the Sun Ray Card Terminal Driver jar file path
    # from the file that OCF uses to locate it's Java classes.
    #
    egrep -vi $CT_JAR_BASE $OCF_CP_FILE >$TMP
    mv $TMP $OCF_CP_FILE

    #
    # Stop the ocfserver, as the classpath file of the ocfserver 
    # has been updated and ocfserver needs to pick these changes.
    #
    /usr/bin/pkill -x $OCFSERVER 2>/dev/null

    # Tell the user what's about to happen since the following
    # operation might take a long time.
    /bin/echo "Preparing to remove Sun Ray Card Terminal Driver from OCF\c"

    # Remove any Sun Ray Card Terminal Drivers from the OCF server.
    # Hack becasue OCF client lib doesn't always wait for OCF server
    # to start before returning.
    CT_MAX_REMOVE_TRIES=20
    CT_REMOVED=0
    while [ 1 ]
      do
	for SR_CT in `$OCF_TERMADMIN -l 2>/dev/null`
	  do
	    if echo $SR_CT | egrep -is $CT_MODEL ; then

		$OCF_TERMADMIN -r "$SR_CT" 2>/dev/null
		if [ "$?" != "0" ] ; then
		    /bin/echo "\nUnable to remove: [$SR_CT] from OCF"
		else
		    CT_REMOVED=$CT_MAX_REMOVE_TRIES
		fi
	    fi
	  done
	CT_REMOVED="`expr $CT_REMOVED + 1`"
	if [ "$CT_REMOVED" -ge "$CT_MAX_REMOVE_TRIES" ] ; then
	    break
	else
	    /bin/echo ".\c"
	fi
      done

    echo "done"

    #
    # Stop the ocfserver, as the classpath file of the ocfserver 
    # has been updated and ocfserver needs to pick these changes.
    #
    /usr/bin/pkill -x $OCFSERVER 2>/dev/null

    exit 0
