#!/bin/sh
#
#	Usage
#		progname [java_options] {start|stop|status|help}
#
#       java options will be passed to the java execution 
#		
#       required arguments:
#		start	Start the mc station
#		stop    Stop the mc station
#		status  Check to see if mc 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
#
#
#

# for NT these will be set
PATH=${CYGWIN_PATH}:/usr/bin:/usr/sbin:/sbin:/usr/ucb/bin

if [ "$PLATFORM" = "" ]
then
    PLATFORM=`uname -s 2>/dev/null`
fi

progname=`basename "$0"`

PKGINFO=pkginfo
PACKAGE=SUNWesm
cwd=`pwd`

# GetText replaces the Unix gettext on NT platforms. When localization is
# implemented, this will be modified perhaps back to gettext(GNU).
# The presence of a third parameter on NT supresses Event Log logging.

GetText()
{
    if [ "$PLATFORM" != "NT" ]
    then
        if [ $# -ge 2 ]
        then
            gettext "$1" "$2"
        else
            gettext "$1"
        fi
    else
        if [ $# -eq 3 ]
        then
            printf "$2"
        else
            eval ${_ESM_HOME}/sbin/esmErrLog.exe "$2"
        fi
    fi

}

# This function exits the script gracefully on an error.
script_exit()
{
    ERROR_CONDITION=$1
    # Unset common variables
    unset TEXTDOMAIN
    unset TEXTDOMAINDIR
    exit $ERROR_CONDITION
}

STATIONDIR=mc

# Output usage
do_usage ()
{

    # Allow script to be multi-use
    if [ 0 -eq 0 ]
    then
        eval echo "\"`GetText $TEXTDOMAIN 'Usage: $progname: [java options] {start|stop|status|help} \n\n'\
'       java options will be passed to the executing java class\n'\
'       required arguments:\n'\
'		start	Start the $STATIONDIR station\n'\
'		stop    Stop the $STATIONDIR station\n'\
'		status  Check $STATIONDIR station status\n'\
'		help    Provide usage for the startup script and $STATIONDIR station\n' 'INFORMATIONAL'`\"" >&2
    else
       eval echo "\"`GetText $TEXTDOMAIN 'Usage: $progname: [java options] \n\n'\
'       java options will be passed to the executing java class\n'\
'       required arguments:\n'\
'		help    Provide usage for the startup script and $STATIONDIR station\n' 'INFORMATIONAL'`\"" >&2
    fi

}

# 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`
            if [ "$PLATFORM" != "NT" ]
               then
                  /usr/ucb/ps auxwwww | grep "com.sun.esm.apps.AppBoot" | grep -v grep > /dev/null 2>&1

               else
                  ps | grep $PID > /dev/null 2>&1
            fi
	    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 [ 1 -eq 1 ]
    then
        do_stat 
	return $?
    fi # [ 1 -ne 1 ]
    return 1
}

#verify if agent

verify_if_agent()
{
    if [ 0 -eq 1 ]
    then
        ESM_JAVA_ARG="$ESM_JAVA_ARG -Djdmk.acl.file=$_ESM_RT_HOME/etc/opt/SUNWesm/snmp/esm_jdmk.acl"
    fi
    return 1
}

# set up environment
env_setup()
{
	if [ "$PLATFORM" != "NT" ]
	then
		ulimit -n 12288
	fi
}

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

    env_setup

    COMMAND="$_ESM_JAVA_START $ESM_JAVA_ARG com.sun.esm.apps.AppBoot -R $_ESM_RT_HOME/ \
            $COMMAND_LINE_ARG"


    #
    #  this is the critical section of the code -
    #
    #  In a unix system, need to make sure that /etc/nsswitch.conf will
    #  not cause unnecessary timeouts.  This is handled by using the
    #  'esm_nonet' script.
    #
    _network_started='no'

    if [ "$PLATFORM" != "NT" ]
    then
	ps -e -o args | grep -v grep | grep "^/usr/sbin/inetd -s" > \
							/dev/null 2>&1
	[ $? -eq 0 ] && _network_started='yes'

	if [ "$_network_started" = 'no' ]
	then
	    #
	    #  source the file with all the logic to handle the
	    #  modifications to the /etc/nsswitch.conf
	    #
	    . $_ESM_HOME/sbin/esm_nonet

	    trap nsswitch_sighandler 1 2 3 15

	    replace_nsswitch
	fi
    fi

    #
    if [ "$ESM_FOREGROUND" != "" ]
    then
	eval $COMMAND
    else
	if [ 1 -ne 1 ]
        then
            eval $COMMAND
        else
	    # create lock that will be cleared by station

	    if [ "esm_mcboot" = "esm_moboot" -o "esm_mcboot" = "esm_mcboot" ]
	    then
		> $LOCK_LOCATION
	    fi

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

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

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

    RETVAL=$?

    #
    #  revert the state of /etc/nsswitch.conf to what it was previously
    #  
    [ "$PLATFORM" != "NT" -a "$_network_started" = 'no' ] && restore_nsswitch

    return $RETVAL
}

# 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
        else
            if [ "$PLATFORM" != "NT" ]
            then
                kill -0 $PID > /dev/null 2>&1
            else
                ps | grep $PID > /dev/null 2>&1
            fi
            if [ $? -ne 0 ]
            then
                eval echo "\"`GetText $TEXTDOMAIN '$progname: Notice: Unable to locate process id\n'\
'            Info: Station may have died prematurely'`\"" >&2
                rm $PID_LOCATION > /dev/null 2>&1
                rm $LOCK_LOCATION > /dev/null 2>&1
                break
            fi
	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
    eval echo "\"`GetText $TEXTDOMAIN '$progname: Error: Did not start completely.'`\"" >&2
    exit 4

}

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

# 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
        if [ "$PLATFORM" != "NT" ]
           then
              kill -0 $PID > /dev/null 2>&1
           else
              ps | grep $PID > /dev/null 2>&1
        fi
	    if [ $? -ne 0 ]
	    then
	        eval echo "\"`GetText $TEXTDOMAIN '$progname: Notice: Unable to locate process id $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
	                eval echo "\"`GetText $TEXTDOMAIN '$progname: Notice: Unable to kill process id $PID '`\"" >&2
		    fi
		fi # -HUP
            fi # -TERM

        else
	    killproc com.sun.esm.apps.AppBoot
        fi
    else
	killproc com.sun.esm.apps.AppBoot
    fi
    #$JAVA_HOME $JAVA_CLASSPATH com.sun.esm.apps.AppBoot -stop &
}

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

    COMMAND="$_ESM_JAVA_START $ESM_JAVA_ARG com.sun.esm.apps.AppBoot -R $_ESM_RT_HOME/ \
            $COMMAND_LINE_ARG"


    #  In a unix system, need to make sure that /etc/nsswitch.conf will
    #  not cause unnecessary timeouts.  This is handled by using the
    #  'esm_nonet' script.
    #
    _network_started='no'

    if [ "$PLATFORM" != "NT" ]
    then
	ps -e -o args | grep -v grep | grep "^/usr/sbin/inetd -s" > \
							/dev/null 2>&1
	[ $? -eq 0 ] && _network_started='yes'

	if [ "$_network_started" = 'no' ]
	then
	    #
	    #  source the file with all the logic to handle the
	    #  modifications to the /etc/nsswitch.conf
	    #
	    . $_ESM_HOME/sbin/esm_nonet

	    trap nsswitch_sighandler 1 2 3 15

	    replace_nsswitch	# perform possible /etc/nsswitch.conf mods
	fi
    fi

    eval $COMMAND

    RETVAL=$?

    #
    #  revert the state of /etc/nsswitch.conf to what it was previously
    #  
    [ "$PLATFORM" != "NT" -a "$_network_started" = 'no' ] && restore_nsswitch

    return $RETVAL
}

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

# Set the location of the lock file
set_lock_location ()
{
	
    case "esm_mcboot"
    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 [ 1 -eq 1 ]
    then
        LOCK_LOCATION=$_ESM_RT_HOME/var/opt/SUNWesm/etc/mc/
        if [ ! -d $LOCK_LOCATION ]
        then
	    mkdir -p $LOCK_LOCATION > /dev/null 2>&1
	    if [ $? -ne 0 ]
	    then
                eval echo "\"`GetText $TEXTDOMAIN '$progname: Unable to locate lock directory $LOCK_LOCATION'`\"" >&2
	        LOCK_LOCATION=
	    else
	        LOCK_LOCATION=$_ESM_RT_HOME/var/opt/SUNWesm/etc/mc/$LOCK_NAME
	    fi
        else
	    LOCK_LOCATION=$_ESM_RT_HOME/var/opt/SUNWesm/etc/mc/$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. For NT it is always set

    # 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
        if [ "$PLATFORM" != "NT" ]
            then _RELOCATE_DIR=`${PKGINFO} -r $PACKAGE 2> /dev/null`
        fi
        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
            eval echo "\"`GetText $TEXTDOMAIN '$progname: Unable to locate root directory $_ESM_HOME'`\"" >&2
	    script_exit 1
        fi

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

check_display()
{
    if [ -z "$DISPLAY" ]; then
        echo ""
        eval echo "\"`GetText $TEXTDOMAIN '$progname: DISPLAY environment variable must be set'`\""
        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
            eval echo "\"`GetText $TEXTDOMAIN '$progname: Unable to open DISPLAY: $DISPLAY'`\""
            exit 1
        fi
    fi
    ESM_JAVA_ARG="$ESM_JAVA_ARG -DDISPLAY=$DISPLAY"
}


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

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

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

# Setup locations / Variables
set_esm_home

if [ 0 -eq 1 ]
then
    if [ "$PLATFORM" != "NT" ]
    then
         check_display
    fi
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
    _STAT_TYPE=mc

    #
    #  preserve the variables that may be modified inside of ESM_SETUP
    #
    _save_progname=$progname
    _save_TEXTDOMAIN=$TEXTDOMAIN
    _save_TEXTDOMAINDIR=$TEXTDOMAINDIR

    . $ESM_SETUP 
    unset _STAT_TYPE

    #
    #  restore the variables that may be modified inside of ESM_SETUP
    #
    progname=$_save_progname
    TEXTDOMAIN=$_save_TEXTDOMAIN
    TEXTDOMAINDIR=$_save_TEXTDOMAINDIR
fi

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

check_valid_user
case $? in
    1) ;;
    *) eval echo "\"`GetText $TEXTDOMAIN '$progname: user has no privilege to run $progname'`\"" >&2
       exit 5
       ;;
esac

# 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=

#
#  helper variable to indicate whether the network has been started
#
_network_started=

if [ "$ARG_LIST" != "" ]
then
    while [ $# -ne 0 ]
    do
	if [ 1 -eq 1 -a $# -eq 1 ]
	then
	    #  check one last time if invoked as a client
	    #
	    if [ "$AS_A_CLIENT" = "" ]
	    then
		case $1 in
		    -command | -p | -port | -mohosts | -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 | \
			-command | \
			-disable | \
			-stop | \
			-start | \
			-version | \
			-isloaded | \
			-mohosts | \
			-port | \
			-p | -I | -l | -U | -e | -u | -s | -S | -V )
		    AS_A_CLIENT=true
		    ;;
		esac
	    fi
	fi
	shift
    done
fi

if [ 1 -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
