#!/bin/sh
#
# Copyright(c) 1998 Sun Microsystems, Inc. All rights reserved
#
#ident  "%Z%%M% %I%     %E% SMI"
#
#
#	Usage
#		progname [java_options] {start|stop|status|help}
#
#       java options will be passed to the java execution 
#		
#       required arguments:
#		start	Start the cli station
#		stop    Stop the cli station
#		status  Check to see if cli is running
#               help	Provide help for the startup script and java code
#
# 	Environment Variable Overrides are:
#		ESM_HOME
#			Location of root of tree (e.g /opt/SUNWesm)
#		ESM_SETUP_HOME
#			Location of the esm_setup script
#		ESM_JAVA_ARG
#			Optional arguments to add the the Java execution
#		ESM_FOREGROUND
#			Change the model of execution for those tasks
#                       which are set to execute in the background to 
#                       execute in the foreground.  This is provided 
#                       mainly for use within test engines.
#
# 	Environment Variable Modified are:
#	        LD_LIBRARY_PATH
#                       The LD_LIBRARY_PATH is prepended with the 
#                       path to our libraries
#
#       Return:
#		0 on success
#		1 or greater on failure
#
#
#

progname=`basename $0`

PATH=/usr/bin:/usr/sbin:/sbin:/usr/ucb/bin
PKGINFO=pkginfo
PACKAGE=SUNWesm
cwd=`pwd`

# Output usage
do_usage ()
{
    echo "$progname: \c" >&2

    # Allow script to be multi-use
    if [ 1 -eq 0 ]
    then
        gettext $TEXTDOMAIN "Usage: [java options] {start|stop|status|help} " >&2
    else
        gettext $TEXTDOMAIN "Usage: [java options] " >&2
    fi

    echo >&2
    echo >&2
    gettext $TEXTDOMAIN "       java options will be passed to the executing java class" >&2
    echo >&2

    gettext $TEXTDOMAIN "       required arguments:" >&2
    echo >&2
    # Allow script to be multi-use
    if [ 1 -eq 0 ]
    then
        gettext $TEXTDOMAIN "		start	Start the cli station" >&2
	echo >&2
        gettext $TEXTDOMAIN "		stop    Stop the cli station" >&2
	echo >&2
        gettext $TEXTDOMAIN "		status  Check cli station status" >&2
	echo >&2
    fi
    gettext $TEXTDOMAIN "		help    Provide usage for the startup script and cli station" >&2
    echo >&2
}

# Check the station status
# Return 0 is running
# Return 1 if not running
do_stat ()
{
    [ "$ESM_FOREGROUND" != "" ] && return 1


    if [ x$PID_LOCATION != x ]
    then
        if [ -f $PID_LOCATION ]
        then
	    PID=`cat $PID_LOCATION`
	    kill -0 $PID > /dev/null 2>&1
	    if [ $? -ne 0 ]
	    then
		# The process is not running
		# remove invalid pid file
	        rm $PID_LOCATION > /dev/null 2>&1
	        return 1
	    else
		# The process is running, pass along info
		return 0
	    fi
	else
	    # Did not find a pid file, mark as not running
	    return 1
	fi # -f $PID_LOCATION
    fi
    return 1
}

# Verify if there is a running process
# Return 0 if running
# Return 1 if not
verify_pid ()
{

    if [ 0 -eq 1 ]
    then
        do_stat 
	return $?
    fi # [ 0 -ne 1 ]
    return 1
}

# set up environment
env_setup()
{

	ulimit -n 256

}

# Start the station
do_start ()
{
    verify_pid
    if [ $? -eq 0 ]
    then
	echo "$progname: \c" >&2
	gettext $TEXTDOMAIN "Error: Running process found. Aborting start." >&2
	echo "" >&2
	exit 4
    fi

    env_setup

    COMMAND="$_ESM_JAVA_START com.sun.esm.cli.Cli -R $_ESM_RT_HOME/ \
	    $ESM_JAVA_ARG $COMMAND_LINE_ARG"
    if [ "$ESM_FOREGROUND" != "" ]
    then
	eval $COMMAND
    else
	if [ 0 -ne 1 ]
        then
            eval $COMMAND
        else
	    # create lock that will be cleared by station

	    if [ "esm_cli" = "esm_moboot" ]
	    then
		> $LOCK_LOCATION
	    fi

            eval "$COMMAND &"
            PID=$!
            if [ x$PID_LOCATION != x ]
            then
                echo $! > $PID_LOCATION
            fi

	    if [ "esm_cli" = "esm_moboot" ]
	    then
		# wait for lock file to be cleared by stations
		wait_lock
	    fi

        fi # [ 0 -ne 1 ]
    fi # [ "$ESM_FOREGROUND" -ne "" ]
    
}

# wait for lock to be cleared
wait_lock()
{
    # How many times to try for lock clearing
    LOCK_TRIES=720

    # Time to wait
    TRY_TIME=5 
    
    # current try
    try=0

    while [ $try -le $LOCK_TRIES ]
    do
	if [ ! -f $LOCK_LOCATION ]
	then
	    # success
	    return
	fi

	sleep $TRY_TIME
        try=`expr $try + 1`

    done
    
    # If you get here, it is an error. Stop the JVM and exit this shell.
    do_stop
    echo "$progname: \c" >&2
    gettext $TEXTDOMAIN "Error: Did not start completely." >&2
    echo "" >&2
    exit 4


}

killproc ()
{
    pid=`/usr/bin/ps -e -o pid -o args | /usr/bin/grep $1 |
         grep -v grep | cut -f1 -d' '`
    [ "$pid" != "" ] && kill $pid
}

# Stop the station
do_stop ()
{
    if [ x$PID_LOCATION != x ]
    then
        if [ -f $PID_LOCATION ]
        then
	    PID=`cat $PID_LOCATION`
	    rm $PID_LOCATION > /dev/null 2>&1
	    kill -0 $PID > /dev/null 2>&1
	    if [ $? -ne 0 ]
	    then
	        echo "$progname: \c" >&2
	        gettext $TEXTDOMAIN "Notice: Unable to locate process id" >&2
	        echo " $PID" >&2
	        rm $PID_LOCATION > /dev/null 2>&1
		return 1
	    fi

	    kill -TERM $PID > /dev/null 2>&1
	    if [ $? -ne 0 ]
	    then
	        kill -HUP $PID > /dev/null 2>&1
		if [ $? -ne 0 ]
		then
	            kill -KILL $PID > /dev/null 2>&1
		    if [ $? -ne 0 ]
		    then
	                echo "$progname: \c" >&2
	                gettext $TEXTDOMAIN "Notice: Unable to kill process id" >&2
	                echo " $PID" >&2
		    fi
		fi # -HUP
            fi # -TERM

        else
	    killproc com.sun.esm.cli.Cli
        fi
    else
	killproc com.sun.esm.cli.Cli
    fi
    #$JAVA_HOME $JAVA_CLASSPATH com.sun.esm.cli.Cli -stop &
}

#  Invoke the program as a client
#
do_client ()
{
    verify_pid
    if [ $? -ne 0 ]
    then
	echo "$progname: \c" >&2
	gettext $TEXTDOMAIN "Error: Running daemon not found. Cannot invoke as a client." >&2
	echo "" >&2
	exit 4
    fi

    COMMAND="$_ESM_JAVA_START com.sun.esm.cli.Cli -R $_ESM_RT_HOME/ \
	    $ESM_JAVA_ARG $COMMAND_LINE_ARG"
    eval $COMMAND
}

# Set the location of the pid file
set_pid_location ()
{
    # Set location of PID File
    if [ 0 -eq 1 ]
    then
        PID_LOCATION=$_ESM_RT_HOME/var/opt/SUNWesm/etc/cli/
        if [ ! -d $PID_LOCATION ]
        then
	    mkdir -p $PID_LOCATION > /dev/null 2>&1
	    if [ $? -ne 0 ]
	    then
	        echo "$progname: \c" >&2
                gettext $TEXTDOMAIN "Unable to locate Process ID directory" >&2
	        echo " $PID_LOCATION" >&2
	        echo >&2
	        PID_LOCATION=
	    else
	        PID_LOCATION=$_ESM_RT_HOME/var/opt/SUNWesm/etc/cli/.pid
	    fi
        else
	    PID_LOCATION=$_ESM_RT_HOME/var/opt/SUNWesm/etc/cli/.pid
        fi
    fi
}

# Set the location of the lock file
set_lock_location ()
{
	
    case "esm_cli"
    in
    esm_moboot)
	LOCK_NAME=.esm_mo_lck
	;;
    esm_mcboot)
	LOCK_NAME=.esm_mc_lck
        ;;
    *)
	LOCK_NAME=.esm_generic_lck
	;;
    esac


    # Set location of lock File
    if [ 0 -eq 1 ]
    then
        LOCK_LOCATION=$_ESM_RT_HOME/var/opt/SUNWesm/etc/cli/
        if [ ! -d $LOCK_LOCATION ]
        then
	    mkdir -p $LOCK_LOCATION > /dev/null 2>&1
	    if [ $? -ne 0 ]
	    then
	        echo "$progname: \c" >&2
                gettext $TEXTDOMAIN "Unable to locate lock directory" >&2
	        echo " $LOCK_LOCATION" >&2
	        echo >&2
	        LOCK_LOCATION=
	    else
	        LOCK_LOCATION=$_ESM_RT_HOME/var/opt/SUNWesm/etc/cli/$LOCK_NAME
	    fi
        else
	    LOCK_LOCATION=$_ESM_RT_HOME/var/opt/SUNWesm/etc/cli/$LOCK_NAME
        fi
    fi
}

# Set the location of the root of the tree 
# Taken from esm_setup
set_esm_home ()
{

    # ESM_HOME is picked up from the environment.  
    # _ESM_HOME is set from the command line.

    # If we find _ESM_HOME do not bother to set it
    if [ "$_ESM_HOME" = "" ]
    then
        # _RELOCATE_DIR attempts to pick up the information from the package
        # database
        _RELOCATE_DIR=`${PKGINFO} -r $PACKAGE 2> /dev/null`
        if [ "$_RELOCATE_DIR" != "" ]
        then
	    _RELOCATE_DIR=${_RELOCATE_DIR}/SUNWesm
        fi

        # _RELOCATE_DEF is a last attempt default
        _RELOCATE_DEF=/opt/SUNWesm
    
        # Set the Location of the root of the tree 
        _ESM_HOME=${ESM_HOME:-${_RELOCATE_DIR:-$_RELOCATE_DEF}}
        export _ESM_HOME

        # Unset the variables we are no longer using
        unset _RELOCATE_DIR
        unset _RELOCATE_DEF

        if [ ! -d $_ESM_HOME ]
        then
	    echo "$progname: \c" >&2
            gettext $TEXTDOMAIN "Unable to locate root directory" >&2
	    echo " $_ESM_HOME" >&2
	    exit 1
        fi

    fi # [ "$_ESM_HOME" != "" ]
}

check_display()
{
    if [ -z "$DISPLAY" ]; then
	echo "$progname: \c" >&2
        gettext $TEXTDOMAIN "DISPLAY environment variable must be set" >&2
        echo "" >&2
        exit 1
    fi
    XHOST=/usr/openwin/bin/xhost
    if [ ! -x $XHOST ]; then
        XHOST=/usr/bin/X11/xhost
    fi
    if [ -x $XHOST ] ; then
        $XHOST >/dev/null 2>&1
        if [ $? -ne 0 ] ; then
	    echo "$progname: \c" >&2
            gettext $TEXTDOMAIN "Unable to open DISPLAY:" >&2
            echo " $DISPLAY" >&2
            exit 1
        fi
    fi
}


# Save off the argument list passed in
ARG_LIST=$*

# Setup locations / Variables
set_esm_home

if [ 0 -eq 1 ]
then
    check_display
fi

# Handle testing environement where esm_setup is not in sbin
if [ "$ESM_SETUP_HOME" != "" ]
then
    ESM_SETUP=$ESM_SETUP_HOME
else
    ESM_SETUP=$_ESM_HOME/sbin/esm_setup
fi

if [ -f $ESM_SETUP ]
then
    . $ESM_SETUP
fi

# Set the name of the message object file to be used for i18n
TEXTDOMAIN=${ESM_TEXTDOMAIN:-esm_cli}

# Set the location for the internationalization libraries
_TEXTDOMAINDIR=`pkgparam $PACKAGE BASEDIR 2> /dev/null ` 
if [ "$_TEXTDOMAINDIR" != "" ] 
then
    _TEXTDOMAINDIR=${_TEXTDOMAINDIR}/SUNWesm
fi
TEXTDOMAINDIR=${_TEXTDOMAINDIR:-${ESM_TEXTDOMAINDIR:-/usr/opt/SUNWesm}}/lib/locale
export TEXTDOMAINDIR

# handle error of ESM_SETUP not being defined here
if [ ! -f $ESM_SETUP ]
then
    echo "$progname: \c" >&2
    gettext $TEXTDOMAIN "Unable to locate esm_setup to configure environment" >&2
    echo >&2
    exit 4
fi


# Set the the variables that point to the root of the tree
set_pid_location 
set_lock_location

COMMAND_LINE_ARG=
LAST_ARG=
AS_A_CLIENT=

if [ "$ARG_LIST" != "" ]
then
    while [ $# -ne 0 ]
    do
	if [ 0 -eq 1 -a $# -eq 1 ]
	then
	    #  check one last time if invoked as a client
	    #
	    if [ "$AS_A_CLIENT" = "" ]
	    then
		case $1 in
		    -version | -V ) COMMAND_LINE_ARG="$COMMAND_LINE_ARG \"$1\""
				    LAST_ARG=$1
				    AS_A_CLIENT=true
				    ;;
		    # We are doing a start/stop script 
		    #
		    *)  EXECUTION=$1
			;;
		esac
	    else
		COMMAND_LINE_ARG="$COMMAND_LINE_ARG \"$1\""
		LAST_ARG=$1
	    fi
	else
	    COMMAND_LINE_ARG="$COMMAND_LINE_ARG \"$1\""
	    LAST_ARG=$1

	    #  check if invoking as a client
	    #
	    if [ "$AS_A_CLIENT" = "" ]
	    then
		case $LAST_ARG in
			-load | \
			-unload | \
			-enable | \
			-disable | \
			-stop | \
			-start | \
			-version | \
			-l | -U | -e | -u | -s | -S | -V )
		    AS_A_CLIENT=true
		    ;;
		esac
	    fi
	fi
	shift
    done
fi

if [ 0 -ne 1 ]
then
    if [ "$LAST_ARG" != "help" ]
    then
	EXECUTION=start
    else
	EXECUTION=help
    fi
fi

case x$EXECUTION in 
    'xstart') 
              do_start 
	      exit $?
              ;;
    'xhelp')
	      do_usage
              echo >&2
	      # Pass help to the java code
	      COMMAND_LINE_ARG="-help"
	      # Don't start jvm in backround
	      ESM_FOREGROUND=TRUE
	      do_start
              ;;
    'xstatus')do_stat
	      exit $?
	      ;;
    'xstop')  do_stop
	      exit $?
              ;;
    *)        if [ "$AS_A_CLIENT" != "" ]
	      then
		  do_client
		  exit $?
	      fi
	      do_usage
	      exit 2
	      ;;
esac

exit 0
