#! /bin/sh
#
# Splus5 LICENSE server [start|stop|status]
#
# Interface to license server functions.
#

if [ $# -gt 0 ]
then subcmd=$1; shift
else subcmd=status
fi

keyfile=$SLIC_KEYDIR/$LIC_FEATURE.lic
case "X$subcmd" in
    Xstart)
        if [ ! -r $keyfile ]
        then
            echo "No S-PLUS license key($feature) installed" >&2
            echo "Need to run 'Splus5 LICENSE install'" >&2
            exit 1
        fi
        # Check that we're on the right host to start the server.
        if Slmhelper okserver $keyfile 2>/dev/null
        then
            # Check to see if it is already up.
            if Slmhelper upserver $keyfile 2>/dev/null
            then echo "License server already started."; exit 0
            fi
        else
            serverhost=`Slmhelper serverhost $keyfile`
            echo "License server should be started on $serverhost." >&2
            echo "License server not started." >&2
            exit 1
        fi
        while [ $# -gt 0 ]
        do case "$1" in
            -e) SLIC_KEYDIR="$2"; shift;;
            -l) LIC_LOGFILE="$2"; shift;;
            -m) LIC_LOGSIZE="$2"; shift;;
            -r) LIC_RESOURCES="$2"; shift;;
            *) extra_args="$extra_args $1";;
        esac; shift; done
        if [ -r $LIC_RESOURCES ]
        then LIC_RESOURCES="-r $LIC_RESOURCES"
        else LIC_RESOURCES=""
        fi
        umask 0
        touch $LIC_LOGFILE 2>/dev/null
        [ -w $LIC_LOGFILE ] || chmod a+w $LIC_LOGFILE 2> /dev/null
        if [ ! -w $LIC_LOGFILE ]
        then
            echo 'Warning: elmd log file not writeable. Moving it to' >&2
            echo "   $LIC_LOGFILE.$$" >&2
            mv $LIC_LOGFILE $LIC_LOGFILE.$$
        fi
        exec elmd -l $LIC_LOGFILE -m $LIC_LOGSIZE \
             -e $SLIC_KEYDIR $LIC_RESOURCES -s0 $extra_args >/dev/null 2>/dev/null
    ;;
    Xstop)
        exec elmadmin -k
    ;;
    Xstatus)
        # Used to use this, but changed due to bug in Elan's libraries:
        # exec elmadmin -s ${1+"$@"}
        exec Slmhelper statserver $keyfile
    ;;
    Xhost)
        exec Slmhelper serverhost $keyfile
    ;;
    *)
        echo "Invalid Splus5 LICENSE server subcommand: $subcmd" >&2
        exit 1
    ;;
esac
