#!/bin/bash
#----------------------------------------------------------------------------
#
# desta
#
# This Bash shell script starts DESTA processes. It exports the
# environment variables we need, then starts the java vm
# (unless overridden), passing optional parameters.
#
# Usage:
# (not all of these are shown in the Usage echo's below, to hide the
# options intended for expert users)
#
# desta [help]
#     Show this help.
# desta start [compete|nice <number>] | [wccproxy]
#     Start the DESTA Director process.
#     compete arg specifies to start director process at a higher priority
#     to compete with other system processes.
#     nice arg allows user to specify nice level of director process.
#     negative numbers indicate higher priority. See the nice man page for
#     further explanation.
#     If the command is 'desta start wccproxy' then the script will start 
#     the WCCProxy program and exit, the director will not be started.
# desta stop [wccproxy]
#     Shut down the DESTA Director process and all DESTA-connected processes.
#     If the command is 'desta stop wccproxy' then the script will stop 
#     the WCCProxy program and exit, the director will not be stopped.
# desta status [wccproxy]
#     Shows the status of the DESTA Director process.
#     If the command is 'desta status wccproxy' then the status of both
#     the director and the WCCProxy program are displayed.
# desta priority [compete|low]
#     Shows the system priority of the DESTA Director process
#     compete or low option changes priority of director process.
# desta bldknw
#     Rebuild frame knowledge from all *Knowledge.jar files.
# desta msg [args]
#     Drive the SendDESTAMsg class (see Java code).
# desta dri [args]
#     (DESTA Registry Interface) Drive the DESTAReg class.
# desta exec [com.compaq.myproject.mypackage.MyClass [args]]
#     Invokes the main() method of the given fully qualified class
#     (MyClass in this example), passing the given args to main().
#     The class must be accessible through either the CLASSPATH or the
#     SVCTOOLS_PATH environment variable (see below).
#
# You can set the following environment variables to change the behavior.
# This script will assign them to proper installed defaults if not set
# by the user.
#
# SVCTOOLS_HOME
#     The top-level directory of Compaq Service Tools. By default,
#     assigned to the parent directory of this script's real directory
#     (symbolic links are followed to arrive at the script's real
#     directory).
#
# DESTA_CMD
#     The DESTA executable command line to run, allowing you to add 
#     command-line options to or use a different Java VM
#     (see comments where this is addressed below).
#
# DESTA's Use Of CLASSPATH :
#
# The "desta" script, will create the Java CLASSPATH for this process
# based on default behavior that can be modified by the user
# (any caller of this script, which could be another script).
# The CLASSPATH will contain (in order):
#
# 1. The $SVCTOOLS_PATH_EXTRA, if defined by the user (see below).
# 2. The base Java .jar files contained in the JRE bundled with DESTA
#    in the $SVCTOOLS_HOME/common/jre directory tree, by default. Can be
#    overriden by defining DESTA_JAVA (see below).
# 3. The $SVCTOOLS_PATH, created here or overriden by the user (see below). 
# 
# CLASSPATH
#     Any existing CLASSPATH will be *ignored* by this script! This is to
#     prevent corruption of DESTA's CLASSPATH by unrelated classes that
#     the user has defined on the CLASSPATH. To explicitly add classes to
#     DESTA's CLASSPATH, define SVCTOOLS_PATH_EXTRA (below). To override
#     the default jars used by DESTA, override SVCTOOLS_PATH (below).
#
# DESTA_JAVA
#     If you wish to use base Java classes of a JDK or JRE other than the
#     JRE installed with DESTA, assign DESTA_JAVA to the base directory
#     of the installed JDK or JRE. (For example, the Tru64 UNIX JDK 1.1.x
#     base directory is /usr by default.)
#
# SVCTOOLS_PATH
#     The colon-separated list of directories and/or .jar files containing
#     all Service Tools' class files. By default, assigned to be all
#     .jar files in the $SVCTOOLS_HOME/common/jars directory. Define SVCTOOLS_PATH
#     only if there is a reason *not* to use the .jar files in
#     $SVCTOOLS_HOME/common/jars.
#
# SVCTOOLS_PATH_EXTRA
#     The colon-separated list of directories and/or .jar files containing
#     additional Java classes not found in $SVCTOOLS_HOME/common/jars but required
#     by this process. Empty by default. If set by the user, the contents 
#     will be prepended to the CLASSPATH created by DESTA.
#
# DESTA's Use Of LD_LIBRARY_PATH :
#
# The "desta" script will create the LD_LIBRARY_PATH for this process based
# on default behavior that can be modified by the user (any caller of this
# script, which could be another script). The LD_LIBRARY_PATH will contain
# (in order):
#
# 1. The $SVCTOOLS_SHARE_EXTRA, if defined by the user (see below).
# 2. The Java shared library directory contained in the JRE bundled with
#    DESTA in the $SVCTOOLS_HOME/common/jre directory tree, by default. Can be
#    overriden by defining DESTA_JAVA (see below).
# 3. The $SVCTOOLS_SHARE, created here or overriden by the user
#    (see below). 
# 
# LD_LIBRARY_PATH
#     Any existing LD_LIBRARY_PATH will be *ignored* by this script! This
#     is to prevent corruption of DESTA's LD_LIBRARY_PATH by identically
#     named but different shared object libraries in directories that the
#     user has defined on the LD_LIBRARY_PATH. To explicitly add shared
#     library directories to DESTA's LD_LIBRARY_PATH, define 
#     SVCTOOLS_SHARE_EXTRA (below). To override the default directory
#     used by DESTA, override SVCTOOLS_SHARE (below).
#
# DESTA_JAVA
#     If you wish to use a base Java shared library directory in a JDK or 
#     JRE other than the JRE installed with DESTA, assign DESTA_JAVA to the 
#     base directory of the installed JDK or JRE. (For example, the Tru64
#     UNIX JDK 1.1.x base directory is /usr by default.)
#
# SVCTOOLS_SHARE
#     The colon-separated list of directories containing all Service 
#     Tools' shared object files. By default, assigned to be the directory
#     $SVCTOOLS_HOME/common/share. Define SVCTOOLS_SHARE only if there is a reason
#     *not* to use the shared objects in the default directory, but also be
#     aware that the installation of DESTA products creates symbolic links
#     to its libraries in /usr/shlib. These links will be found in the 
#     absence of LD_LIBRARY_PATH, unless those links are changed/moved.
#
# SVCTOOLS_SHARE_EXTRA
#     The colon-separated list of directories containing additional shared
#     objects not found in $SVCTOOLS_HOME/common/share but required by this
#     process. Empty by default. If set by the user, the contents will be
#     prepended to the LD_LIBRARY_PATH created by DESTA.
#
# DESTA Status File
#     The Director creates a status file at startup which contains the status
#     of the director. This script kicks off the Director process and then
#     checks the contents of the status file to see if the director has 
#     started correctly. It then displays a message to the console informing
#     the user if the director started correctly or not. 
#----------------------------------------------------------------------------
# Uncomment this line to show what's going on, or (better) use the
# desta_g debug variant of this script instead (located in the same 
# directory as the desta script).
#set -x

# Make all new files have no permissions for group and world.
#umask 077

# Remove all exported aliases so that ksh built-in commands do what we
# expect them to do.
#unalias -a

#
# Linux doesn't have a /var/adm dir by default.
# If this dir doesn't exist then create it so
# that many Webes features will work.
#
if [ ! -d /var/adm ]
then
    mkdir /var/adm
    chmod 755 /var/adm
    chgrp root /var/adm
    chown root /var/adm
fi

ReadRegistry ()
#  Read the` value associated with the specified key in the registry.
{
    REGISTRY_FILE=$SVCTOOLS_HOME/specific/desta/config/DESTA.REG
    if [ -r $REGISTRY_FILE ]
    then
        REGISTRY_VALUE=`/bin/grep "^ *$REGISTRY_KEY *=" $REGISTRY_FILE`
        REGISTRY_VALUE=`echo $REGISTRY_VALUE | /bin/sed 's/.*= *//'`
        REGISTRY_VALUE=`echo $REGISTRY_VALUE | /bin/sed 's/ *$//'`
    fi
}


#  Build the DESTA environment variables based on the real location of
#  this shell script, or the user's overrides.

#  Derive the SVCTOOLS_HOME environment variable if not overridden, and
#  validate the directory.
STARTING_DIR=`/bin/pwd`
if [ "$SVCTOOLS_HOME" = "" ]
then
    #  Find my real directory, even if $0 is really a symbolic link
    MYREALDIR=`/bin/ls -l $0 | /bin/cut -f 2 -d '>' | /bin/cut -f 2 -d ' '`

    if [ "$MYREALDIR" = "" ]; then
        # Not a symbolic link
        SVCTOOLS_HOME=`/usr/bin/dirname $0`/../..
    else
        # Symbolic link, use the directory to which it points
        SVCTOOLS_HOME=`/usr/bin/dirname $MYREALDIR`/../..
    fi
fi

if [ ! -d "$SVCTOOLS_HOME" ]
then
    echo "$0 Error: $SVCTOOLS_HOME directory does not exist."
    exit 642
fi
#  The following is to fix an anomaly whereby if this script is executed
#  in a dir below where SVCTOOLS_HOME is to be, it ends up getting 
#  assigned a relative path instead of an absolute which can cause
#  problems if a class file is expecting and requires an absolute path.
cd $SVCTOOLS_HOME
SVCTOOLS_HOME=`/bin/pwd`
cd $STARTING_DIR
export SVCTOOLS_HOME

if [ "$SVCTOOLS_PATH" = "" ]
then
    #  Build SVCTOOLS_PATH by looking for all jar files in the jars directory.

    SVCTOOLS_PATH=`/bin/ls $SVCTOOLS_HOME/common/jars/*.jar | /usr/bin/tr "\n" ":"`
    if [ "$SVCTOOLS_PATH" = "" ]
    then
	echo "$0 Error: Could not find the Service Tools installed jar files."
	exit 650
    fi
    export SVCTOOLS_PATH
fi
export CLASSPATH=$SVCTOOLS_PATH_EXTRA:$SVCTOOLS_PATH

#  Define the directory for DESTA shared libraries, if not defined already.
if [ "$SVCTOOLS_SHARE" = "" ]
then
    SVCTOOLS_SHARE=$SVCTOOLS_HOME/common/share
fi
#  Define the directory for WCCProxy shared libraries, if not defined already.
if [ "$SVCTOOLS_WCCPROXY_SHARE" = "" ]
then
    SVCTOOLS_WCCPROXY_SHARE=$SVCTOOLS_HOME/common/wccproxy/share
fi
export LD_LIBRARY_PATH=$SVCTOOLS_WCCPROXY_SHARE:$SVCTOOLS_SHARE_EXTRA:$SVCTOOLS_SHARE

#  Export the directory for the SWCC home, if not defined already.
#  This is a temporary solution for Compaq Analyze. It's not a good thing
#  to add code to DESTA scripts required by non-Common-Components code.

if [ "$SWCC_HOME" = "" ]
then
    export SWCC_HOME=/var/adm
fi

#  Find the correct java command

if [ "$DESTA_JAVA" = "" ]; then
   export JAVA_HOME=$SVCTOOLS_HOME/common/jre
else
   export JAVA_HOME=$DESTA_JAVA
fi

if [ ! -x "$JAVA_HOME/bin/jre" -a ! -x "$JAVA_HOME/bin/java" ]
then
    echo "$0 Error: Could not find Java environment."
    exit 658
fi

#  If you wish to pass command-line options to the java vm or Desta you can
#  assign DESTA_CMD (before you run this script) to include them, such as:
#      DESTA_CMD=java -version
#  If you wish to run something other that the DESTAController such as the
#  DESTADriver wrapper class, you can assign DESTA_CMD (before you run 
#  this script) such as:
#      DESTA_CMD=java -nojit com.compaq.svctools.desta.cli.DESTADriver
#  You should then update the DESTA Registry's desta.Subprocess.CommandLine
#  key as appropriate.

if [ "$DESTA_CMD" = "" ]
then
# I do not belive linux has this ? 
#    SetAffinity
    DESTA_CMD_NO_PREFIX="$JAVA_HOME/bin/java  -noverify -DSvctools.Home=$SVCTOOLS_HOME -DSwcc.Home=/var/adm"
    DESTA_CMD="$RUNON_PREFIX$DESTA_CMD_NO_PREFIX"
    # echo $DESTA_CMD
    DESTA_CMD_STANDARD=true

else 

    #  Use the user's DESTA_CMD  settings instead.
    DESTA_CMD_STANDARD=false
fi

# The Director's status file
STATUS_FILE=$SVCTOOLS_HOME/specific/desta/data/DESTA.stat

# The JNIRoot Launcher executable
WCCPROXY_EXE=WCCProxy

# The JNIRoot Launcher PID file
WCCPROXY_PID_FILE=$SVCTOOLS_HOME/specific/wccproxy/data/wccproxy.pid

# Set the ulimit to well below the value that causes WEBES processes to 
# crash with segmentation violations (around 3,500,000) and lower than
# the 4,194,304 default value on Sierra clusters that causes the Java VM
# to refuse to run, claiming the stack limit is too high.
# We don't actually need it any higher than the default e.g. 2048 on
# Unix 4.x non-clustered machines, we do this only to prevent the too-high
# error from the Java VM.
ulimitsMAX=1000000
ulimitsNOW=`ulimit -s`
# check if the stack limit is "unlimited"
if [ $ulimitsNOW = unlimited ]
then
    ulimitsNOW=$ulimitsMAX
else
    # Ensure integer format for ulimitsNOW
    # this printf call uses the format string %15.0f
    # because sometimes the number is so large that ulimit 
    # returns it in scientific notation, like 2.345e+09
    # using the floating point format string ensures an integer 
    # format so that the comparison work.
    ulimitsNOW=`/usr/bin/printf "%15.0f" $ulimitsNOW`
fi
if [ $ulimitsNOW -ge $ulimitsMAX ]
then
    ulimit -s $ulimitsMAX
fi

# How long (in seconds) this script waits for the Director to start 
# before aborting
DESTA_TIMEOUT=80
# How long (in seconds) this script waits for the Director to start 
# before reassuring the user that we're still waiting.
DESTA_REASSURE=20

#  Checks for the Director's PID in the process table
#  RETURNS the exit status of the ps call
function checkDirProcess {
    PID=`head -n 2 $STATUS_FILE | tail -n 1 `
    #ps -ef|grep $PID|grep -v grep | grep jre | grep -q DESTAController 
    #ps p $PID $PID| grep -q DESTAController 
    ps --pid $PID   >>/dev/null
    # $? is 0 if a PID is found, > 0 if no PID found
    return $?
}


#  Gets the state of the DESTA Director process (running or not)
#  RETURNS an integer - the state value. 
#  STATE can have the following values. These state values are the same for
#  UNIX, VMS and NT.
#   99 => unknown state
#   1  => Director is not running
#   9  => Director status file says it's running, but the PID was not found
#   3  => Director is running
#   5  => Director is starting up
#   7  => Director is shutting down

function getDirectorState {
    typeset STATE  # local variable
    STATE=99   # unknown state
            
    # If the state file doesn't exist, assume the director is not running
    if [ ! -e $STATUS_FILE ]  
    then
        STATE=1   # not running
    else
        STATUS=`head -n 1 $STATUS_FILE` # Get the first line
        if [ "$STATUS" = "SYSTEM_UP" ]
        then
            # Status file says director is up, check if the PID is 
            # in the process table
            checkDirProcess
            CHECK=$?
            if ((!$CHECK))
            then
                STATE=3    # Running
            else
                STATE=9    # Not running
            fi	
        elif [ "$STATUS" = "SYSTEM_STARTING" -o "$STATUS" = "PID" ]
        then
            checkDirProcess
            CHECK=$?
            if ((!$CHECK))
            then
                STATE=5    # Starting
            else
                STATE=9    # Not running
            fi
        elif [ "$STATUS" = "SYSTEM_SHUTDOWN" ]
        then
            checkDirProcess
            CHECK=$?
            if ((!$CHECK))
            then
                STATE=7    # Shutting down
            else
                STATE=9    # Not running
            fi
        elif [ "$STATUS" = "SYSTEM_DOWN" -o "$STATUS" = "SYSTEM_ERROR" ]
        then
            STATE=1    # Not running
        fi
    fi
    return $STATE
}

function setProcessUlimit {
    # Compute 1/2 of current total swap file allocation and
    # Set addressspace/vmemory hard limit for this process and children
    # Unless current limit is lower

    # Also set the data segment limit to be the lesser of the virtual 
    # memory limit or the system's hard limit for the data segment

    # printf calls in this function use the format string %15.0f
    # because sometimes the number is so large that ulimit 
    # returns it in scientific notation, like 2.345e+09
    # using the floating point format string ensures an integer 
    # format so that the comparisons work.

    ulimitvOLD=`ulimit -v`

    ulimitvNEW=`/sbin/swapon -s | \
	/bin/grep partition | \
	/bin/awk '{print $3/2}'
        #-F[(MG]' \
	#'/MB/{print $3*1000/2} \
	#/GB/{print $3*1000000/2}'`
    # Ensure integer format for ulimitvNEW
    ulimitvNEW=`/usr/bin/printf "%15.0f" $ulimitvNEW`

    # check if the VM limit is "unlimited"
    if [ $ulimitvOLD = unlimited ]
    then 
		# set VM limit equal to the computed VM limit.
		ulimitvOLD=$ulimitvNEW
	else
		# it's not unlimited
		# Ensure integer format for ulimitvOLD
		ulimitvOLD=`/usr/bin/printf "%15.0f" $ulimitvOLD`
    fi
    ulimitdHARD=`ulimit -H -d`
    # check if the hard data limit is "unlimited"
    if [ $ulimitdHARD = unlimited ]
    then
        # set the data hard limit to the lesser of the system's virtual memory
        # limit or the computed virtual memory limit
        if [ $ulimitvOLD -gt $ulimitvNEW ]
        then
            ulimitdHARD=$ulimitvNEW
        else
            ulimitdHARD=$ulimitvOLD
        fi
    fi
    # Ensure integer format for ulimitdHARD
    ulimitdHARD=`/usr/bin/printf "%15.0f" $ulimitdHARD`
    if [ $ulimitvOLD -gt $ulimitvNEW ]
    then
        ulimit -v $ulimitvNEW
        # Now set data segment limit
        if [ $ulimitvNEW -gt $ulimitdHARD ]
        then
	    ulimit -d $ulimitdHARD
        else
    	    ulimit -d $ulimitvNEW
        fi
    else
        if [ $ulimitvOLD -gt $ulimitdHARD ]
        then
            ulimit -d $ulimitdHARD
        else
            ulimit -d $ulimitvOLD
        fi
    fi
}

wccproxy_start () 
{
    cd $SVCTOOLS_HOME/common/wccproxy/bin
    ./wccproxy start
    cd $OLDPWD
}

wccproxy_stop ()
{
    cd $SVCTOOLS_HOME/common/wccproxy/bin
    ./wccproxy stop
    cd $OLDPWD
}


desta_dir_stop ()
{
   SLEEPS=0
   while true
   do
      if [ $SLEEPS = 0 ]; then
         $DESTA_CMD com.compaq.svctools.desta.cli.SendDESTAMsg -stop $RUNON_POSTFIX
      fi

      # Are there any Controller (main) or Wrapper (subprocess) processes
      # still running?
      MAIN_PROC="`/bin/ps -ef | /bin/egrep 'DESTAController$' | /bin/grep -v grep`"
      SUB_PROCS="`/bin/ps -ef | /bin/egrep 'DESTAProcessWrapper$' | /bin/grep -v grep`"

      if [ -z "$MAIN_PROC" -a -z "$SUB_PROCS" ]; then
         break
      fi

      # If we've waited 10 seconds and it still hasn't stopped, 
      # reassure the user we're still waiting.
      if [ $SLEEPS -eq 5 ]; then
         echo "Director in shutdown phase 2."
      fi

      # If we've waited 30 seconds and it still hasn't stopped, kill it.
      if [ $SLEEPS -eq 15 ]; then
         # get a list of processes and kill them all
         echo "Normal desta stop failed, killing Director processes."
         MAIN_PROC_PID="`/bin/ps -ef | /bin/egrep 'DESTAController$' | /bin/grep -v grep | /usr/bin/awk '{print \$2}'`"
         if [ -n "$MAIN_PROC_PID" ]; then
            for PROCESS in $MAIN_PROC_PID; do
               echo "Killing Director process $PROCESS."
               kill -9 ${PROCESS}
            done
         fi
         # probably no subprocesses anymore, but check anyway
         SUB_PROC_PIDS="`/bin/ps -ef | /bin/egrep 'DESTAProcessWrapper$' | /bin/grep -v grep | /usr/bin/awk '{print \$2}'`"
         if [ -n "$SUB_PROC_PIDS" ]; then
            for PROCESS in $SUB_PROC_PIDS; do
               echo "Killing Director subprocess $PROCESS."
               kill -9 ${PROCESS}
            done
         fi
         break
      fi

      sleep 2
      SLEEPS=`expr $SLEEPS + 1`
   done

   # Remove the lock file for this daemon so that Linux shutdown doesn't
   # try to stop it.
   rm -f /var/lock/subsys/desta
}

case "$1" in

    'status')
        # Print out the status of the Director
        
        getDirectorState
        DIRSTATE=$?
        case "$DIRSTATE" in
        99)
            echo "The Director's status could not be determined."
            ;;
         1)
            echo "The Director is NOT running."
            ;;
         9)
            echo "The Director's status file indicates it is running, but"
            echo "the process ID was not found, so the Director process is"
            echo "NOT running."
            ;;
         3)
            echo "The Director is running"
            ;;
         5)
            echo "The Director is starting up"
            ;;
         7)
            echo "The Director is shutting down"
            ;;
        esac 

	# if the command is 'desta status wccproxy' we will print out the 
	# status of the WCCProxy program also.
	if [ "$2" = "wccproxy" ]
	then 
	    $SVCTOOLS_HOME/common/wccproxy/bin/wccproxy status
	fi
	exit $DIRSTATE
        ;;
	'priority')	    
	# Checks or sets the system priority of the director process.
	# USAGE:	    
	# 'desta priority' simply prints out the director's PID, 	    
	# priority and nice level and exits.
	#	    
	# 'desta priority compete' renices the director's priority to a 
	# nice level of 0. This allows the director process to compete
	# on a level playing field with other system processes.
	#	    
	# 'desta priority low' renices the director process to a nice level
	# of 10. This is the default priority for the director process.
	#
        # First check to see if a Director is already running
        getDirectorState
        STATE=$?
        if (($STATE == 1 || $STATE == 9)) # Director not running
        then
                echo "The Director process is NOT running."
                exit 0
        fi
	
		PID=`sed -n '2p' $STATUS_FILE` 
		typeset -i PRI
		typeset -i NICE
		typeset -i NICEPARAM
		PRI=`ps -e -o pid,pri,nice|grep $PID|gawk '{print $2}'`
		NICE=`ps -e -o pid,pri,nice|grep $PID|gawk '{print $3}'`
		echo "Director PID = $PID. Priority = $PRI. Nice level = $NICE."
		if [ "$2" = "compete" ]
		then
			echo "resetting director process priority to 'compete'"
			NICEPARAM=-$NICE
			`renice -n $NICEPARAM $PID`
		elif [ "$2" = "low" ]
		then
			echo "resetting director process priority to 'low'"
			NICEPARAM=10-$NICE
			`renice -n $NICEPARAM $PID`
		fi
	;;	
    'start')

        # start can only be executed if user has correct permissions
        if [ ! -w $SVCTOOLS_HOME/specific/desta/data ]
        then
            echo ""
            echo "You do not have the permissions required to start the"
            echo "Desta Director."
            echo ""
            exit 0
        fi

	# if the command is 'desta start wccproxy' then start the WCCProxy program 
	# and exit.
	if [ "$2" = "wccproxy" ]
	then
		wccproxy_start
		exit 0
	   fi

	#  Start the DESTA Director process
	
	# First check to see if a Director is already running
	getDirectorState
	STATE=$?
	if (($STATE > 1 && $STATE < 9)) 
	then
		echo "The Director process is currently running, cannot start another."
		exit 1
	fi

	# Start the JNIRoot launcher program
	  wccproxy_start

	# Check if the user wants to manipulate the director process' 
	# priority.
	if [ "$2" = "nice" ]
	then
	    if (($# < 3)) # Check for three parameters
	    then
		echo "You must specify a nice level when using the nice option."
		echo "Using default nice level."
		NICE="nice"
	    else #TODO Linux
		# check that $3 is a number (negative numbers are OK)
		#if [[ $3 = ?([+-])+([[:digit:]]) ]]
		#then
		#    NICE="nice -n $3"
		#else
		#    echo "Nice level must be a number."
		#    echo "using default nice level"
		    NICE="nice"
		#fi
	    fi
	elif [ "$2" = "compete" ]
	then
		NICE=""
	else
        	NICE="nice"
	fi	
        if [ "$DESTA_CMD_STANDARD" = "true" ]
        then

            if [ "$RUNON_PREFIX" = "" ]
            then
                #  Not using the runon prefix.
                #  Make sure "runon" is not in the subprocess command
                #  line either.
                SUBPROC_REG_KEY=desta.Subprocess.CommandLine
                SUBPROC_REG_KEYVAL=`$0 dri GET $SUBPROC_REG_KEY`
                SUBPROC_REG_UNDEF=`echo $SUBPROC_REG_KEYVAL | /bin/cut -f 2 -d '='`
                SUBPROC_RUNON=`echo $SUBPROC_REG_KEYVAL | /bin/grep runon`

                if [ -z "$SUBPROC_REG_UNDEF" -o \
                     "$SUBPROC_REG_UNDEF" = "null" -o \
                     -n "$SUBPROC_RUNON" ]
                then
                    #  The subprocess command line has "runon" in it,
                    #  or the DRI entry isn't defined. Fix it.
                    echo "Resetting subprocess command line..."
                    $0 setsub
                    echo "Reset complete."
                fi
                
            else
            
                #  Check the processor ID that we'll bind subprocesses to.
                #  This information is stored in the DESTA Registry.
                #  It's part of the subprocess launch command line, e.g.:
                #  desta.Subprocess.CommandLine=runon 0 ...
                #  ...where "0" is the CPU ID
                SUBPROC_REG_KEY=desta.Subprocess.CommandLine
                SUBPROC_REG_KEYVAL=`$0 dri GET $SUBPROC_REG_KEY`
                SUBPROC_CPU=`echo $SUBPROC_REG_KEYVAL | /bin/cut -f 2 -d '=' | /bin/cut -f 2 -d ' '`
    
                if [ ! "$SUBPROC_CPU" = "$RUNNING_CPU" ]
                then
                    #  The subprocess command line has a different 
                    #  processor ID, or the DRI entry isn't defined.
                    #  Fix it.
                    #  (The ID can differ if a CPU is stopped, restarted,
                    #  or changed.)
                    echo "Updating subprocess command line to run on CPU $RUNNING_CPU."
                    $0 setsub
                    echo "Update complete."
                fi
            fi
        fi
	# Check if there is a max heap size in the DESTA.REG file for the director.
	MAXHEAP_REG_KEY=desta.director.maxHeapSize
        MAXHEAP_REG_KEYVAL=`$0 dri GET $MAXHEAP_REG_KEY`
	MAXHEAP_REG_UNDEF=`echo $MAXHEAP_REG_KEYVAL | /bin/cut -f 2 -d '='`
	if [ ! -z "$MAXHEAP_REG_UNDEF" -a \
             "$MAXHEAP_REG_UNDEF" != "null" ]
	then
		# if the user has specified a $DESTA_CMD environment variable, we will not modify it.
		# else, tack on the max heap setting switch (-Xmx)
		if [ "$DESTA_CMD_STANDARD" = "true" ]
		then
			DESTA_CMD_NO_PREFIX="$DESTA_CMD_NO_PREFIX -Xmx$MAXHEAP_REG_UNDEF"
		fi
        else
                # use the default
                DESTA_CMD_NO_PREFIX="$DESTA_CMD_NO_PREFIX -Xmx340M"
	fi
            
        echo "Starting DESTA Director process."

        LOGFILE=desta_dir.log
        DESIRED_LOGDIR=$SVCTOOLS_HOME/specific/webes/logs
        DESIRED_LOGPATH=$DESIRED_LOGDIR/$LOGFILE
        ALTERNATE_LOGPATH=./$LOGFILE

        if [ -e $DESIRED_LOGPATH ]
        then
            if [ -w $DESIRED_LOGPATH ]
            then
                LOGNAME=$DESIRED_LOGPATH
            else
                echo "Cannot append to $DESIRED_LOGPATH, logging to current directory instead."
                LOGNAME=$ALTERNATE_LOGPATH
            fi
        else
            if [ -w $DESIRED_LOGDIR -a -x $DESIRED_LOGDIR ]
            then
                LOGNAME=$DESIRED_LOGPATH
            else
                echo "Cannot write to $DESIRED_LOGDIR, logging to current directory instead."
                LOGNAME=$ALTERNATE_LOGPATH
            fi
        fi
        echo "Logging outputs to: $LOGNAME"
        echo >> $LOGNAME
        echo "_________________________ desta start issued `date`." >> $LOGNAME
        echo >> $LOGNAME
        # Remove the status file, if it exists
        if [ -e $STATUS_FILE ]
        then
            rm $STATUS_FILE
        fi
	setProcessUlimit

        # Execute the DESTA command
	# RUNON_CMD will be blank if no affinity is set.
	# Use the no-prefix DESTA_CMD because we know we have no special
	# characters (&, <, >) within our command line (the redirections are 
	# OK), and it makes the "ps" list entry look better.

        /usr/bin/nohup $NICE $RUNON_CMD $DESTA_CMD_NO_PREFIX com.compaq.svctools.desta.core.DESTAController >> $LOGNAME 2>&1 &

        # Create the Linux lock file for this daemon so that Linux shutdown
        # will know to stop it. (OK if the Director doesn't start up or dies,
        # because it's OK to call "desta stop" even if no Director is running.)
        touch /var/lock/subsys/desta

        # capture the PID in DESTA_PID
        DESTA_PID=$! 
        # Put the PID in the status file, the Controller will pick it up 
        # from there
        echo "PID">$STATUS_FILE
        echo $DESTA_PID>>$STATUS_FILE
        TIME=0 
        DONE=0
        REASSURE_TIME=$DESTA_REASSURE
        # Assign bad return code, override with good (0) only if all goes well.
        # Exit code 1 already used above (Dir already running).
        EXIT_CODE=2
        while ((!$DONE)) 
        do
            STATUS=`head -n 1 $STATUS_FILE`
            if [ "$STATUS" = "SYSTEM_STARTING" -o "$STATUS" = "PID" ]
            then
                # Wait another second and check again
                sleep 1 		
                ((TIME=$TIME+1))	
            elif [ "$STATUS" = "SYSTEM_UP" ]
            then
                # The system's up, print a message to the console
                # and get out of here.
                DONE=1
                EXIT_CODE=0
                echo
                echo "The Director process has started successfully."
            elif [ "$STATUS" = "SYSTEM_ERROR" ]
            then
                # something went wrong, show the error messages in the status file
                echo
                echo "The Director process did not start correctly and was shut down."
                echo "Error messages:"
                tail -n 2 $STATUS_FILE
                echo
                echo "Please refer to $LOGNAME for more details."
                DONE=1
            fi
            if (($TIME > $DESTA_TIMEOUT))
            then
                # We've waited more than the timeout period, something 
                # probably went wrong and the director is not going
                # to start, so just get out of here.
                echo
                echo "The Director process has not finished startup."
                echo "It may not have started correctly."
                echo
                echo "Please refer to $LOGNAME for more details."
                DONE=1
            elif (($TIME > $REASSURE_TIME))
            then
                # Reassure the user we're still waiting.
                echo
                echo "Director in startup phase 2."
                REASSURE_TIME=$(($REASSURE_TIME + $DESTA_REASSURE))
            fi
        done
        exit $EXIT_CODE
        ;;

    'stop')

	# if the command is 'desta stop wccproxy' then stop the WCCProxy program 
	# and exit.
	if [ "$2" = "wccproxy" ]
	then
		wccproxy_stop
		#wccproxy_kill
		exit 0
	   fi
        #  Stop the DESTA Director process

	# First check to see if a Director is running
	getDirectorState
	STATE=$?
	if (($STATE == 1 || $STATE == 9))
	then
		echo "The Director process is NOT currently running, cannot stop it."
		exit 1
	fi
	echo "Stopping the Director."
	desta_dir_stop
        $0 status
	# Now stop the JNIRoot Launcher
	#  wccproxy_stop
	#wccproxy_kill
	;;

    'bldknw')
        #  Start the command-line interface to rebuild frame knowledge.
        
        # First check to see if a Director is running
        getDirectorState
	STATE=$?
	if (($STATE == 1 || $STATE == 9))
	then
		echo "The Director process is NOT currently running, cannot rebuild knowledge base."
		exit 1
	fi
	
        #  New scheme: wipe out and rebuild KnowledgeStore.dat by registering
        #  all frames in all *Knowledge.jar files in $SVCTOOLS_HOME/common/jars.
        #  To drive BuildKnowledgeStore directly (the old way), type:
        #  "desta exec com.compaq.svctools.desta.cli.BuildKnowledgeStore ..."
        shift
        echo "Clearing existing KnowledgeStore.dat ..."
        $DESTA_CMD com.compaq.svctools.desta.cli.BuildKnowledgeStore -clear $RUNON_POSTFIX
        for KNOWLEDGE_JAR_FILE in $SVCTOOLS_HOME/common/jars/*Knowledge.jar
        do
            echo "Registering decomposer frame knowledge in $KNOWLEDGE_JAR_FILE ..."
            $DESTA_CMD com.compaq.svctools.desta.cli.BuildKnowledgeStore -j $KNOWLEDGE_JAR_FILE $RUNON_POSTFIX
        done
        echo "KnowledgeStore.dat rebuilt."
        ;;

    'msg')
        #  Start the command-line interface to send message(s).
        
        # First check to see if a Director is running
        getDirectorState
	STATE=$?
	if (($STATE == 1 || $STATE == 9))
	then
		echo "The Director process is NOT currently running, cannot send it a message."
		exit 1
	fi
	
        shift
        $DESTA_CMD com.compaq.svctools.desta.cli.SendDESTAMsg $* $RUNON_POSTFIX
        ;;

    'dri')
        #  Start the command-line interface to manipulate the DESTA Registry.
        #  Typically called only by this script or installation scripts.
        shift
        $DESTA_CMD com.compaq.svctools.desta.cli.DESTAReg $* $RUNON_POSTFIX
        ;;

    'qsap')
        shift
        $DESTA_CMD com.compaq.svctools.desta.cli.ToggleQSAP $* $RUNON_POSTFIX
	;;
	
	'mom')
        shift
        $DESTA_CMD com.compaq.svctools.desta.cli.ToggleMOM $* $RUNON_POSTFIX
	;;
		
    'sicl')
        shift
        $DESTA_CMD com.compaq.svctools.desta.cli.ToggleSICL $* $RUNON_POSTFIX
	;;
			
    'isee')
        shift
        $DESTA_CMD com.compaq.svctools.desta.cli.ToggleISEE $* $RUNON_POSTFIX
	;;

    'smtp')
        shift
        $DESTA_CMD com.compaq.svctools.desta.cli.ToggleSMTPMail $* $RUNON_POSTFIX
	;;

    'entity')
        shift
        $DESTA_CMD com.compaq.svctools.desta.services.managedentities.CliManagedEntities $* $RUNON_POSTFIX
	;;

    'servob')
        # Change current Service Obligation information or override an expired obligation.
        shift
        $DESTA_CMD com.compaq.svctools.desta.cli.ServiceObligation $* $RUNON_POSTFIX
        ;;

    'exec')
	#  Execute the given Java class, with optional parameters.
	setProcessUlimit
	shift
    if [ "$1" = "" ]
    then
      echo "Error 386: Insufficient arguments."
    else
      if [ "$DESTA_CMD_STANDARD" = "true" ]
      then
         DESTA_CMD="$DESTA_CMD -Xmx80M"
      fi
      $DESTA_CMD $* $RUNON_POSTFIX
    fi
	;;

    'setsub')
        #  Add/replace the subprocess command line in the DESTA registry file.
        #  Typically called only by this script.
	#  
	# RUNON_CMD will be blank if no affinity is set.
	# Use the no-prefix DESTA_CMD because the echo-ing scheme doesn't
	# work when we try to write this command to a file, and we know we
	# have no special characters (&, <, >) within our command line,
	# and it makes the "ps" list entry look better.
	#

	# Check if there is a max heap size in the DESTA.REG file for the subprocess.
	SUBPROC_MAXHEAP_REG_KEY=desta.subprocess.maxHeapSize
        SUBPROC_MAXHEAP_REG_KEYVAL=`$0 dri GET $SUBPROC_MAXHEAP_REG_KEY`
	SUBPROC_MAXHEAP_REG_UNDEF=`echo $SUBPROC_MAXHEAP_REG_KEYVAL | /bin/cut -f 2 -d '='`
	if [ ! -z "$SUBPROC_MAXHEAP_REG_UNDEF" -a \
             "$SUBPROC_MAXHEAP_REG_UNDEF" != "null" ]
	then
		# if the user has specified a $DESTA_CMD environment variable, we will not modify it.
		# else, tack on the max heap setting switch (-Xmx)
		if [ "$DESTA_CMD_STANDARD" = "true" ]
		then
			DESTA_CMD_NO_PREFIX="$DESTA_CMD_NO_PREFIX -Xmx$SUBPROC_MAXHEAP_REG_UNDEF"
		fi
        else
                # use the default
                DESTA_CMD_NO_PREFIX="$DESTA_CMD_NO_PREFIX -Xmx300M"
	fi

	PROCESSLAUNCHER=com.compaq.svctools.desta.util.DESTAProcessWrapper
        $0 dri DEL desta.Subprocess.CommandLine \
            ADD desta.Subprocess.CommandLine \
            SET desta.Subprocess.CommandLine $RUNON_CMD $DESTA_CMD_NO_PREFIX \
		 $PROCESSLAUNCHER

        ;;

    'verify')

		# Call a script to verify the integrity of the current installation.
		$SVCTOOLS_HOME/bin/integrityCheck
		;;

    'sysinfo')
        sysInfoUsage="Syntax error. Usage: desta sysinfo [ out filename.txt ]"
        if [ "$2" = "" ]
        then
            sysInfoFile=WEBES_sysinfo.txt
        else
            if [ "$2" = "out" ]
            then
                if [ "$3" = "" ]
                then
                    echo "$sysInfoUsage"
                    exit 50
                else    
                    sysInfoFile=$3
                fi
            else
                echo "$sysInfoUsage"
                exit 50
            fi
        fi
        if [ -e $sysInfoFile ]
        then
            echo "$sysInfoFile already exists, exiting."
            exit 706
        fi
        set -C
       # Enable noclobber to ensure we don't overwrite an existing file.
        echo "Dumping system information into $sysInfoFile"
        echo "This may take a while..."
        # print out some information on this systems settings
        echo "System Information:" > $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "Identification:" >> $sysInfoFile 2>&1
        /bin/uname -a >> $sysInfoFile 2>&1
        /bin/date >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "Swap space:" >> $sysInfoFile 2>&1
        /sbin/swapon -s >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "Default process limits:" >> $sysInfoFile 2>&1
        ulimit -a >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "Hard process limits:" >> $sysInfoFile 2>&1
        ulimit -H -a >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "vmstat:" >> $sysInfoFile 2>&1
        /usr/bin/vmstat  >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "Environment variables:" >> $sysInfoFile 2>&1
        set >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "Network status:" >> $sysInfoFile 2>&1
        /bin/netstat -i >> $sysInfoFile 2>&1
        /bin/netstat -r >> $sysInfoFile 2>&1
        /bin/netstat -rn >> $sysInfoFile 2>&1
        /bin/netstat >> $sysInfoFile 2>&1
        /bin/netstat -a >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "Ping myself:" >> $sysInfoFile 2>&1
        /bin/ping -c3 localhost >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "Boot messages:" >> $sysInfoFile 2>&1
        /bin/cat /var/log/boot.log >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "Kernel messages:" >> $sysInfoFile 2>&1
        /bin/cat /var/log/ksyms.0 >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "System messages:" >> $sysInfoFile 2>&1
        /bin/cat /var/log/messages >> $sysInfoFile 2>&1	
        echo "=================================" >> $sysInfoFile 2>&1
        echo "File systems:" >> $sysInfoFile 2>&1
        /bin/df -k >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "Installed products:" >> $sysInfoFile 2>&1
        /bin/rpm -qa >> $sysInfoFile 2>&1
        if [ -x /usr/bin/dsn ]
        then
            echo "=================================" >> $sysInfoFile 2>&1
            echo "DSNlink info:" >> $sysInfoFile 2>&1
            /usr/bin/dsn version >> $sysInfoFile 2>&1
        fi
        echo "=================================" >> $sysInfoFile 2>&1
        echo "WEBES release:" >> $sysInfoFile 2>&1
        /bin/cat $SVCTOOLS_HOME/common/webes/release.txt >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "WEBES directories:" >> $sysInfoFile 2>&1
        /bin/ls -alRL /usr/opt/hp/svctools >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
        echo "Running WCCProxy process:" >> $sysInfoFile 2>&1
        /bin/ps ugxww | /bin/grep WCCProxy | /bin/grep -v grep >> $sysInfoFile 2>&1
        echo "=================================" >> $sysInfoFile 2>&1
	echo "Open files" >> $sysInfoFile 2>&1
	/usr/sbin/lsof +D $SVCTOOLS_HOME >> $sysInfoFile 2>&1
	echo "=================================" >> $sysInfoFile 2>&1
        echo "End of desta sysinfo output." >> $sysInfoFile 2>&1
        echo "Complete."
    ;;
  'WCCService')
#    set -x
    /usr/bin/nohup nice $2 $3 $4 $5 $6 $7 $8 $9 >> $SVCTOOLS_HOME/specific/desta/logs/WCCServices.log 2>&1 &
    WCCSpid=$!
    echo $WCCSpid >> $SVCTOOLS_HOME/specific/desta/logs/WCCService.pids
    ;;
    'killwccproxy')
    wccproxy_kill
    exit 0
    ;;

    *)
	#  Unknown or "help" command
      if [ "$1" = "" ]
      then
        echo "Error 386: Insufficient arguments."
        more $SVCTOOLS_HOME/common/desta/docs/clihelp/desta_summary.txt
      else
        if [ "$1" = "help" ]
        then
          more $SVCTOOLS_HOME/common/desta/docs/clihelp/desta_summary.txt
        else
          if [ ! "$1" = "help" ]
          then
              echo "Error 50: Illegal arguments."
              more $SVCTOOLS_HOME/common/desta/docs/clihelp/desta_summary.txt
          fi
        fi
      fi
	;;
	
 esac

# End of file
