#!/bin/sh
###############################################################################
# WebSphere Application Server liberty launch script
#
# Copyright IBM Corp. 2011
# The source code for this program is not published or other-
# wise divested of its trade secrets, irrespective of what has
# been deposited with the U.S. Copyright Office.
# 
# ----------------------------------------------------------------------------
#
# To customize the use of this script (for example with /etc/init.d system 
# service managers), use the following environment variables:
#
# JAVA_HOME  - The java executable is found in ${JAVA_HOME}/bin
#
# JVM_ARGS   - A list of JVM command line options,
#              e.g. system properties or -X parameters
#              The value will be expanded by the shell (use quotes for spaces)
#
# LOG_DIR    - The log file directory
#              The default value is ${WLP_OUTPUT_DIR}/serverName/logs
#
# LOG_FILE   - The log file name
#              This log file is only used if the server is run in the
#              background via the start action. 
#              The default value is console.log
#
# PID_DIR    - The directory that should be used for server pid file(s).
#              The default value is ${WLP_OUTPUT_DIR}/.pid
#
# PID_FILE   - The file that should be used for the server pid file.
#              The default value is ${PID_DIR}/serverName.pid
#
# WLP_USER_DIR - The user/custom configuration directory used to store
#              shared and server-specific configuration. 
#              See README.TXT for details about shared resource locations.
#              A server's configuration is at ${WLP_USER_DIR}/servers/serverName
#              The default value is the usr directory in the install directory.
#
# WLP_OUTPUT_DIR - The directory containing output files for defined servers.
#              This directory must have both read and write permissions for
#              the user or users that start servers.
#              By default, a server's output logs and workarea are stored
#              in the ${WLP_USER_DIR}/servers/serverName directory
#              (alongside configuration and applications).
#              If this variable is set, the output logs and workarea 
#              would be stored in ${WLP_OUTPUT_DIR}/serverName.
#
###############################################################################

##
## Determine the absolute path of the installation directory.
##
dirname=`dirname "$0"`
WLP_INSTALL_DIR=`cd "$dirname/.." && pwd`

##
## Platform specific setup
##
PS_P='ps -p'
os400lib=false
shareclassesCacheDirPerm=true
defaultFileEncoding=
newline='
'
nativeEBCDIC=false

case `uname` in
  CYGWIN_*)
    PS_P='ps -Wp'
    WLP_INSTALL_DIR=`cygpath -m "${WLP_INSTALL_DIR}"`
    shareclassesCacheDirPerm=false
    ;;

  OS/390)
    defaultFileEncoding=iso8859-1
    nativeEBCDIC=true         # Auto-convert server.env/jvm.options from ASCII-to-EBCDIC, if necessary.
    _BPXK_WLM_PROPAGATE=NO    # Prevent WLM enclave propagation to spawned processes
    _EDC_PTHREAD_YIELD=-2     # Disable sleeps inside of pthread_yield
    JAVA_PROPAGATE=NO         # Prevent WLM enclave propagation to new threads
    export _BPXK_WLM_PROPAGATE _EDC_PTHREAD_YIELD JAVA_PROPAGATE

    WLP_NLS_PATH="${WLP_INSTALL_DIR}/lib/native/zos/s390x/nls/%N.cat"
    if [ ${NLSPATH} ]
    then          
      NLSPATH="${WLP_NLS_PATH}:${NLSPATH}" 
    else
      NLSPATH="${WLP_NLS_PATH}"
    fi
    ;;

  OS400) 
    # os400lib gets unset later if we cannot find WAS_PRODUCT_LIB and WAS_SHARED_LIB
    os400lib=true
    ;;
esac

##
## safeEcho: Portable echo that can handle backslashes and leading dashes.
safeEcho()
{
  cat <<EOF
$*
EOF
}

##
## Quote ${WLP_INSTALL_DIR} for eval.
##
WLP_INSTALL_DIR_QUOTED=\'`safeEcho "$WLP_INSTALL_DIR" | sed s/\'/\'\"\'\"\'/g`\'

##
## Consume script parameters: 
##   action is required/positional, 
##   serverName is optional, --options following
##
if [ $# -lt 1 ]
then
  ACTION=help:usage
else
  ACTION=$1
  shift #consume
  if [ $# -ge 1 ]
  then
    # Only use if it isn't something that looks like an option
    case $1 in
    -*);;
    *)
      SERVER_NAME=$1
      shift #consume
    esac
  fi
fi

##
## Set server name and directory
##
if [ -z "$SERVER_NAME" ]
then
  SERVER_NAME=defaultServer
fi


##
## Set JAVA_AGENT_QUOTED if WLP_SKIP_BOOTSTRAP_AGENT is unset.
##
JAVA_AGENT_QUOTED=-javaagent:${WLP_INSTALL_DIR_QUOTED}/lib/bootstrap-agent.jar
if [ -n "${WLP_SKIP_BOOTSTRAP_AGENT}" ]; then
  JAVA_AGENT_QUOTED=
fi

##
## mkdirs: Create a directory and all parent directories, if necessary.
##
mkdirs()
{
  if [ ! -d "$1" ]; then
    mkdir -p "$1"
  fi
}

##
## serverStatus: Check for a running server process.  If the first argument is
##               true, avoid using the launcher to verify the status if possible,
##               and don't output messages even if the launcher is used.
##               The second argument is passed to clientCmd, and the third
##               argument is the --status variant.
##               If success is returned, then ${PID} will be set if available.
serverStatus()
{
  if [ -f "${SERVER_OUTPUT_DIR}/workarea/.sLock" ]; then
    if [ ! -f "${SERVER_OUTPUT_DIR}/workarea/.sCommand" ]; then
      # Workarea exists, .sCommand doesn't.  Server is not running.
      rm -f "${PID_FILE}"
      return 1
    fi

    # Read the PID file to set ${PID} if possible.  Remove it if stale.
    # Otherwise, assume the server is started if we're avoiding the launcher.
    if serverPIDStatus && $1; then
      return 0
    fi

    # The workarea suggests a started server.  Either the script started a
    # server process that ended before removing .sCommand, or the server was
    # started without using the script (so the PID file was never created).
    # In either case, verify the status using the launcher.
    if $1; then
      clientCmd $2 "${SERVER_NAME}" $3 > /dev/null
    else
      clientCmd $2 "${SERVER_NAME}" --pid="${PID}" $3
    fi
    rc=$?

    if [ $rc = 1 ]; then
      # The launcher verified the server is not running.  Remove the indicator
      # files to avoid checking again on subsequent script invocations.
      rm -f "${SERVER_OUTPUT_DIR}/workarea/.sCommand"
    fi

    return $rc
  fi

  if serverPIDStatus; then
    if $1; then
      return 0
    fi

    # PID file suggests a started server with a removed workspace.  Verify
    # using the launcher.
    clientCmd $2 "${SERVER_NAME}" --pid-file="${PID_FILE}" --pid="${PID}" $3
    return $?
  fi

  # Neither workarea nor PID file suggest a started server.
  return 1
}

##
## serverPIDStatus: Check the PID file for a running server process.  ${PID}
##                  will be set to the PID if running or to empty if not.
serverPIDStatus()
{
  if [ -f "${PID_FILE}" ]; then
    PID=`cat "${PID_FILE}"`
    if $PS_P "$PID" > /dev/null 2>&1; then
      return 0
    fi

    rm "${PID_FILE}"
  fi

  PID=
  return 1
}

##
## checkServer: Check for created/existing server.  If it does not, issue an
##              error message if the first argument is true, and then exit the
##              script regardless.
checkServer()
{
  if [ -d "${SERVER_CONFIG_DIR}" ] || [ "defaultServer" = "${SERVER_NAME}" ]
  then
    return 0
  fi

  if $1
  then
    javaCmd false '' --message:info.serverNotExist "${SERVER_NAME}"
  fi
  return 1
}

##
## installEnv: Set variables for a non-server or nonexistent server command.
installEnv()
{
  readServerEnv "${WLP_INSTALL_DIR}/etc/server.env"
  installEnvDefaults
  serverEnvDefaults
}

##
## installEnvDefaults: Set variable defaults for a non-server or nonexistent
##                     server command.
installEnvDefaults()
{
  readServerEnv "${WLP_INSTALL_DIR}/etc/default.env"

  if [ -z "${WLP_USER_DIR}" ]
  then
    if [ -z "${WLP_DEFAULT_USER_DIR}" ]
    then
      WLP_DEFAULT_USER_DIR=${WLP_INSTALL_DIR}/usr
    fi
    WLP_USER_DIR=${WLP_DEFAULT_USER_DIR}
  fi

  if [ -z "${WLP_OUTPUT_DIR}" ]
  then
    if [ -z "${WLP_DEFAULT_OUTPUT_DIR}" ]
    then
      WLP_DEFAULT_OUTPUT_DIR=${WLP_USER_DIR}/servers
    fi
    WLP_OUTPUT_DIR=${WLP_DEFAULT_OUTPUT_DIR}
  fi

  SERVER_CONFIG_DIR=${WLP_USER_DIR}/servers/${SERVER_NAME}

  if $os400lib
  then
    if [ -z "${WAS_PRODUCT_LIB}" ] || [ -z "${WAS_SHARED_LIB}" ]
    then 
      os400lib=false
    fi
  fi  
  
  export WLP_USER_DIR
  export WLP_OUTPUT_DIR
}

##
## serverEnvDefaults: Set defaults for server variables.
serverEnvDefaults()
{
  SERVER_OUTPUT_DIR=${WLP_OUTPUT_DIR}/${SERVER_NAME}

  if [ -z "$LOG_DIR" ]
  then
    LOG_DIR=${SERVER_OUTPUT_DIR}/logs
  fi

  if [ -z "$LOG_FILE" ]
  then
    LOG_FILE=console.log
  fi

  if [ -z "${PID_FILE}" ]; then
    if [ -z "${PID_DIR}" ]; then
      PID_DIR=${WLP_OUTPUT_DIR}/.pid
    fi
    PID_FILE=${PID_DIR}/${SERVER_NAME}.pid
  else
    PID_DIR=`dirname "${PID_FILE}"`
  fi

  if [ -z "${JAVA_HOME}" ]
  then
    if [ -z "${JRE_HOME}" ]
    then
      if [ -z "${WLP_DEFAULT_JAVA_HOME}" ]
      then
        # Use whatever java is on the path
        JAVA_CMD=java
      else
        JAVA_HOME=${WLP_DEFAULT_JAVA_HOME}
        JAVA_CMD=${WLP_DEFAULT_JAVA_HOME}/bin/java
      fi
    else
      JAVA_HOME=${JRE_HOME}
      JAVA_CMD=${JRE_HOME}/bin/java
    fi
  else
    JAVA_CMD=${JAVA_HOME}/bin/java
  fi

  if $shareclassesCacheDirPerm
  then
    ibmVersionProperties=
    if [ -z "${JAVA_HOME}" ]
    then
      javaBinDir=`type java 2> /dev/null | sed -e 's,[^/]*,,' -e 's,/java[^/]*$,,'`
      if [ -n "${javaBinDir}" ]
      then
        if [ -f "${javaBinDir}/../lib/version.properties" ]
        then
          ibmVersionProperties=${javaBinDir}/../lib/version.properties
        elif [ -f "${javaBinDir}/../jre/lib/version.properties" ]
        then
          ibmVersionProperties=${javaBinDir}/../jre/lib/version.properties
        fi
      fi
    elif [ -f "${JAVA_HOME}/lib/version.properties" ]
    then
      ibmVersionProperties=${JAVA_HOME}/lib/version.properties
    elif [ -f "${JAVA_HOME}/jre/lib/version.properties" ]
    then
      ibmVersionProperties=${JAVA_HOME}/jre/lib/version.properties
    fi

    if [ -n "${ibmVersionProperties}" ] && ibmSdkVersion=`grep '^sdk\.version=' "${ibmVersionProperties}"`
    then
      # We only want to set -Xshareclasses if we can set the cacheDirPerm option,
      # but it is only available on IBM 1.6 SR10 and 1.6 (2.6 VM) SR1 and later.
      # The version.properties file was added in IBM 1.6, so accept any other
      # version for forwards compatibility.
      case $ibmSdkVersion in
      sdk.version=*60-*);;
      sdk.version=*60fp*);;
      sdk.version=*60ifix*);;
      sdk.version=*60sr[1-9]-*);;
      sdk.version=*60sr[1-9]fp*);;
      sdk.version=*60sr[1-9]ifix*);;
      sdk.version=*60_26-*);;
      sdk.version=*60_26fp*);;
      sdk.version=*60_26ifix*);;
      sdk.version=*)
        IBM_JAVA_OPTIONS="-Xshareclasses:name=liberty-%u,nonfatal,cacheDir=\"${WLP_OUTPUT_DIR}/.classCache\",cacheDirPerm=1000 -XX:ShareClassesEnableBCI -Xscmx60m -Xscmaxaot4m $IBM_JAVA_OPTIONS"
        export IBM_JAVA_OPTIONS
      esac
    fi
  else
    IBM_JAVA_OPTIONS="-Xshareclasses:name=liberty-%u,nonfatal,cacheDir=\"${WLP_OUTPUT_DIR}/.classCache\" -XX:ShareClassesEnableBCI -Xscmx60m -Xscmaxaot4m $IBM_JAVA_OPTIONS"
    export IBM_JAVA_OPTIONS
  fi

  # Set a default file encoding if needed
  if [ -n "$defaultFileEncoding" ]; then
    if ! expr "${JVM_OPTIONS_QUOTED} ${JVM_ARGS} ${IBM_JAVA_OPTIONS}" : '.*\(-Dfile\.encoding\=[^[:space:]]\)' > /dev/null; then
      JVM_ARGS="${JVM_ARGS} -Dfile.encoding=$defaultFileEncoding"
    fi
  fi
}

##
## serverEnv: Set variables for an existing server.
serverEnv()
{
  readServerEnv "${WLP_INSTALL_DIR}/etc/server.env"
  installEnvDefaults

  readServerEnv "${SERVER_CONFIG_DIR}/server.env"
  serverEnvDefaults
}

##
## serverEnvAndJVMOptions: Read server.env files and set environment variables.
##                         Read jvm.options file into ${JVM_OPTIONS_QUOTED}
serverEnvAndJVMOptions()
{
  serverEnv

  # By default, set -XX:MaxPermSize.  This option should be ignored by JVMs
  # that don't support the option.
  JVM_OPTIONS_QUOTED=-XX:MaxPermSize=256m

  # Try to read ${SERVER_CONFIG_DIR}/jvm.options.  If it does not exist, then
  # try to read ${WLP_INSTALL_DIR}/etc/jvm.options.
  for jvmOptions in "${SERVER_CONFIG_DIR}/jvm.options" "${WLP_INSTALL_DIR}/etc/jvm.options"; do
    if [ -f "$jvmOptions" ]; then
      saveIFS=$IFS
      IFS=$newline
      for option in `readNativeFile "$jvmOptions" '[#-]' | tr -d '\r'`; do
        if [ -n "$option" ]; then
          case $option in
          \#*);;
          *)
            option=\'`safeEcho "$option" | sed s/\'/\'\"\'\"\'/g`\'
            JVM_OPTIONS_QUOTED="$JVM_OPTIONS_QUOTED $option"
          esac
        fi
      done
      IFS=$saveIFS

      # If jvm.options exists in server config, then ignore the one in wlp/etc/
      break
    fi
  done
}

##
## readServerEnv: Read server.env file and export environment variables.
readServerEnv()
{
  if [ -f "$1" ]; then
    saveIFS=$IFS
    IFS=$newline
    for line in `readNativeFile "$1" '[#_A-Za-z=]' | tr -d '\r'`; do
      case $line in
      \#*);;
      *=*)
        # Only accept alphanumeric variable names to avoid eval complexities.
        if var=`safeEcho "$line" | sed -e 's/^\([a-zA-Z0-9_][a-zA-Z0-9_]*\)=.*/\1/'`; then
          value=\'`safeEcho "$line" | sed -e 's/[^=]*=//' -e s/\'/\'\"\'\"\'/g`\'
          eval "$var=$value; export $var"
        fi
      esac
    done
    IFS=$saveIFS
  fi
}

##
## Detects the code page of the file and converts to EBCDIC,
## if necessary, before cat'ing.
##
## Only applicable if running in a native EBCDIC environment (z/OS).
##
## $1 the file name
## $2 pattern denoting the expected first char of file
readNativeFile() {
  if ${nativeEBCDIC}; then
    # ASCII 'm' overlaps with EBCDIC '_', so strip it out before detecting the codepage.
    # Note: cat used here to handle ASCII-tagged files.
    filecontents=`cat "$1" | iconv -f ISO8859-1 -t IBM-1047 | tr -d 'm\r\n'`
    case $filecontents in
      $2*) iconv -f ISO8859-1 -t IBM-1047 "$1" ;;  # ASCII file.
      *) cat "$1"                # EBCDIC file or ASCII-tagged file.
    esac
  else
    cat "$1"
  fi
}

##
## serverWorkingDirectory: Change the working directory to ${SERVER_OUTPUT_DIR}
serverWorkingDirectory()
{
  # Change the working directory to ${SERVER_OUTPUT_DIR}.
  mkdirs "${SERVER_OUTPUT_DIR}"
  cd "${SERVER_OUTPUT_DIR}"
}

##
## javaCmd: Execute a java-based command.  Arguments are:
##
##   background
##     true if the process should be created in the background; false otherwise.
##
##   logFile
##     Non-empty path for output log; empty otherwise.  Directory must exist.
##     If background is true, then both stdout and stderr will be redirect.
##     Otherwise, only stderr will be redirect.
##
##   "$@"
##     All remaining arguments to be passed to the command
##
## The following variables must be set:
##   ${JAVA_CMD} - the java command
##   ${JAVA_DEBUG} - JVM options to enable debug, or empty
##   ${JAVA_AGENT_QUOTED} - The -javaagent argument quoted for eval
##   ${JVM_OPTIONS_QUOTED} - jvm.options quoted for eval
##   ${WLP_INSTALL_DIR_QUOTED} - ${WLP_INSTALL_DIR} quoted for eval
javaCmd()
{
  JAVA_CMD_BACKGROUND=$1
  shift
  JAVA_CMD_LOG=$1
  shift

  # Set all the parameters for the java command.  We use eval so that each line
  # in jvm.options is treated as a distinct argument.
  eval "set -- ${JVM_OPTIONS_QUOTED} ${JAVA_DEBUG} ${JVM_ARGS} ${JAVA_AGENT_QUOTED} -jar ${WLP_INSTALL_DIR_QUOTED}/lib/ws-launch.jar "'"$@"'

  # Do not add extra logic after the commands without preserving $?
  if [ -n "${JAVA_CMD_LOG}" ]; then
    if ${JAVA_CMD_BACKGROUND}; then
      "${JAVA_CMD}" "$@" > "${JAVA_CMD_LOG}" 2>&1 &
    else
      safeEcho "${JAVA_CMD}" "$@" > "${JAVA_CMD_LOG}"
      "${JAVA_CMD}" "$@" 2>> "${JAVA_CMD_LOG}"
    fi
  else
    if ${JAVA_CMD_BACKGROUND}; then
      "${JAVA_CMD}" "$@" &
    else
      "${JAVA_CMD}" "$@"
    fi
  fi
}

##
## javaCmdOS400: Execute a java-based command using OS400 Native launcher
##
##   background
##     true if the process should be created in the background; false otherwise.
##
##   logFile
##     Non-empty path for output log; empty otherwise.  Directory must exist.
##
##   "$@"
##     All remaining arguments to be passed to the command
##
## The following variables must be set:
##   ${JAVA_CMD} - the java command
##   ${JAVA_DEBUG} - JVM options to enable debug, or empty
##   ${JAVA_AGENT_QUOTED} - The -javaagent argument quoted for eval
##   ${JVM_OPTIONS_QUOTED} - jvm.options quoted for eval
##   ${WLP_INSTALL_DIR_QUOTED} - ${WLP_INSTALL_DIR} quoted for eval
javaCmdOS400()
{
  SERVER_CMD_BACKGROUND=$1
  shift
  SERVER_CMD_LOG=$1
  shift
  
  eval "set -- -jvmargs ${JVM_OPTIONS_QUOTED} ${JAVA_DEBUG} ${JVM_ARGS} ${JAVA_AGENT_QUOTED} -jar ${WLP_INSTALL_DIR_QUOTED}/lib/ws-launch.jar "'"$@"'
  
  export JAVA_HOME
  
  if ${SERVER_CMD_BACKGROUND}
  then
    "/QSYS.LIB/${WAS_PRODUCT_LIB}.LIB/QWLPSTRSVR.PGM" \
      -pgm "${WAS_PRODUCT_LIB}/QWLPSTRSVR" \
      -server "${SERVER_NAME}" \
      -sharedlib "${WAS_SHARED_LIB}" \
      -pidfile "${PID_FILE}" \
      -background \
      -logdir  "${LOG_DIR}"  \
      -serveroutputdir "${SERVER_OUTPUT_DIR}" \
      -serverlog "${SERVER_CMD_LOG}" \
      "$@"
  else
    "/QSYS.LIB/${WAS_PRODUCT_LIB}.LIB/QWLPSTRSVR.PGM" \
      -logdir  "${LOG_DIR}"  \
      -serveroutputdir "${SERVER_OUTPUT_DIR}" \
      "$@"
  fi      
}

## clientCmd: Execute and log a client command, and sets CLIENT_CMD_LOG.
##            Must only be called if the server exists.
##
clientCmd()
{
  CLIENT_CMD_LOG=${LOG_DIR}/$1.log
  shift

  mkdirs "${LOG_DIR}"
  javaCmd false "${CLIENT_CMD_LOG}" "$@"
}

##
## serverCmd: Launch a server process.
##
## PID will be set if SERVER_CMD_BACKGROUND is true and return code is 0
##
serverCmd()
{
  SERVER_CMD_BACKGROUND=$1
  shift
  SERVER_CMD_LOG=$1
  shift

  if $os400lib; then
    javaCmdOS400 ${SERVER_CMD_BACKGROUND} "${SERVER_CMD_LOG}" "${SERVER_NAME}" "$@"
    rc=$?

    JVM_OPTIONS_QUOTED=

    if ${JAVA_CMD_BACKGROUND}; then
      # Verify/wait for the process to start
      clientCmd start "${SERVER_NAME}" --status:start "$@"
      rc=$?      
      
      if [ $rc = 0 ]; then
        PID=`cat "${PID_FILE}"`
        rm "${CLIENT_CMD_LOG}"
      fi
    fi    
  else
    javaCmd ${SERVER_CMD_BACKGROUND} "${SERVER_CMD_LOG}" "${SERVER_NAME}" "$@"
    rc=$?

    JVM_OPTIONS_QUOTED=
    PID=$!

    if $JAVA_CMD_BACKGROUND; then
      # Verify/wait for the process to start
      clientCmd start "${SERVER_NAME}" --pid="${PID}" --status:start "$@"
      rc=$?

      if [ $rc = 0 ]; then
        safeEcho "${PID}" > "${PID_FILE}"
        rm "${CLIENT_CMD_LOG}"
      fi
    fi
  fi

  return $rc
}


JAVA_DEBUG=
JVM_OPTIONS_QUOTED=

case "$ACTION" in

  # Start the server in the foreground
  run | debug)
    serverEnvAndJVMOptions
    if checkServer true
    then
      if [ "${ACTION}" = "debug" ]
      then
        JAVA_DEBUG="-Dwas.debug.mode=true -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=7777"
      fi

      serverWorkingDirectory
      serverCmd false '' "$@"
      exit $?
    else
      exit 2
    fi
  ;;
   
  # Start the server in the background
  start)    
    serverEnvAndJVMOptions
    if checkServer true
    then
      # We can't start the server in the background if it is already running.
      mkdirs "${LOG_DIR}"
      serverStatus false start --status:starting
      rc=$?
      case $rc in
      "0" )
        rc=1
        ;;
      "1" )
        serverWorkingDirectory

        if [ -f "${LOG_DIR}/${LOG_FILE}" ] && [ ! -w "${LOG_DIR}/${LOG_FILE}" ]
        then
          javaCmd false '' --message:error.fileNotFound "${LOG_DIR}/${LOG_FILE}" 
          exit 22
        fi

        mkdirs "${PID_DIR}"
        rm -f "${PID_FILE}"

        mkdirs "${SERVER_OUTPUT_DIR}/workarea"
        touch "${SERVER_OUTPUT_DIR}/workarea/.sLock"
        rm -f "${SERVER_OUTPUT_DIR}/workarea/.sCommand"

        # Start the target server with the provided arguments
        serverCmd true "${LOG_DIR}/${LOG_FILE}" "$@"
        rc=$?
        if [ $rc = 1 ]; then
          # The launcher failed (due to bad JVM arguments, for example).
          # Translate to a better error code.
          rc=22
        fi
        ;;
      esac
      exit $rc
    else
      exit 2
    fi    
  ;;

  create)
    installEnv

    mkdirs "${WLP_OUTPUT_DIR}/.logs"
    javaCmd false "${WLP_OUTPUT_DIR}/.logs/create.log" "${SERVER_NAME}" --create "$@"
    rc=$?

    if [ $rc = 0 ]; then
      rm "${JAVA_CMD_LOG}"
      rm -f "${PID_FILE}"

      if $os400lib; then
        # If production on IBM i, authorize QEJBSVR to the server folder
        system "CHGAUT OBJ('${WLP_USER_DIR}/servers/${SERVER_NAME}') USER(QEJBSVR) DTAAUT(*RX) OBJAUT(*ALL) SUBTREE(*ALL)"
        system "CHGAUT OBJ('${WLP_OUTPUT_DIR}') USER(QEJBSVR) DTAAUT(*RWX) OBJAUT(*ALL) SUBTREE(*ALL)"
      fi
    fi

    exit $rc
  ;;
  
  # Stop the server. 
  stop)
    serverEnv
    if checkServer true
    then
      clientCmd stop "${SERVER_NAME}" --stop "$@"
      rc=$?

      case "$rc" in
        "0" )
          rm "${CLIENT_CMD_LOG}"
          rm -f "${PID_FILE}"
          ;;

        "1" )
          rm -f "${PID_FILE}"
          rm -f "${SERVER_OUTPUT_DIR}/workarea/.sCommand"
          ;;
      esac
      exit $rc
    else
      exit 2
    fi
  ;;
  
  # Check if server is running
  status)
    serverEnv
    if checkServer true
    then
      serverPIDStatus
      clientCmd status "${SERVER_NAME}" --pid="${PID}" --status
      rc=$?

      if [ $rc = 1 ]; then
        rm -f "${PID_FILE}"
        rm -f "${SERVER_OUTPUT_DIR}/workarea/.sCommand"
      fi
      exit $rc
    else
      exit 2
    fi
  ;;

  status:fast)
    serverEnv
    if checkServer false
    then
      serverStatus true status --status
      exit $?
    else
      exit 2
    fi
  ;;

  # Package up the runtime and target server configuration
  package)
    serverEnv
    # Check to see if the server exists
    if checkServer true
    then
      serverPIDStatus
      clientCmd package "${SERVER_NAME}" --pid="${PID}" --package "$@" 
      rc=$?

      if [ $rc = 0 ]; then
        rm "${CLIENT_CMD_LOG}"
      fi

      exit $rc
    else
      exit 2
    fi    
  ;;
  

  # dump the server's configs/logs/status to a zip file
  dump)
    serverEnv
    # Check to see if the server exists
    if checkServer true
    then
      clientCmd dump "${SERVER_NAME}" --dump "$@" 
      exit $?
    else
      exit 2
    fi    
  ;;

  # dump JVM status
  javadump)
    serverEnv
    if checkServer true
    then
      clientCmd javadump "${SERVER_NAME}" --javadump "$@"
      exit $?
    else
      exit 2
    fi
  ;;
    
  version)
    installEnv
    javaCmd false '' --version
  ;;  
  
  help)
    installEnv
    javaCmd false '' --script="$0" --help
  ;;  

  help:usage)
    installEnv
    javaCmd false '' --script="$0" --help:usage
  ;;
  
  *)
    installEnv
    javaCmd false '' --script="$0" --help:actions
  ;;
esac

exit 0
