#!/bin/sh
#
# Startup script for the Hardware Management Console
#
# Description: Common function definitions for various HMC scripts, especially
#              those used during startup of the HMC JVM(s)
#
# Change log:
#
# 04/03/2002 Kurt Schroeder  -01 D50O added init script processing and cleanup functions
# 05/14/2002 Kurt Schroeder  -02 D50R add /console to the PATH
# 06/17/2002 Joe Gdaniec     -03 Added runmanagerOnly function as dup of runmanager that
#                                specifies PERFORM_INIT=NO.  Used when running manager-
#                                only confiurations (i.e. no local client).
# 06/25/2002 Kurt Schroeder  -04 D50U Add work directory creation routine
# 07/19/2002 Kurt Schroeder  -05 D50V Add /usr/local/bin to path.
# 07/15/2003 Kurt Schroeder  -06 Add HTML support.
# 09/11/2003 Mike Clark      -07 Added Apache support.
# 10/02/2003 Kurt Schroeder  -08 Handle hostname change.
# 10/17/2003 Kurt Schroeder  -09 Add standalone task support.
# 11/19/2003 Kurt Schroeder  -10 Add ulimit support for core files - ODT E3085
# 01/12/2004 James Jenks     -11 Modified queryFileLocation so it does not return DFC attributes.
# 01/22/2004 P.Clas          -12 Add begin/end(^/$) characters to queryFileLocation so matching
#                                works properly.  Change search for JAR files to search for files
#                                with .jar extension instead of any files off the jars directory
# 01/26/2004 Kurt Schroeder  -13 Add unpacking of hmcmanager.tgz and bringup.tgz.
# 02/06/2004 Mike Clark      -14 Suppress automatic java/heap dumps on OutOfMemoryError
# 02/10/2004 Jim Hennessy        Add ability to suppress listening on JDI debugging
#                                port on launch of manager, via HMC_DEBUG_OFF
#                                environment variable.
# 03/18/2004 Larry Brocious  -15 Add "unified JVM" support.  Note - enabling this
#                                support automatically enables HTML support.
#                                Also did some code cleanup and added comments.
# 03/26/2004 Kurt Schroeder  -16 Add lookForDesktopFile function.
# 05/05/2004 Mike Clark      -17 Add usingSSL function
# 05/21/2004 Kurt Schroeder  -18 Add environment variables for javacore/heap dump locations.
# 07/23/2004 Jim Hennessy        Don't use -type f option on find for jar files,
#                                to allow for symbolic links.
# 08/03/2004 Kurt Schroeder  -19 Disable Java debugging port to speed things up temporarily.
# 08/27/2004 Kurt Schroeder  -20 Disable JIT to work around JVM core problems.
# 12/20/2004 Kurt Schroeder  -21 Run init scripts on office/developer machines as well.
# 01/07/2005 Kurt Schroeder  -22 Enable JIT to speed things up.
# 01/14/2005 Dave Simpson    -23 Add ^ to comment stripping spec in queryFileLocation.
#                                Also convert ? to . in file specs
# 02/15/2005 Kurt Schroeder  -24 Make sure to unpack TGZ files when userid is created.
# 03/17/2005 Mike Clark      -25 Add Bobcat support
# 03/30/2005 Kurt Schroeder  -26 Add BRINGUP option for JVM command
# 04/04/2005 Kurt Schroeder  -27 Add environment setting support for init scripts.
# 04/04/2005 Mike Clark      -28 Use getJvmOptions in bobcat path for common System Properties
# 08/26/2005 Kurt Schroeder  -29 Change logic used to determine if hmcmanager.tgz needs to be unpacked.
# 04/04/2006 Tom Mathias     -30 H8447; fix stack size to 2048 MB
# 05/30/2006 Kurt Schroeder  -31 Fix home directory file permissions to adhere to security audits.
# 10/08/2006 Larry Brocious  -32 Add rotatefile function
# 10/12/2006 Kurt Schroeder  -33 Force JVM locale to be en_US.
# 11/07/2006 Kurt Schroeder  -34 Add component tracing for performance measurements.
# 12/15/2006 Kurt Schroeder  -35 Make sure DFC directory ownership correct at startup,
#                                also change getManagerId to return correct userid on
#                                non-Z platforms.
# 01/12/2006 Kurt Schroeder  -36 Add more output to cleanupTmp
# 01/13/2007 Bill Dovin      -37 suppress dumps
# 01/19/2007 Larry Brocious  -38 Fix JVM dump-related environment variables so we get heapdump on SIGQUIT
# 02/22/2007 Kurt Schroeder  -39 Add JVM -Xgcthreads1 option temporarily to work around dual core garbage collection hang.
# 03/20/2007 Dave Simpson    -40 Add CIMOM pathing.
# 05/17/2007 Brian Myers     -41 Force JVM default encoding to be UTF8.
# 06/21/2007 P. Callaghan    -42 Allow CLASSPATH to be prepended
# 06/25/2007 Jim Hennessy    -43 Start Unified JVM as root.  It will drop privileges.
# 08/19/2008 Minh Nguyen     -44 Increase File Open limit to 2048 (defect 675860)
# 10/07/2008 Steve Feustel   -45 Run with option -Xjit:disableIdiomRecognition to work around JIT/Garbage collection crash (defect 678476)

#-16 start
# A function to look for the desktop file (actzdesk.dat).  Returns the
# fully qualified name if it exists and the empty string if it does not.
lookForDesktopFile() {
   #-21 start
   local result=""
   if [ `whoami` == "root" ]; then
      local fn="actzdesk.dat"
      result=`queryFileLocation $fn`"$fn"

      if ! [ -f "$result" ]; then
         result=""
      fi
   fi
   #-21 end

   echo "$result"
}
#-16 end

#-08 start
# A function to set the system's hostname to match the system configuration
# file, if it doesn't match already.
resetHostName() {
  local curname=`hostname`
  local newname=`cat /etc/HOSTNAME | sed -e 's/\..*//1'`
  echo "resetHostName: curname=$curname newname=$newname"
  #local newname=`cat /etc/sysconfig/network | sed -e '/HOSTNAME=/!d' -e 's/HOSTNAME="//1' -e 's/"//g'`
  if [ -n "$newname" ]; then
     if [ "$curname" != "$newname" ]; then
        echo "Resetting hostname from $curname to $newname."
        hostname $newname
     fi
  fi
}
#-08 end

#-15 start
#-06 start
# A function to determine if we're running in an "HTML" environment.  This is
# primarily based on the presence of a marker file in the top-level HMC
# directory; however, it can be overridden by other factors.  The marker file
# setting may be overridden by enabling the "unified JVM" support as follows -
# when running in a unified JVM environment, the HTML support is automatically
# enabled.  However, both of those factors can be overridden by setting the
# NO_HTML environment variable to any non-null value; this is intended for use
# by the runtask script to run a "standalone" task in an AUIML environment
# regardless of the environment in which the HMC is running.
# Returns a non-empty string if HTML support is enabled; otherwise, returns
# an empty string (which indicates we'll be using AUIML instead).
isHtml() {
   local result

   if [ -n "$NO_HTML" ]; then       # Override is set
      result=""
   else
      if [ -n "`isUnified`" ]; then # In a unified JVM environment
         result="html";             # HTML support is required
      else  # Honor the presence/absence of the marker file
         if [ -e "${CONSOLE_PATH}html" ]; then  # Marker file exists
            result="html";
         else
            result="";
         fi
      fi
   fi

   echo "$result"
}
#-06 end
#-15 end

# A function to determine a browser should be started or not.
# primarily based on the presence of a marker file in the top-level HMC
# directory. If the file, noBrowser exists, this function returns the
# string "true"; otherwise an empty string is returned.
isNoBrowser() {
   local result

   if [ -e "${CONSOLE_PATH}noBrowser" ]; then  # Marker file exists
      result="true";
   else
      result="";
   fi

   echo "$result"
}

#-15 start
# A function to determine if we're running in a "unified JVM" environment
# (both the "manager" and "client" code running in the same JVM).  This is
# based on the presence of a marker file in the top-level HMC directory.
# Note that this environment is not supported in a non-HTML environment.
# Enabling the "unified JVM" support automatically enables HTML support.
# See isHtml() for additional comments.
# Returns a non-empty string if we are running in a unified JVM environment;
# otherwise, returns an empty string.
isUnified() {
   local result

   if [ -e "${CONSOLE_PATH}unified" ]; then  # Marker file exists
      result="true";
   else
      result="";
   fi

   echo "$result"
}
#-15 end

#-15 start
# A function to determine if we're using the Apache web server.  This is
# based on the presence of a marker file in the top-level HMC directory.
# Returns a non-empty string if we are using Apache; otherwise, returns an
# empty string.
usingApache() {
   local result

   if [ -e "${CONSOLE_PATH}use_apache" ]; then  # Marker file exists
      result="true";
   else
      result="";
   fi

   echo "$result"
}
#-15 end

#-17 start
# A function to determine if the apache web server is configured to use SSL.
# This is based on the presence of a certificate in the data/certs/ directory.
# Returns a non-empty string if we are using SSL; otherwise, returns an
# empty string.
usingSSL() {
    local result

    if [ -e "${CONSOLE_PATH}/data/certs/ssl.crt/server.crt" -a -e "${CONSOLE_PATH}/data/certs/ssl.key/server.key" ]; then
        result="true";
    else
        result="";
    fi

    echo "$result"
}
#-17 end

#-15 start
# A function to determine if the memory debugging suport is enabled.  This is
# based on the presence of a marker file in the top-level HMC directory.
# Returns a non-empty string if it is enabled; otherwise, returns an
# empty string.
usingMemDebug() {
   local result

   if [ -e "${CONSOLE_PATH}memdebug" ]; then  # Marker file exists
      result="true";
   else
      result="";
   fi

   echo "$result"
}
#-15 end

#-25 start
usingBobcat() {
    local result

    if [ -e "${CONSOLE_PATH}/use_bobcat" ]; then
        result="true";
    else
        result="";
    fi

    echo "$result"
}
#-25 end

#-15 start
# A function to return various options for the java command line to be used
# when running the manager, client or unified JVM.
# Arguments:
# . JVM identifier - either "manager", "client" or "unified"
# Returns a string (possibly an empty string) of options for the java command.
getJvmOptions() {
   local options= html= mgroptions= clientoptions= extraoptions=

   if [ -z "$HMC_JVM_EXTRA_OPTS" ]; then
      extraoptions=""                     # No extra options to specify.
   else
      extraoptions="$HMC_JVM_EXTRA_OPTS"  # Use the extra options.
   fi
   #-26 start
   if [ -e "$CONSOLE_PATH/bringup.tgz" ]; then
      extraoptions="-DBRINGUP=YES $extraoptions"
   fi
   #-26 end

   if [ -n "`isHtml`" ]; then  # Running in an HTML environment
      mgroptions="-DHMC_USING_HTML"
      #-28 start
      if [ -n "`isNoBrowser`" ]; then  # Do not start the browser
         clientoptions="-DSTART_BROWSER=false -DPERFORM_INIT=NO -DCONSOLE_PATH=$CONSOLE_PATH"
      else
         clientoptions="-DSTART_BROWSER=true -DCONSOLE_PATH=$CONSOLE_PATH"
      fi
      if [ -n "`usingBobcat`" ]; then
         clientoptions="$clientoptions -DRUNNING_BOBCAT=true"
#     else
#        clientoptions="$clientoptions"
      fi
      #-28 end
      if [ "manager" == "$1" ]; then
         options="$mgroptions $extraoptions"
      else
         if [ "client" == "$1" ]; then
            options="$clientoptions $extraoptions"
         else # Unified JVM; just combine the manager and client options
            options="$mgroptions $clientoptions $extraoptions"
         fi
      fi
   else                    # Running in a non-HTML enviroment
      options="$extraoptions"
   fi

   echo "$options -Xgcthreads1"
}
#-06 end
#-15 end

# A function to return the manager userid (Linux login)
getManagerId() {
   #-21 start
   if [ `whoami` == "root" ]; then
      if [ -n "${CONSOLE_USERID}" ]; then #-35
         echo "${CONSOLE_USERID}";        #-35
      else                                #-35
         echo "hmcmanager";               #-35
      fi                                  #-35
   else
      echo `whoami`
   fi
   #-21 end
}

# A function to return the local client userid (Linux login)
getLocalClientId() {
   #echo "hmcclient"
   getManagerId      # Run the client under the same userid as the manager
}

# A function to return the manager JVM's JDI debugging port.
getManagerDebugPort() {
   echo "8000"
}

# A function to return the client JVM's JDI debugging port.
getLocalClientDebugPort() {
   echo "8001"
}

#-15 start
# A function to return the unified JVM's JDI debugging port.
getUnifiedDebugPort() {
   echo "8000"
}
#-15 end

# A function to return the standard Java debugging options
getJavaDebugOptions() {
    #-10 start
    local jvmversion=

    jvmversion=`java -version 2>&1 | sed -e '/.*Classic.*/!d'`
    if [ -z "$jvmversion" ]; then
       # Non-classic java
       #-06 start
       echo "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=$1,suspend=n"
       #-06 end
    else
       #Classic java
       echo "-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,address=$1,suspend=n -Djava.compiler=NONE"
    fi
    #-10 end
}

# A function to setup the environment for the manager of the local client.
# Parameters: $1 - Top-level HMC directory
#             $2 - String of JAR paths to be excluded from CLASSPATH.  May be empty.
setupEnv() {
   local dirs= newpath= jars= jar= dir= dumpdir=
   #-06 start
   local jarexclude= part= html= expart= exclude=

   # Set the CONSOLE_PATH environment variable to the top-level directory for
   # the console code, with a trailing slash
   export CONSOLE_PATH=$1/

   # Set the list of JAR directory names that should be excluded/
   if [ -n "$2" ]; then jarexclude="$2";
   else jarexclude=""; fi

   # Exclude either HTML or AUIML JARs based on which mode we're running in
   html=`isHtml`;
   if [ -n "$html" ]; then # HTML mode
      jarexclude="auiml $jarexclude";
   else                    # AUIML mode
      jarexclude="html $jarexclude";
   fi
   #echo "jarexclude=$jarexclude."
   #-06 end

   # Set JDKHOME if not already set.
   if [ -z "$JDKHOME" ]; then
      export JDKHOME=/java
   fi

   #-14 start
   # Set IBM JVM environment variables so:
   # - we don't get a heapdump on every OutOfMemoryError occurrence
   # - we get both a javacore and a heapdump when SIGQUIT is received (e.g., when sent by hmcdebuginfo)
   # - we get a core dump and javacore for controlled abort conditions (SIGABRT)
   # - we get a core dump and javacore for unexpected synchronous terminating signals (e.g., SIGSEGV, SIGFPE)
   # - we don't get any dumps for asynchronous terminating signals (e.g., SIGTERM, SIGINT, SIGHUP)
   export JAVA_DUMP_OPTS="ONOUTOFMEMORY(NONE),ONDUMP(JAVADUMP,HEAPDUMP),ONERROR(SYSDUMP,JAVADUMP),ONEXCEPTION(SYSDUMP,JAVADUMP),ONINTERRUPT(NONE)"  # -38
   #-18 start
   dumpdir=`queryFileLocation jvmdumptargetdirectory`
   dumpdir=`dirname $dumpdir/x`
   export IBM_HEAPDUMPDIR=$dumpdir
   export IBM_JAVACOREDIR=$dumpdir
   #-18 end
   #-14 end
   #-20 start
   #-22 export JAVA_COMPILER=NONE
   #-20 end

   #-02 start
   # Add the top-level HMC directory to PATH
   export PATH=$1:$PATH
   #-02 end

   export HOME=/home/`getManagerId`
   export xhost=localhost

   #-10 start
   ulimit -c unlimited
   #-10 end
   #-44 start
   ulimit -n 2048
   #-44 end
   #-30 start
   ulimit -s 2048
   #-30 end

   # Add Java to PATH if not already there.
   if ! which javac >/dev/null 2>&1; then
      if [ -e $JDKHOME/jre/bin/java ]; then export PATH=$JDKHOME/jre/bin:$PATH;
      else export PATH=$JDKHOME/bin:$PATH; fi
   fi

   # Scan the HMC's top-level bin directory for subdirectories to add to PATH.
   dirs=`find $1/bin -mindepth 1 -type d 2>/dev/null`
   newpath=$PATH:/usr/X11R6/bin:/usr/local/bin
   # -40 start
   if [ -d $PEGASUS_HOME ]; then
      newpath="$PEGASUS_HOME/bin:$newpath"
   fi
   # -40 end
   for dir in $dirs; do
      newpath=$dir:$newpath
   done
   export PATH=$newpath

   # Scan the HMC's top-level lib directory for subdirectories to add to LD_LIBRARY_PATH.
   dirs=`find $1/lib -mindepth 1 -type d 2>/dev/null`
   newpath=$LD_LIBRARY_PATH
   # -40 start
   if [ -d $PEGASUS_HOME ]; then
      newpath="$PEGASUS_HOME/lib:$newpath"
   fi
   # -40 end
   for dir in $dirs; do
      newpath=$dir:$newpath
   done
   export LD_LIBRARY_PATH=$newpath

   # Scan the HMC's top-level jars directory for files to add to CLASSPATH.
   jars=`find $1/jars -mindepth 1 -name "*.jar" 2>/dev/null`
   #-06 start
   newpath=$1  # Start with HMC's top-level directory
   #-42 start
   if [ -e "${CONSOLE_PATH}first_in_classpath" ]; then  # Marker file exists
      classpathToPrepend=`cat ${CONSOLE_PATH}first_in_classpath 2>/dev/null`
      newpath=$classpathToPrepend:$newpath
   fi
   #-42 end
   if [ -z "$html" ]; then    # AUIML mode
      newpath="$newpath:$1/csa_runtime/settings"   # Add AUIML stuff
   fi
   for jar in $jars; do
      exclude=""
      for part in $jarexclude; do
         expart=`echo -n $jar | sed -e s?.*/$part/.*??1`
         if [ -z "$expart" ]; then
            exclude="X"
         fi
      done
      #echo "exclude=$exclude, for jar=$jar."
      if [ -z "$exclude" ]; then
         newpath=$newpath:$jar
      fi
   done
   #-06 end
   export CLASSPATH=$newpath:$CLASSPATH
   echo -e "\nCLASSPATH=$CLASSPATH\n"

   #-06 start
   # Handle memory allocation/deallocation tracing option
   if [ -n "`usingMemDebug`" ]; then   #-15
      export HWMCA_TRACE_MEMCALLS=1
      echo -e "\nMemory allocation/deallocation tracing is enabled...\n"
   else
      unset HWMCA_TRACE_MEMCALLS
      echo -e "\nMemory allocation/deallocation tracing is disabled...\n"
   fi
   #-06 end
}

# A function to run the client JVM
# Arguments:
# . The top-level HMC directory
# . Hostname of manager JVM to connect to
# . Login ID under which to run the client JVM; if empty, then current login is used
runclient() {
   #-19 start
   if [ -n "$HMC_DEBUG_ON" ]; then
      local debugport=`getLocalClientDebugPort`
      local debuggingopts="`getJavaDebugOptions $debugport` -DJDI_PORT=$debugport"
   else
      local debuggingopts=""
   fi
   #-19 end
   #-06 start
   local otheropts=`getJvmOptions client`
   local javacmd= html=

   #-08 start
   # Be sure the hostname is correct
   resetHostName
   #-08 end

   #-07 start
   local using_apache
   if [ -n "`usingApache`" ]; then  #-15
      using_apache="true"
   else
      using_apache="false"
   fi

   javacmd="java $debuggingopts $otheropts -Djava.library.path=$LD_LIBRARY_PATH -Djava.security.policy=$1/data/rmipolicy -Djava.endorsed.dirs=$1/endorsed -DUSING_APACHE=$using_apache"
   #-07 end

   # Complete the java command line by adding the appropriate startup class name
   if [ -n "`isHtml`" ]; then # Using HTML support   -15
      javacmd="$javacmd com.ibm.hwmca.fw.tomcat.Startup"
   else                       # AUIML
      javacmd="$javacmd com.ibm.hwmca.fw.ui.HmcClient host=$2"
   fi

   echo -e "\n$javacmd\n"
   #-06 end
   # Issue the java command to start the client JVM
   if [ -z "$3" ]; then
      $javacmd
   else
      su -m $3 --command="$javacmd"
   fi

   jvmRc=$?    # Capture the JVM's exit status
}

# A function to run the manager JVM
# Arguments:
# . The top-level HMC directory
# . Login ID under which to run the manager JVM; if empty, then current login is used
runmanager() {
   if [ -n "$HMC_DEBUG_ON" ]; then  # OK to enable debugging -19
      local debugport=`getManagerDebugPort`
      local debuggingopts="`getJavaDebugOptions $debugport` -DJDI_PORT=$debugport"
   else
      local debuggingopts=""
   fi

   #-08 start
   # Be sure the hostname is correct
   resetHostName
   #-08 end

   #-06 start
   local otheropts=`getJvmOptions manager`
   local javacmd="java $debuggingopts $otheropts -DPERFORM_INIT=YES -DCONSOLE_PATH=$1/ -Djava.security.policy=$1/data/rmipolicy -Djava.library.path=$LD_LIBRARY_PATH com.ibm.hwmca.fw.system.Manager"

   echo -e "\n$javacmd\n"
   #-06 end
   # Issue the java command to start the manager JVM
   if [ -z "$2" ]; then
      $javacmd
   else
      su -m $2 --command="$javacmd"
   fi

   jvmRc=$?    # Capture the JVM's exit status
}

# A function to run the manager when no local client will be started
# Arguments:
# . The top-level HMC directory
# . Login ID under which to run the manager JVM; if empty, then current login is used
# -03 start
runmanagerOnly() {
   if [ -n "$HMC_DEBUG_ON" ]; then  # OK to enable debugging -19
      local debugport=`getManagerDebugPort`
      local debuggingopts="`getJavaDebugOptions $debugport` -DJDI_PORT=$debugport"
   else
      local debuggingopts=""
   fi

   #-06 start
   local otheropts=`getJvmOptions manager`
   local javacmd="java $debuggingopts $otheropts -DPERFORM_INIT=NO -DCONSOLE_PATH=$1/ -Djava.security.policy=$1/data/rmipolicy -Djava.library.path=$LD_LIBRARY_PATH com.ibm.hwmca.fw.system.Manager"

   echo -e "\n$javacmd\n"
   #-06 end
   # Issue the java command to start the manager JVM
   if [ -z "$2" ]; then
      $javacmd
   else
      su -m $2 --command="$javacmd"
   fi

   jvmRc=$?    # Capture the JVM's exit status
}
# -03 end

#-15 start
# A function to start the unified JVM
# Arguments:
# . The top-level HMC directory
# . Login ID under which to run the unified JVM; if empty, then current login is used
runUnified() {
   if [ -n "$HMC_DEBUG_ON" ]; then  # OK to enable debugging -19
      local debugport=`getUnifiedDebugPort`
      local debuggingopts="`getJavaDebugOptions $debugport` -DJDI_PORT=$debugport"
   else
      local debuggingopts=""
   fi

   local otheropts=`getJvmOptions`
   local javacmd=

   # -43 start
   if [ -n "$2" ]; then
      otheropts="$otheropts -DHMC_RUN_USER=$2"
   fi

   # -45 start
   otheropts="$otheropts -DHMC_CAPABILITIES=CAP_NET_BIND_SERVICE=ep -Xjit:disableIdiomRecognition"
   # -45 end
   # -43 end

   # Be sure the hostname is correct
   resetHostName

   local using_apache="false"
   if [ -n "`usingApache`" ]; then
      using_apache="true"
   fi

   local using_ssl="false"
   if [ -n "`usingSSL`" ]; then
      using_ssl="true"
   fi

#-25 start
   local using_bobcat="false"
   if [ -n "`usingBobcat`" ]; then
      using_bobcat="true"
      . $1/bobcat/profiles/hmcprofile/bin/setupCmdLine.sh

      javacmd="java $otheropts -Xbootclasspath/p:/opt/bobcat/java/jre/lib/ext/ibmorb.jar:/opt/bobcat/java/jre/lib/ext/ibmext.jar \
-Dws.ext.dirs=$WAS_EXT_DIRS \
-Dserver.root=$1/bobcat/profiles/hmcprofile \
-Duser.install.root=$1/bobcat/profiles/hmcprofile \
-Dcom.ibm.itp.location=/opt/bobcat/bin \
-classpath $WAS_CLASSPATH \
-Dwas.install.root=$WAS_HOME \
-Djava.library.path=/opt/bobcat/java/jre/bin:/opt/bobcat/java/jre/bin/classic:/opt/bobcat/java/jre/bin:/opt/bobcat/bin:$LD_LIBRARY_PATH:/usr/lib \
-Djava.security.auth.login.config=$1/bobcat/profiles/hmcprofile/properties/wsjaas.conf \
-Djava.security.policy=$1/bobcat/profiles/hmcprofile/properties/server.policy \
$USER_INSTALL_PROP com.ibm.ws.bootstrap.WSLauncher com.ibm.ws.runtime.WsServer $CONFIG_ROOT $WAS_CELL $WAS_NODE hmcserver"
   else
     # suppress dump code
     if [ -n "$2" -a "$2" = "suppressDumps" -o -n "$3" -a "$3" = "suppressDumps" ]; then
          if [ "$2" = "suppressDumps" ]; then
            suppressopts="SUPPRESS_DUMPS=$3"
          else
             suppressopts="SUPPRESS_DUMPS=$4"
          fi
          javacmd="java $debuggingopts $otheropts -Djava.library.path=$LD_LIBRARY_PATH -Djava.security.policy=$1/data/rmipolicy -Djava.endorsed.dirs=$1/endorsed -DUSING_APACHE=$using_apache -DUSING_APACHE_SSL=$using_ssl -D$suppressopts com.ibm.hwmca.fw.startup.UnifiedStartup"
     else
      javacmd="java $debuggingopts $otheropts -Djava.library.path=$LD_LIBRARY_PATH -Djava.security.policy=$1/data/rmipolicy -Djava.endorsed.dirs=$1/endorsed -DUSING_APACHE=$using_apache -DUSING_APACHE_SSL=$using_ssl com.ibm.hwmca.fw.startup.UnifiedStartup"
     fi
   fi

   echo -e "\n$javacmd\n"

   actzTrace 99 "XFRMPRFF: Starting unified JVM";  #-34
   # -43 start
   # Issue the java command to start the unified JVM.  It will drop its root
   # privileges, but retain the capability to bind to TCP ports less than 1024.
   LANG=en_US.UTF8 $javacmd
# We previously used the following if $2 was non-empty:
#     su -m $2 --command="LANG=en_US.UTF8 $javacmd"   #-33 -41
   # -43 end

   jvmRc=$?    # Capture the JVM's exit status

   if [ "$using_bobcat" = "true" ]; then
       # when using bobcat the JVM's *real* return code will be left in the 'rc' file
       jvmRc=`cat $1/rc`    # Capture the JVM's exit status
   fi
#-25 end
}
#-15 end

# A function to check to see if a user with a specified login name exists
# Arguments:
# . The login name to check
# Returns a non-empty string if the user exists; otherwise, returns an empty string
checkuser() {
   echo `cat /etc/passwd | sed -e /$1:/!D`
}

# A function to create the manager userid, if necessary, and setup some things
# in its home directory.
# Arguments:
# . The top-level HMC directory
makeManagerId() {
   # Check to see if the HMC manager userid exists, if it does not, create it.
   local user=`getManagerId`
   local x=`checkuser $user`
   if [ -z "$x" ]; then
      echo "The user $user does not exist, so we are creating it."
      useradd -c "HMC Manager Userid" -g nobody -d /home/$user -M $user
      echo "$user:passw0rd" | /usr/sbin/chpasswd
      mkdir -p /home/$user
      chown -R $user:nobody /home/$user
      #tar -xvzf $1/hmcicewm.tgz -C /home/$user
      chown -R $user:nobody /home/$user
      #if [ -e $1/clienttools.tgz ]; then tar -xvzf $1/clienttools.tgz -C /home/$user; fi
      rm -f "$1/hmcmanager.loaded" "$1/bringup.loaded" #-24
#  else
#     echo "The user $user already exists."
   fi

   # Setup some things in the home directory if it hasn't been done yet
   #-29 if ! [ -e "$1/hmcmanager.loaded" ]; then  # Not setup yet
   if [ "$1/hmcmanager.tgz" -nt "$1/hmcmanager.loaded" ]; then # it is new -29
      echo "Unpacking hmcmanager.tgz file..." #-29
      tar -xzf $1/hmcmanager.tgz -C /home/$user
      touch -r "$1/hmcmanager.tgz" "$1/hmcmanager.loaded"  # Mark that we've done this setup -29
   fi
   if [ -e "$1/bringup.tgz" ]; then
      #-29 if ! [ -e "$1/bringup.loaded" ]; then  # Not setup yet
      if [ "$1/bringup.tgz" -nt "$1/bringup.loaded" ]; then # it is new -29
         echo "Unpacking bringup.tgz file..." #-29
         tar -xzf $1/bringup.tgz -C /home/$user
	 touch -r "$1/bringup.tgz" "$1/bringup.loaded"  # Mark that we've done this setup -29
      fi
   fi
   #-31 start
   chmod -v 'u=rwx,g=r,o=' "/home/$user"
   chmod -v -R 'o=' "/home/$user"
   find "/home/$user" -type f | xargs -r chmod -v 'g-w'
   #-31 end
}

# A function to create the local client userid if necessary
makeLocalClientId() {
   makeManagerId "$1" # Just use the manager userid
   # Check to see if the HMC client userid exists, if it does not, create it.
   #local user=`getLocalClientId`
   #local x=`checkuser $user`
   #if [ -z "$x" ]; then
   #   echo "The user $user does not exist, so we are creating it."
   #   useradd -c "HMC Client Userid" -g nobody -d /home/$user -M $user
   #   mkdir -p /home/$user
   #   chown -R $user:nobody /home/$user
   #   tar -xvzf $1/hmcicewm.tgz -C /home/$user
   #   chown -R $user:nobody /home/$user
   #   if [ -e $1/clienttools.tgz ]; then tar -xvzf $1/clienttools.tgz -C /home/$user; fi
   #else
   #   echo "The user $user already exists."
   #fi
}

# A function to log to the system messages log
# Arguments:
# . A string to be written to the log
hmcinitlog() {
   local logger= logcmd=
   logger=`type -p logger`
   if [ -n "$logger" ]; then     # logger exists; use it
      logcmd="$logger -t HMC $1"
   else
      logger=`type -p initlog`
      if [ -n "$logger" ]; then  # initlog exists; use it
         logcmd="$logger --name=HMC --string='$1'"
      fi
   fi
   if [ -n "$logcmd" ]; then     # We found a logger and built a suitable command
      $logcmd                    # Issue the actual command
   fi
}

# A function that uses the DFC file to determine the location of the specified file.
# This function requires that the CONSOLE_PATH environment variable be set to the
# top-level HMC directory, with a trailing slash.
# Arguments:
# . The name of the file to look up in DFC
# Writes to stdout the location of the specified file
queryFileLocation() {
   local pattern= path= ans= tmp= tmppattern= attr=
   #Austin{
   # For some reason the actzQueryFileLocation binary is not working in the
   # Austin ODE environment, and the code for this binary is far more complex
   # than I care to decipher.  I'd rather just bypass it and use the alternate
   # script code in the else leg below since it appears to work fine.  The
   # following conditional will be false if ODEOUTDIR is defined:
   if `which actzQueryFileLocation$ODEOUTDIR >/dev/null 2>&1`; then
  #if `which actzQueryFileLocation >/dev/null 2>&1`; then
   #Austin}
      # use the C program since it is faster
      tmp=`XDFC_CHECK_DEFAULT_PATH=1 actzQueryFileLocation $1`;
      echo "$tmp" | cut -d ':' -f 2;
      return `echo "$tmp" | cut -d : -f 1`;
   else
      # do it the hard way
      #-23 start
      cat "$CONSOLE_PATH"iqzddfc.trm | sed -e "/^#.*/D" |
      #-23 end
      while read pattern path attr;
      do
         if [ -z "$ans" ]; then
            #-23 start
            tmppattern=`echo "$pattern" | sed -e "s?\.?#?g" -e "s?\*?.*?g" -e "s/?/./g" -e "s?#?\\\\\.?g" -e "s?/?\\\\\/?g"`;
            #-23 end
            tmp=`echo $1 | sed -e "/^$tmppattern$/!D"`;
            #echo "tmp=$tmp pattern=$pattern tmppattern=$tmppattern";
            if [ "$tmp" == "$1" ]; then
               echo "$path" | sed -e s?"\*"?"$CONSOLE_PATH"?g -e "s?//?/?g";
               ans=$path;
               if [ "$pattern" == "*" ]; then
                  return 1;
               else
                  return 0;
               fi
            fi
         fi
      done
   fi
   #return 0
}

#-01 start
# A function to cleanup the temporary directory for the HMC.
cleanupTmp() {
   local tmp=`queryFileLocation "tmp"`
   local consoleUser="";   #-35
   local consoleGroup="";  #-35
   echo "About to cleanup the $tmp directory..."; #-36
   if [ -n "$tmp" ]; then rm -vfR $tmp; fi
   find "$tmp" -ls #-36
   #-35 start
   # If we know the console userid and default group, then run through the
   # DFC file and make sure any "C" entries are created and have the correct
   # ownership/permissions.
   if [ `whoami` == "root" ] && [ -n "${1}" ]; then
      consoleUser=`getManagerId`;
      if [ -n "${consoleUser}" ]; then
         consoleGroup=`id --group --name ${consoleUser}`;
         if [ -n "${consoleGroup}" ]; then
            cat "${1}/"iqzddfc.trm | sed -e "/^#.*/D" |
            while read pattern path attr;
            do
               if [ "${attr}" == "C" ]; then
                  defpath="`echo $path | sed -e '/^*/!d'`";   #-36
                  fullpath=`echo $path | sed -e "s?\*?$1/?g" -e 's?//?/?g'`;
                  parts=`echo $fullpath | sed -e 's?/? ?g'`;
                  if [ -n "$parts" ]; then
                     path="";
                     for dir in $parts;
                     do
                        path="$path/$dir";
                        if [ ! -d "$path" ]; then
                           mkdir -v "$path";  #-36
                           chown -v "${consoleUser}:${consoleGroup}" "$path"
                           chmod -v "u=rwx,g=rwxs" "$path"
                        else
                           if [ "$fullpath" == "$path/" ] || [ -n "$defpath" ]; then #-36
                              chown -v "${consoleUser}:${consoleGroup}" "$path"
                              chmod -v "u=rwx,g=rwxs" "$path"
                           fi
                        fi
                        ls -ld "$path";  #-36
                     done
                  fi
               fi
            done
         fi
      fi
   fi
   #-35 end
}

# A function to cleanup semaphores and shared memory used by the HMC.
# These resources are identified by a key that begins with 0x9672.
cleanupMem() {
   local keys="0x9672 0x630 0x50"
   local key= id= rest= chkkey= match=

   # Find and remove HMC-related semaphores
   ipcs -s | while read key id rest;
   do
      if [ -n "$key" ]; then
         for chkkey in $keys; do
            match=`echo $key | sed -e /^$chkkey/!d`
            if [ "$key" == "$match" ]; then
               ipcrm sem $id;
            fi
         done
      fi
   done

   # Find and remove HMC-related shared memory segments
   ipcs -m | while read key id rest;
   do
      if [ -n "$key" ]; then
         for chkkey in $keys; do
            match=`echo $key | sed -e /^$chkkey/!d`
            if [ "$key" == "$match" ]; then
               ipcrm shm $id;
            fi
         done
      fi
   done

   # Find and remove HMC-related message queues
   ipcs -q | while read key id rest;
   do
      if [ -n "$key" ]; then
         for chkkey in $keys; do
            match=`echo $key | sed -e /^$chkkey/!d`
            if [ "$key" == "$match" ]; then
               ipcrm msg $id;
            fi
         done
      fi
   done
}

# A function to execute all of the HMC's init scripts.  All executable files
# in the HMC's top-level init directory structure will be executed.
# Arguments:
# . The top-level HMC directory
runInit() {
   local files= file=
   # Scan the HMCs top-level init directory for all files
   files=`find $1/init -mindepth 1 -type f 2>/dev/null`
   for file in $files; do
      #-21 start
      if [ -x "$file" ]; then
         actzTrace 99 "XFRMPRFF: Starting initialization script: $file";  #-34
         #-27 start
         if [ -z "`echo $file | sed -e '/\.env$/!d'`" ]; then
            # Normal init script
            echo "Executing initialization script $file"
            $file $1 $2
         else
            # Environment altering init script
            echo "Executing initialization script $file"
            . $file $1 $2
         fi
         #-27 end
         actzTrace 99 "XFRMPRFF: Finished initialization script: $file";  #-34
      else
         echo "Could not execute initialization script $file: not executable"
      fi
      #-21 end
   done
}

# -01 end

#-04 start
# A function to return the name of the HMC's work directory
# Arguments:
# . The top-level HMC directory
# Returns the name of the HMC's work directory
getWorkDir() {
   local workdir=$1/work
   echo $workdir
}

# A function to create the HMC's work directory with full r/w access
# Arguments:
# . The top-level HMC directory
makeWorkDir() {
   local workdir=`getWorkDir $1`
   if ! [ -e "$workdir" ]; then
      mkdir $workdir
   fi
   chmod 777 $workdir
}
#-04 end

#-21 start
# Attempts to run a command that need root authority.  The command will
# be executed if the user is root, or if the user has authorized the
# command to be run through sudo
# Arguments:
# . The command to execute
sudoThis() {
   local sudolist
   # If we are already root, run the command as is
   if [ `whoami` == "root" ]; then
      $@
   # Otherwise, if we have sudo privledges, run it through sudo
   elif [ `whoami` != "hmcmanager" ]; then
      sudolist=`which $1`
      sudolist=`sudo -l | grep "NOPASSWD: ALL\|NOPASSWD: $sudolist"`
      if [ -n "$sudolist" ]; then
         sudo $@
      # Otherwise, don't run it at all
      else
        echo "$@: not executed because user does not have root or sudo authority"
      fi
   fi
}

# zSeries HMC/SE initialization script used to mount the /ffdc
# partition on top of the /console/ffdc directory and create some
# useful symbolic links.
initFFDC() {
   local consoleffdc="$1/ffdc"
   local rootffdc="/ffdc"

   # Create the /console/ffdc directory if it does not exist.
   if [ -d "$consoleffdc" ]; then
      echo "Skipping creation of $consoleffdc, since it already exists."
   else
      echo "Creating $consoleffdc..."
      mkdir -p "$consoleffdc"
   fi
   echo "Fixing ownership/permissions of $consoleffdc directory."
   chown ":nobody" "$consoleffdc"
   chmod 775 "$consoleffdc"

   # Fix ownership/permissions of /ffdc directory if it exists.
   if [ -d "$rootffdc" ]; then
      echo "Fixing ownership/permissions of $rootffdc directory."
      # Be sure that directory ownership and permissions are correct
      chown ":nobody" "$rootffdc"  # Set group ownership of /ffdc directory
      # Set the permissions for /ffdc directory and all of its subdirectories
      chmod 775 "$rootffdc"
      find "$rootffdc" -type d | xargs chmod 775
      echo "Mounting $rootffdc on top of $consoleffdc..."
      mount --bind "$rootffdc" "$consoleffdc"
   else
      echo "The $rootffdc directory does not exist."
   fi
}
#-21 end


#-32 start
# "Rotate" a specified file so that the most recent versions can be kept.
# A specified number of straight copies can be kept as well as a specified
# number of compressed copies.
# Arguments:
# . The name of the file to rotate
# . The number of straight copies to keep.  They will have a numeric suffix
#      on the filename to identify them
# . The number of compressed copies to keep.  They will be compressed with
#      bzip2 and will have a numeric suffix in addition to a "bz2" suffix.
rotatefile() {
   fn="$1"               # Name of the file to rotate
   count=$2              # Number of uncompressed files to keep
   bzcount=$((count+$3)) # Total number of rotated copies to keep

   # Remove the oldest log file if it exists
   if [ -e "${fn}.${count}" ]; then
      # Remove the oldest bzipped log file if it exists
      if [ -e "${fn}.${bzcount}.bz2" ]; then
         rm -f "${fn}.${bzcount}.bz2"
      fi
      # Rename the other bzipped log files
      for ((i=$bzcount; $i > $count; i=i-1)); do
         if [ -e "${fn}.$((i-1)).bz2" ]; then
            mv "${fn}.$((i-1)).bz2" "${fn}.${i}.bz2"
         fi
      done
      if ((bzcount > count)); then
      bzip2 "${fn}.${count}"
      mv -f "${fn}.${count}.bz2" "${fn}.$((count+1)).bz2"
      fi
   fi
   # Rename the other log files
   for ((i=$count; $i > 1; i=i-1)); do
      if [ -e "${fn}.$((i-1))" ]; then
         mv "${fn}.$((i-1))" "${fn}.${i}"
      fi
   done
   # Rename the last log file
   if [ -e "${fn}" ]; then
      mv ${fn} "${fn}.1"
   fi
}
#-32 end
