#!/bin/sh
## ============================================================================
## $Header  da.sh 1.05 2012/01/27 10:00:00 vpickard ship       $
## ============================================================================
##
## NAME:
##   da.sh
##
## DESCRIPTION:
##   Run Diagnostic Assistant tool capabilities from the command line
##
## PARAMETERS:
##   $1 - Utility name - ocm, rda, adr, examenu, menu, asrcollect, version
##   $2, $3, $4 - Utility parameters
##
## WRITTEN BY:
##   23-MAY-2011 Vikki Pickard
##
## UPDATED BY:
##   06-JUN-2011 HSPATEl    Added support for ASR direct call
##   24-MAY-2011 HSPATEL    Added Tool commands
##   01-JUN-2011 SSANDREW   Fixed == to = in Debug if statement, failed solaris
##   01-JUL-2011 VPICKARD   Added Module_Check to determine installation,
##                          setup and previous execution status for ADR, RDA and OCM.
##   14-JUL-2011 HSPATEL    Change to libary listing to reflect new codeline
##                          All need libs will resides under $DA_HOME/lib+
##   25-JUL-2011 HSPATEL    Added detecting ASM SID, HOME, and INITORA to da.env
##   29-JUL-2011 SSANDREW   Moved da_menus.xml to menus dir. and added to this
##                          by running da.sh menu -demo
##   16-AUG-2011 VPICKARD   Added new "Core DA" menu called "menus.xml". This
##                          is temporarily invoked by calling da.sh menu2.
##                          Eventually, this will be a submenu of other menus.
##   25-AUG-2011 SSANDREW   Added "cli" option but not put on help, testing!
##   28-SEP-2011 SSANDREW   Added more args to support ASR commandlinem, and
##                          dynamically use libs in DA_HOME/lib if not in 
##                          ccr/lib
##   30-SEP-2011 SSANDREW   Updated PARAMS / changed Impls to use XXXCli's
##   25-OCT-2011 VPICKARD   Removed all references to da.env and added
##                          Check_for_libs().
##   25-OCT-2011 SSANDREW   Fixed the order of defaults and extra } syntax
##   27-OCT-2011 HSPATEL    Changed ${ECHO} to Debug per customer request 
##                          L117,148
##   10-NOV-2011 VPICKARD   Worked on Set_Env_Vars to use a better order, give
##                          better messages, do more reliable tests and exit
##                          gracefully if we can't find DA_HOME.
##   14-NOV-2011 VPICKARD   Enhanced the DA_HOME determination, and added
##                          removal of the last dirname. Removed declarations
##                          of color variables.
##   16-NOV-2011 VPICKARD   Renamed all of the PARAM* variables to P* and
##                          made other small changes to shorten lines to < 80
##                          characters.
##   22-NOV-2011 VPICKARD   Bug 13415798 - Add umask 077 to remove permissions
##                          on all files created for everyone except the owner.
##   06-DEC-2011 VPICKARD   Bug 13471401 - Removed the exit in Unzip_OCM.
##                          Also added "adr" back into case statement.
##   20-DEC-2011 VPICKARD   Bug 13516466 - Forced java to come from the right
##                          location by using the whole path.
##   28-DEC-2011 VPICKARD   Enh 13526292 - Added -qq to the unzip command
##   06-JAN-2012 VPICKARD   Enh 13567159 - Ensure user.properties and 
##                          da.properties have write permissions
##   06-JAN-2012 SSANDREW   RDA / OCM Issue, need to be sure Log4J directory 
##                          is writeable in DA_OUTPUT/output/log new location
##   11-JAN-2012 SSANDREW   Changed _JAVA_HOME check from: ! -z to -x check
##   18-JAN-2012 VPICKARD   Bug 13591534 - Add ! -z back in, reorder sequence
##   27-JAN-2012 VPICKARD   Enh 13614845 - Set PRODUCT_FAMILY_TYPE to
##                          match the values in CONSTANTS.java.
##   27-JAN-2012 VPICKARD   Removed duplicate code for log4j directory
##   01-FEB-2012 SSANDREW   Removed initial ORACLE_HOME check and turned off 
##                          debug and removed echo of java command args running
##                          also added non-documented em command arg to run 
##                          DaAgentCli.
##                          Next: we need to discover ORACLE_HOME relative to
##                          DA_HOME in Set_Env_Vars () after Set_Da_Home
##   02-FEB-2012 SSANDREW   Defaulting da.sh menu to new discovered menus
##   08-FEB-2012 VPICKARD   Enh 13689260 - Modified Set_Env_Vars() to try to
##                          figure out the OH when not set. Added set
##                          for MW_HOME and WL_HOME. Added jrockit* dir as
##                          possible java location.
##   14-FEB-2012 VPICKARD   Enh 13708286 and 13708429 - Add "-collect" 
##                          command to adr and fix rda "-collect" call.
##                          Commented out the da.sh level "collect" from the
##                          help.
##   16-FEB-2012 VPICKARD   Bug 13727725 - Change all references to 
##                          diagassist.jar to dacore.jar.
##   16-FEB-2012 VPICKARD   Change references to "status" to "summary"
##   21-FEB-2012 VPICKARD   Bug 13734458 - Change syntax back to generic shell
##   24-FEB-2012 VPICKARD   Enh 13719342 - Edit -summary syntax for adr/rda/ocm
##                          to pass the 2nd - 6th parameters through.
##   28-FEB-2012 RJWILLIA   Enh 13708429 - IMPLEMENT -COLLECT OPTION FOR RDA FROM 
##                          DA.SH Now passes "-rda_collect" to RdaCli.
##   14-MAR-2012 VPICKARD   Enh 13487011 - Added Trap_Signal() to recursively
##                          terminate child processes before exiting from
##                          Ctrl-C.
##   14-MAR-2012 VPICKARD   Enh 13370632, part #7. Added command variable for
##                          unzip in case it is not in the path. Also,
##                          completed #1.
##   20-MAR-2012 VPICKARD   Enh 13487011 - Corrected syntax for suppressing
##                          stderr when killing child processes.
##   20-MAR-2012 RJWILLIA   Enh 13790973 - ENH: ADD COMMAND LINE SUPPORT FOR 
##                          -collect_all AND -summary_all
##   29-MAR-2012 VPICKARD   Enh 13846824 - Removed content duplicated in
##                          DaDiscovery.java and added call to it before all
##                          other commands.
##   29-MAR-2012 HSPATEL    Enh 13779051 - Added getmenu option 
##   30-MAR-2012 VPICKARD   Added missing ${DIRNAME}.
##   02-APR-2012 VPICKARD   Enh 13846824 - Changed filename to daenv.env.
##                          Now, if file doesn't get created, they get 
##                          warning message and exit gracefully. Also, rm
##                          the file after sourcing it.
##   03-APR-2012 VPICKARD   Implemented dynamic filename.
##   12-APR-2012 VPICKARD   Re-modularized main and simplified Set_DA_Home
##   16-APR-2012 VPICKARD   Fixed line 733 to use our aliased commands
##   17-Apr-2012 MERICKSO   13852055:change menu filename exadata.xml
##   02-MAY-2012 VPICKARD   Added derivation of JAVA_HOME from WL_HOME
##   03-MAY-2012 VPICKARD   Added DA_OUTPUT command line arg
##   08-MAY-2012 VPICKARD   Removed all -D command line args
##   16-MAY-2012 ssandrew   Moved Discovery class from common to discover
##   17-MAY-2012 ssandrew   Updated -summary_all to and -collect_all to use
##                          standard [Options] [flag] instead of just flags
##                          since no other inputs worked without options and
##                          changed -summary_all to just summary [-detail] and
##                          -collect_all to collect without minus.
##   18-MAY-2012 vpickard   Bug 14092414 - Add 2 add'l possible locations for
##                          JAVA_HOME in case MW_HOME and WL_HOME aren't set.
##   20-MAY-2012 vpickard   Removed quotes around paths in Set_Java_Home()
##                          so wildcards will work.
##   21-MAY-2012 ssandrew   Updated to fail if java being discovered is not
##                          JDK 1.4.2 or higher and is not GCC type java.
##                          Added Check_Java_Install () that is used to set 
##                          JAVA_HOME_SETUP_OK to true if JAVA_HOME java is ok.
##                          Also removed non-required variables usage for WLS.
##   22-MAY-2012 ssandrew   Updated after testing with another JVM that failed
##                          GNU. Note: It also sends java -version to std.out
##                          instead of >2 >1 so, changed to &> for all output.
##                          Bug 14101794 - Added: Check_Write_Permissions
##   22-MAY-2012 hspatel    Added exalogic menu choice
##   23-MAY-2012 ssandrew   Added DA_OUTPUT to Run_Command to support new 
##                          DaDiscovery change and Constants / PM integration.
##   24-MAY-2012 ssandrew   Bug 14109080 - DA_OUTPUT and changed 
##                          Check_Write_Permissions to Check_User_Permissions
##                          to support SunOS and groups root/bin
##   01-JUN-2012 ssandrew   Fixed typo in Check_Java_Install () that was caused
##                          wls's JVM to not be discovered 3 directories back.
##   12-JUN-2012 ssandrew   Changed who am i to use who to support QA cron.
##                          added WHO alias and used in Check_User_Permissions
##   25-JUN-2012 ssandrew   Had to add -m to WHO command because on linux it
##                          shows all users unless specified. 
##   28-JUN-2012 ssandrew   SKIP_USER_CHECK env varible if set to anything will
##                          skip the Unix ID running matching the installed user
##   29-JUN-2012 ssandrew   Bug 14257670 - PERFORMANCE BUG IN DADISOVERY   
##   29-Aug-2012 rrakrish   minimum changes needed to run shell script on mac osx
## ============================================================================

Set_Command_Vars()
{
  ## Things we still need to make this little part work:
  ## The possible locations and specifications for native commands.
  _usrLocalBinDir="/usr/local/bin"
  _usrBinDir="/usr/bin"
  _binDir="/bin"
  ## The "echo" executable
  ECHO="${_binDir}/echo"
  ## The "which" executable
  WHICH="${_usrBinDir}/which"
  ## The "grep" executable
  GREP="${_binDir}/grep"  
  ## The "cut" executable
  if [ -f "${_binDir}/cut" ]
  then
    CUT="${_binDir}/cut"
  elif [ -f "${_usrBinDir}/cut" ]
  then
    CUT="${_usrBinDir}/cut"
  fi
  ## The "uname" executable
  if [ -f "${_binDir}/uname" ]
  then
    UNAME="${_binDir}/uname"
  elif [ -f "${_usrBinDir}/uname" ]
  then
    UNAME="${_usrBinDir}/uname"
  fi
  PLATFORM=`${UNAME} | ${CUT} -f1`
  ## The "awk" executable
  if [ -f "${_binDir}/awk" ]
  then
    AWK="${_binDir}/awk"
  elif [ -f "${_usrBinDir}/awk" ]
  then
    AWK="${_usrBinDir}/awk"
  fi
  if [ "$PLATFORM" = "SunOS" ]
  then
     if [ -f "${_binDir}/nawk" ]
    then
        AWK="${_binDir}/nawk"
    elif [ -f "${_usrBinDir}/nawk" ]
    then
        AWK="${_usrBinDir}/nawk"
    fi
  fi
  ## The "who" executable
  if [ -f "${_usrBinDir}/who" ]
  then
    WHO="${_usrBinDir}/who -m"
  elif [ -f "${_binDir}/who" ]
  then
    WHO="${_binDir}/who -m"
  else 
    WHO="who -m"
  fi
    
  ## The "tr" executable
  TR="${_usrBinDir}/tr"
  ## The "dirname" executable
  DIRNAME="${_usrBinDir}/dirname"
  FIND=${_usrBinDir}/find
  CHMOD=${_binDir}/chmod
  MKDIR=${_binDir}/mkdir
  MKDIRP="${_binDir}/mkdir -p"
}

Set_DA_Home ()
{
###############################################################################
##
## Set_DA_Home - If DA_HOME is set, verify it's correct, and use it.
##               Else, get it from the calling command and verify it.
##               If we can't get it from either place, exit gracefully.
##
###############################################################################

if [ ! -z "${DA_HOME}" ]; then
  # Let's confirm the value they set is correct. If we can't find our
  # library under it, it's a bad value.
  if [ -r "${DA_HOME}/lib/dacore.jar" ]; then
    # Found our .jar - set a variable so we can skip deriving it
    DA_HOME_OK="Y"
  fi	
fi

if [ "${DA_HOME_OK}" != "Y" ]; then
    # Derive it from the command that called us
    DA_BIN_HOME=`${DIRNAME} "$0"`
    DA_HOME=`cd "${DA_BIN_HOME}";cd ..;pwd`

    # Test again to be sure we're right
    if [ -r "${DA_HOME}/lib/dacore.jar" ]; then
      # Found our .jar
	Debug "DA_HOME is set to ${DA_HOME}"
      export DA_HOME
    else
      # We don't really have anywhere else to look - give error and exit...
      ${ECHO} "ERROR: Unable to locate the DA_HOME directory. "
      ${ECHO} "Please set and export DA_HOME and retry your command."
      exit 4
    fi
  fi

}

Set_Java_Home()
{

Debug "JAVA_HOME is ${JAVA_HOME}"

TEMP_JAVA_DIR5=`ls -d ${DA_HOME}/../../../jdk*/jre 2> /dev/null`
Debug "TEMP_JAVA_DIR5 is ${TEMP_JAVA_DIR5}"

TEMP_JAVA_DIR6=`ls -d ${DA_HOME}/../../../jrockit*/jre 2> /dev/null`
Debug "TEMP_JAVA_DIR6 is ${TEMP_JAVA_DIR6}"

if [ -x "${ORACLE_HOME}/jdk/bin/java" -a "x${ORACLE_HOME}" != "x" ]; then
  Debug "_JAVA_HOME is ${ORACE_HOME}/jdk"
  _JAVA_HOME="${ORACLE_HOME}/jdk"
elif [ -x "${ORACLE_HOME}/jre/bin/java" -a "x${ORACLE_HOME}" != "x" ]; then
  Debug "_JAVA_HOME is ${ORACLE_HOME}/jre"
  _JAVA_HOME="${ORACLE_HOME}/jre"
elif [ -x "${TEMP_JAVA_DIR5}/bin/java"  -a "x${TEMP_JAVA_DIR5}" != "x"  ]; then
  Debug "_JAVA_HOME is ${TEMP_JAVA_DIR5}"
  _JAVA_HOME="${TEMP_JAVA_DIR5}"
elif [ -x "${TEMP_JAVA_DIR6}/bin/java" -a "x${TEMP_JAVA_DIR6}" != "x"  ]; then
  Debug "_JAVA_HOME is ${TEMP_JAVA_DIR6}"
  _JAVA_HOME="${TEMP_JAVA_DIR6}"
elif [ -x "${JAVA_HOME}/bin/java"  -a "x${JAVA_HOME}" != "x" ]; then
  Debug "_JAVA_HOME is ${JAVA_HOME}"
  _JAVA_HOME="${JAVA_HOME}"
elif [ "x`${WHICH} java | ${GREP} 'no java in'`" = "x" ]; then
  ## so if java *IS* in the path, use it
  TWO_UP=`${WHICH} java`
  ONE_UP=`dirname "${TWO_UP}"`
  _JAVA_HOME=`dirname "${ONE_UP}"`
  Debug "Using the java which is already in the path: ${TWO_UP}"
else
   ${ECHO} "ERROR: Could not find a java executable in the PATH or any of:"
   ${ECHO} "       ORACLE_HOME/jdk/bin directory"
   ${ECHO} "       ORACLE_HOME/jre/bin directory"
   ${ECHO} "       MW_HOME/jdk*/jre/bin directory"
   ${ECHO} "       MW_HOME/jrockit*/jre/bin directory"
   ${ECHO} "       WL_HOME/../jdk*/jre/bin directory"
   ${ECHO} "       WL_HOME/../jrockit*/jre/bin directory"
   ${ECHO} "       DA_HOME/../../../jdk*/jre/bin directory"
   ${ECHO} "       DA_HOME/../../../jrockit*/jre/bin directory"
   ${ECHO} "       JAVA_HOME/bin directory"
   exit 2
fi

JAVA_HOME="${_JAVA_HOME}"
PATH=${JAVA_HOME}:${JAVA_HOME}/bin:$PATH:.
export JAVA_HOME PATH
}


##
##  Method assumes that the JAVA_HOME was setup first calling
##  Set_Java_Home(). 
##  a) This routine sets the JAVA_HOME_SETUP_OK to false if the java 
##     executable version is not > REQUIRED_VERSION_VALUE
##     (1.4.2) currently.
##  b) Confirms that the java executable is not of type GCC based
##     on java -version output. 
##
##  NOTE: This is currently running before DaDiscovery but could be moved
##        if needed for some future reason because DaDiscover does work 
##        using JDK GCC Type.
##
Check_Java_Install ()
{

JAVA_HOME_SETUP_OK=true;
DAJAVA_VERSION=/tmp/javaVerCheck.$$
#  To specify the required version,
# set the REQUIRED_VERSION to the major version required,
# e.g. 1.3, but not 1.3.1.
REQUIRED_VERSION_VALUE=1.4.2

# Transform the required version string into a number that
# can be used in comparisons
REQUIRED_VERSION=`echo $REQUIRED_VERSION_VALUE | sed -e 's;\.;0;g'`

# Check JAVA_HOME directory to see if Java version is adequate
  if [ $JAVA_HOME ];then
    JAVA_EXE=$JAVA_HOME/bin/java
    # NOTE: Some jvm's such as gij (GNU libgcj) java -version
    # only goes to std.out, so need 2> and 1> or &> So if cant read bytes
    # out of file -s, then run the other version.
    $JAVA_EXE -version 2> $DAJAVA_VERSION
    if [ ! -s $DAJAVA_VERSION ];then
      $JAVA_EXE -version 1> $DAJAVA_VERSION
    fi
    # Just in case it is long version: 1.6.2_232xx need to substr to 5
    VERSION=`cat $DAJAVA_VERSION | grep "java version" | sed 's/\"//g' | awk '{ print $3 }' | sed -e 's;\.;0;g' | awk '{ print substr($1, 1, 5); }'`
    # ${ECHO} "SHOW VERSION: $VERSION vs $REQUIRED_VERSION"
    
    ############################################################################
    # JAVA TYPE CHECK: ie. cannot be GCC or GNU
    ############################################################################
    JDK_TYPE_GCC=`grep "(GCC)" $DAJAVA_VERSION | awk '{print $2}'`
    JDK_TYPE_GNU=`grep "(GNU" $DAJAVA_VERSION | awk '{print $2}'`
    if [ "${JDK_TYPE_GCC}" != "" -o  "${JDK_TYPE_GNU}" != ""  ];then
      ${ECHO}
      ${ECHO} "ISSUE: DA does not support GCC or GNU JDK in: `which java`"
      ${ECHO} "Please either:"
      ${ECHO} " a) Point to Oracle Product JDK HOME or "
      ${ECHO} " b) Install Oracle Java JDK"
      ${ECHO}
      ${ECHO} "    And then set JAVA_HOME to that directory or put the new"
      ${ECHO} "    java in your PATH."
      JAVA_HOME_SETUP_OK=false;
      JAVA_VERSION_ISSUE=`cat $DAJAVA_VERSION`
    fi
    
    ############################################################################
    # VERSION CHECK: > 1.4.2 currently
    ############################################################################
    if [ "${VERSION}" != "" -a "${REQUIRED_VERSION}" != "" ]; then
      if [ $VERSION -ge $REQUIRED_VERSION ]; then    
        JAVA_HOME=`echo $JAVA_EXE | awk '{ print substr($1, 1, length($1)-9); }'`
        # echo "OK: ge is true"
      else
        JAVA_HOME=
        ${ECHO}
        ${ECHO} "ISSUE: DA requires an upgrade of JDK version to >= $REQUIRED_VERSION_VALUE"
        ${ECHO} " Note: Using java currently in: `which java`"
        JAVA_HOME_SETUP_OK=false;
        JAVA_VERSION_ISSUE=`cat $JAVA_VERSION_ISSUE`
      fi
    else 
       ${ECHO} "WARNING: Could not confirm JDK version and type."
    fi
  
  else 
    ${ECHO} "ISSUE: Could not find a JAVA_HOME, set in PATH or export a valid JAVA_HOME"
    JAVA_HOME_SETUP_OK=false;
  fi
  
  if [ -w $DAJAVA_VERSION ];then
    rm $DAJAVA_VERSION
  fi 
  
  export JAVA_HOME_SETUP_OK  
}


Show_Help ()
{

${ECHO} "NAME
       da.sh - Run Diagnostic Assistant from the command line
SYNOPSIS
       da.sh [OPTION] [FLAG]
OPTIONS
       Run Diagnostic tool specified by OPTION:
       adr - Automatic Diagnostic Repository
             Valid flags for adr are:  -help, -summary, -collect, -custom
       ocm - Oracle Configuration Manager
             Valid flags for ocm are:  -help, -summary, -collect, -custom
       rda - Remote Diagnostic Agent
             Valid flags for rda are:  -help, -summary, -collect, -custom
   collect - Runs each collector above (rda,ocm,adr) with defaults settings
   summary - Shows summary of the above collectors adr, ocm, rda
             Valid flags for summary is: -detail

      Guided Diagnostic Menus 
      menu - Starts default Diagnostic Menu System
   exadata - Starts Exadata Diagnostic Menu
  exalogic - Starts Exalogic Diagnostic Menu
   getmenu - Starts Diagnostic Menu from MOS Knownledge Article Note#
             Required flag is: getmenu 201804.1 
             
   version - Displays the current version DA
"

## 14-FEB-2012 Vikki - Removed until the super collector is implemented
##    collect - Generic Api call to collect for a specific Product and Error
##             Valid flags for collect are: -help, -status, -view
##               status - Show Collection Status for all Collectors
##               view   - Show Collection Summary
  exit
}

###############################################################################
##
## Trap_signal
##
## Trap_signal is called when events 1 (HUP), 2 (INT) and 15 (TERM) occur.
## It displays the list of still active processes (if any) and displays them
## to the user. 
##
###############################################################################

Trap_Signal ()
{

  #############################################################################
  ##
  ## find_children
  ##
  ## find_children is a recursive subroutine that just builds a list of child,
  ## grandchild, etc. processes and appends the PID's to the KILL_LIST
  ## variable. It takes a PID as its parameter.
  ##
  #############################################################################

  find_children() {

    CURR_MY_PPID=${1}
    arraycounter=1

    ## If the PID passed isn't blank, then find the children
    if [ "x${CURR_MY_PPID}" != "x" ]; then
      ## echo "MY PPID is ${CURR_MY_PPID}"

      LIST_OF_CHILDREN=`ps -ef| awk '$3 == '${CURR_MY_PPID}' { print $2 }'`
      ## echo "List of children for ${CURR_MY_PPID} is ${LIST_OF_CHILDREN}"

      ## Loop through the children, checking to make sure it's not the
      ## original PID, and adding it to the end of KILL_LIST. Then call
      ## find_children again recursively on each one.
      for i in ${LIST_OF_CHILDREN}
        do
          ## echo "i is currently ${i}"
          if [ ${i} -ne ${CURR_MY_PPID} ]; then
            KILL_LIST=`echo "${KILL_LIST} ${i}"`
            find_children ${i}
          fi
      done
    fi
  }
  
  echo "Checking for child processes before terminating..."

  ## MY_PPID will hold the parent of da.sh command, kill everything
  ## under it
  DA_SH_PS=`ps -ef | grep -v "grep" | grep "da.sh menu" | tail -1`
  MY_PPID=`echo ${DA_SH_PS} | awk '{print $3}'`
  KILL_LIST=""

  find_children ${MY_PPID}

  ##echo "Final KILL_LIST is ${KILL_LIST}"

  for a_proc in ${KILL_LIST}
    do
      echo "Killng child process ${a_proc}..."
      ## Hush the output in case the job completed already in
      ## the meantime...
      kill -9 ${a_proc} 2>/dev/null
  done

  echo "All children have been terminated. Now exiting..."
  exit
}



Parse_Args ()
{

## First param will be the utility name or the word "start"

UTIL_NAME=`${ECHO} ${ARGS} | ${AWK} '{print $1}'`
export UTIL_NAME

## Get the 2nd parm so we know what to run...
    P1=`${ECHO} ${ARGS} | ${AWK} '{print $2}'`
    P2=`${ECHO} ${ARGS} | ${AWK} '{print $3}'`
    P3=`${ECHO} ${ARGS} | ${AWK} '{print $4}'`
    P4=`${ECHO} ${ARGS} | ${AWK} '{print $5}'`
    P5=`${ECHO} ${ARGS} | ${AWK} '{print $6}'`
    P6=`${ECHO} ${ARGS} | ${AWK} '{print $7}'`
    P7=`${ECHO} ${ARGS} | ${AWK} '{print $8}'`
    P8=`${ECHO} ${ARGS} | ${AWK} '{print $9}'`
    P9=`${ECHO} ${ARGS} | ${AWK} '{print $10}'`
    P10=`${ECHO} ${ARGS} | ${AWK} '{print $11}'`
    P11=`${ECHO} ${ARGS} | ${AWK} '{print $12}'`
    P12=`${ECHO} ${ARGS} | ${AWK} '{print $13}'`
    P13=`${ECHO} ${ARGS} | ${AWK} '{print $14}'`
    export P1 P2 P3 P4 P5 P6 P7 P8 P9 P10 P11 P12 P13

    Debug "PARAMs 1 thru 8 are:  $P1 $P2 $P3 $P4 $P5 $P6 $P7 $P8"
    Debug "PARAMs 9 thru 13 are: $P9 $P10 $P11 $P12 $P13"

case "${UTIL_NAME}" in

 "adr" )

    if [ "${P1}" = "-help" ]; then
      UTIL_PARAM="-adr_help"
      export UTIL_PARAM
    elif [ "${P1}" = "-summary" ]; then
      UTIL_PARAM="-summary ${P2} ${P3} ${P4} ${P5} ${P6} "
      export UTIL_PARAM
    elif [ "${P1}" = "-collect" ]; then
      UTIL_PARAM="-collect"
      export UTIL_PARAM
    elif [ "${P1}" = "-custom" ]; then
      UTIL_PARAM="-custom ${P2} ${P3} ${P4} ${P5} ${P6} "
      UTIL_PARAM2="${P7} ${P8} ${P9} ${P10} ${P11} ${P12}"
      ${ECHO} "CALLING: $UTIL_PARAM $UTIL_PARAM2"
      export UTIL_PARAM UTIL_PARAM2
    else
      UTIL_PARAM="${P1} ${P2} ${P3} ${P4} ${P5} ${P6} "
      UTIL_PARAM2="${P7} ${P8} ${P9} ${P10} ${P11} ${P12}"
      ${ECHO} "CALLING: $UTIL_PARAM $UTIL_PARAM2"
      export UTIL_PARAM UTIL_PARAM2
    fi

    JAVA_PARMS="oracle.sysman.da.cli.AdrCli ${UTIL_PARAM} ${UTIL_PARAM2}"
    CMD_DESCR="Running ADR with parameter ${UTIL_PARAM} ${UTIL_PARAM2}"
    export JAVA_PARMS CMD_DESCR
    ;;

  "ocm" )

    if [ "${P1}" = "-help" ]; then
      UTIL_PARAM="-ocm_help"
      export UTIL_PARAM
    elif [ "${P1}" = "-summary" ]; then
      UTIL_PARAM="-ocm_summary ${P2} ${P3} ${P4} ${P5} ${P6} "
      export UTIL_PARAM
    elif [ "${P1}" = "-collect" ]; then
      UTIL_PARAM="-collect"
      export UTIL_PARAM
    elif [ "${P1}" = "-custom" ]; then      
      UTIL_PARAM="-custom ${P2} ${P3} ${P4} ${P5} ${P6} ${P7} "
      UTIL_PARAM2="${P8} ${P9} ${P10} ${P11} ${P12} ${P13}"
      export UTIL_PARAM UTIL_PARAM2
    else
      UTIL_PARAM="${P1} ${P2} ${P3} ${P4} ${P5} ${P6} ${P7} "
      UTIL_PARAM2="${P8} ${P9} ${P10} ${P11} ${P12} ${P13}"
      ${ECHO} "CALLING: $UTIL_PARAM $UTIL_PARAM2"
      export UTIL_PARAM UTIL_PARAM2
    fi

    JAVA_PARMS="oracle.sysman.da.cli.OcmCli ${UTIL_PARAM} ${UTIL_PARAM2}"
    CMD_DESCR="Running OCM with parameter ${UTIL_PARAM} ${UTIL_PARAM2}"
    export JAVA_PARMS CMD_DESCR
    ;;

  "rda" )

    if [ "${P1}" = "-help" ]; then
      UTIL_PARAM="-rda_help"
      if [ "${P2}" = "profiles" ]; then
        UTIL_PARAM="-rda_profile_list"
      fi
      export UTIL_PARAM
    elif [ "${P1}" = "-summary" ]; then
      UTIL_PARAM="-rda_summary ${P2} ${P3} ${P4} ${P5} ${P6} "
      export UTIL_PARAM
    # Run default collection for target
    elif [ "${P1}" = "-collect" ]; then
      UTIL_PARAM="-rda_collect"
      export UTIL_PARAM
    elif [ "${P1}" = "-custom" ]; then
      UTIL_PARAM="-custom ${P2} ${P3} ${P4} ${P5} ${P6} ${P7} "
      UTIL_PARAM2="${P8} ${P9} ${P10} ${P11} ${P12} ${P13}"
      export UTIL_PARAM UTIL_PARAM2
    else
      UTIL_PARAM="${P1} ${P2} ${P3} ${P4} ${P5} ${P6} ${P7} "
      UTIL_PARAM2="${P8} ${P9} ${P10} ${P11} ${P12} ${P13}"
      ${ECHO} "CALLING: $UTIL_PARAM ${UTIL_PARAM2}"
      export UTIL_PARAM UTIL_PARAM2
    fi

    JAVA_PARMS="oracle.sysman.da.cli.RdaCli ${UTIL_PARAM} ${UTIL_PARAM2}"
    CMD_DESCR="Running RDA with parameter ${UTIL_PARAM} ${UTIL_PARAM2}"
    export JAVA_PARMS CMD_DESCR
    ;;

  "examenu"|"exadata" )
  
    JAVA_PARMS="oracle.sysman.da.cli.DaCli -menu ./menus/exadata.xml"
    CMD_DESCR="Running DA MENU with parameter ${JAVA_PARMS}"
    export JAVA_PARMS CMD_DESCR
    ;;    
    
  "exalogic" )
  
    JAVA_PARMS="oracle.sysman.da.cli.DaCli -menu ./menus/exalogic.xml"
    CMD_DESCR="Running DA MENU with parameter ${JAVA_PARMS}"
    export JAVA_PARMS CMD_DESCR
    ;;    

  "menu" )       
    if  [ "${P1}" = "-demo" ]; then
      JAVA_PARMS="oracle.sysman.da.cli.DaCli -menu ./menus/qa_menus.xml"      
    elif [ "${P1}" != "" ]; then     
      JAVA_PARMS="oracle.sysman.da.cli.DaCli -menu ${P1}"
    else 
    # Update to us Menu of Memus
    #  JAVA_PARMS="oracle.sysman.da.cli.DaCli -menu ./menus/menus.xml"
       JAVA_PARMS="oracle.sysman.da.cli.DaCli -start_menus dynamic"    
    fi
    CMD_DESCR="Running the Core DA MENU with parameter ${JAVA_PARMS}"
    export JAVA_PARMS CMD_DESCR
    ;;    

  "getmenu" )       
    if [ "${P1}" != "" ]; then     
      JAVA_PARMS="oracle.sysman.da.cli.DaCli -mos_menus ${P1}"
    else 
      Show_Help 
    fi
    CMD_DESCR="Running the MOS DA MENU with parameter ${JAVA_PARMS}"
    export JAVA_PARMS CMD_DESCR
    ;;    

  "class" )    
    # ie. class asr.AsrSetup ARGS{n}          
    UTIL_PARAM="${P2} ${P3} ${P4} ${P5} ${P6} ${P7} "
    UTIL_PARAM2="${P8} ${P9} ${P10} ${P11} ${P12} ${P13}"
    export UTIL_PARAM UTIL_PARAM2
    
    JAVA_PARMS="oracle.sysman.da.${P1} ${UTIL_PARAM} ${UTIL_PARAM2}"    
    CMD_DESCR="Running the Core DA Class with parameter ${JAVA_PARMS}"    
    export JAVA_PARMS CMD_DESCR 
    ;;        

  "version" )

    JAVA_PARMS="oracle.sysman.da.cli.DaCli -version"
    CMD_DESCR="Running the Core DA MENU with parameter ${JAVA_PARMS}"
    export JAVA_PARMS CMD_DESCR
    ;;   
  
  ## 14-FEB-2012 - Vikki - Comment "collect" out until we implement a
  ## SUPER collector routine
  ## "collect" )
    ##  java DaCollector -collect [-target j2ee_application] [-upload]
    ##  java DaCollector -status 
    ##  Case1: da.sh collect -target j2ee_application
	  ##  Case2: da.sh collect -status
  ## 
  ##   if [ "${P1}" = "-help" ]; then
  ##     UTIL_PARAM="-help"
  ##     export UTIL_PARAM
  ##   elif [ "${P1}" = "-summary" ]; then
  ##     UTIL_PARAM="-summary  ${P2} ${P3} ${P4} ${P5} ${P6} "
  ##     export UTIL_PARAM 
  ##   elif [ "${P1}" = "-view" ]; then
      # -view_collection -details false -limit_type rda
  ##     UTIL_PARAM="-view_collection"
  ##     export UTIL_PARAM
    # SETTING OS MODULE AS DEFAULT FOR DEMO
  ##   else
  ##     UTIL_PARAM="-collect"
  ##     export UTIL_PARAM
  ##   fi

  ##   JAVA_PARMS="oracle.sysman.da.apps.DaCollector ${UTIL_PARAM}"
  ##   CMD_DESCR="Running Demo Collector with parameter ${UTIL_PARAM}"
  ##   export JAVA_PARMS CMD_DESCR
  ##  ;;
    
  "asrsetup" )

    JAVA_PARMS="oracle.sysman.da.asr.AsrSetup"
    CMD_DESCR="Running the Core DA MENU with parameter ${JAVA_PARMS}"
    export JAVA_PARMS CMD_DESCR
    ;;   
    
  "asrcollect" )
    ##  java AsrCollector -collect -target j2ee_application -error BEA-000383
        ## show incident -mode detail -p 'incident_id=37252'
        ##  Case1: da.sh asrcollect -target j2ee_application -error BEA-000383
        ##  Case2: da.sh asrcollect -target oracle_database 
        ##               -error ORA-700 -upload
        ##  Case3: da.sh asrcollect -target oracle_database -error ORA-600 
        ##               -error_msg "kfnsMasterWaitPriv" -xargs 
        ##               "/u01/app/oracle/diag/rdbms/v1121/V1121/incident/\
        ##               incdir_37252/V1121_ora_25705_i37252.trc"        
        ##
        ##  /* Example Script calling current da.sh
        ##     Main usage (extra_args=incident_id)
        ## * #!/bin/sh
        ## *  ./bin/da.sh asrcollect -target oracle_database -error ORA-700 \
        ## *     -error_msg NODE2-sr_number 123 -output_path /tmp/asr1.txt \
        ## *     -extra_args 41100
        ## */
    
    UTIL_PARAM="-collect ${P1} ${P2} ${P3} ${P4} ${P5} ${P6} "
    UTIL_PARAM2="${P7} ${P8} ${P9} ${P10} ${P11} ${P12} ${P13}"
    export UTIL_PARAM UTIL_PARAM2
        
    if [ "${P1}" = "-summary" ]; then
      UTIL_PARAM="-summary  ${P2} ${P3} ${P4} ${P5} ${P6} "
      export UTIL_PARAM
    fi

    if [ "${P1}" = "-help" ]; then
      UTIL_PARAM="-help"
      export UTIL_PARAM
    fi

    JAVA_PARMS="oracle.sysman.da.asr.AsrCollector ${UTIL_PARAM} ${UTIL_PARAM2}"
    CMD_DESCR="Running AsrCollector w/parameter ${UTIL_PARAM} ${UTIL_PARAM2}"
    export JAVA_PARMS CMD_DESCR
    ;;

  "cli" )
    JAVA_PARMS="oracle.sysman.da.cli.DaCli ${UTIL_PARAM}"
    CMD_DESCR="Running DaCli with no arguments to start cli prompt version."
    export JAVA_PARMS CMD_DESCR
    # java -classpath %CLASSPATH% oracle.sysman.da.cli.DaCli
   ;; 

  "verify" )
    UTIL_PARAM="${P2} ${P3} ${P4} ${P5} ${P6} ${P7} "
    JAVA_PARMS="oracle.sysman.da.discover.DaDiscovery -verify ${UTIL_PARAM}"    
    CMD_DESCR="Running DaCli with no arguments to start cli prompt version."
    export JAVA_PARMS CMD_DESCR    
   ;; 

  "create" )
    UTIL_PARAM="${P2} ${P3} ${P4} ${P5} ${P6} ${P7} "
    # JAVA_PARMS="oracle.sysman.da.cli.DaDiscovery -create -f config/checksum.csv ${UTIL_PARAM}"    
    JAVA_PARMS="oracle.sysman.da.discover.DaDiscovery -create ${UTIL_PARAM}"    
    CMD_DESCR="Running DaCli with no arguments to start cli prompt version."
    export JAVA_PARMS CMD_DESCR    
   ;; 



  "em" )    
    # ie. em -metric_file_xml ./menus/run_one_command.xml
    UTIL_PARAM="${P1} ${P2} ${P3} ${P4} ${P5} ${P6} ${P7} "
    UTIL_PARAM2="${P8} ${P9} ${P10} ${P11} ${P12} ${P13}"
    export UTIL_PARAM UTIL_PARAM2
    
    JAVA_PARMS="oracle.sysman.da.cli.DaAgentCli ${UTIL_PARAM} ${UTIL_PARAM2}"    
    CMD_DESCR="Running the Core DA Class with parameter ${JAVA_PARMS}"    
    export JAVA_PARMS CMD_DESCR 
    ;;        


  "discover_menu" )
    # Runs the new daDiscovery class to setup the classpath and
	# create the env to source
    #UTIL_PARAM="${P1} ${P2} ${P3} ${P4} ${P5} ${P6} ${P7} "
	UTIL_PARAM="-discover_menu"
    UTIL_PARAM2="${P8} ${P9} ${P10} ${P11} ${P12} ${P13}"
    export UTIL_PARAM UTIL_PARAM2
	
    JAVA_PARMS="oracle.sysman.da.discover.DaDiscovery ${UTIL_PARAM} ${UTIL_PARAM2}"    
    CMD_DESCR="Running the Core DA Class with parameter ${JAVA_PARMS}"    
    export JAVA_PARMS CMD_DESCR 
    ;;        
	
	
  * )

    ## They did not pass ANY parameters or passed an invalid one
    Show_Help
    ;;

  esac

}

Debug ()
{
  if [ "${DEBUG}" = "on" ];then
    ${ECHO} "$1"
  fi
}

##
## ssandrew 5/23/2012         Added DA_OUTPUT to Run_Command to support new
##                            DaDiscovery env figuring it out
##
Run_Command ()
{
  ## Bug 13516466 - Added ${JAVA_HOME}/bin in front of both the Debug and
  ## actual execution java statements  
    Debug "Executing command ${JAVA_HOME}/bin/java -DDA_OUTPUT=${DA_OUTPUT} -classpath ${CLASSPATH} ${JAVA_PARMS} "
	
    ${JAVA_HOME}/bin/java -DDA_OUTPUT=${DA_OUTPUT} -classpath ${CLASSPATH} ${JAVA_PARMS}    
}

Run_summary_all ()
{
		## Get the 2nd parm if user requests detail... 
    ## ssandrew changed to support -detail, but Java wants just detail
    UTIL_PARAM2=`${ECHO} ${ARGS} | ${AWK} '{print $2}'`
    if [ "${UTIL_PARAM2}" = "-detail" ];then
      UTIL_PARAM2="detail"
    fi
## ADR
        UTIL_NAME=adr
        UTIL_PARAM="-summary"
        JAVA_PARMS="oracle.sysman.da.cli.AdrCli ${UTIL_PARAM} ${UTIL_PARAM2}"
        CMD_DESCR="Running ADR with parameter ${UTIL_PARAM} ${UTIL_PARAM2}"
        export JAVA_PARMS CMD_DESCR UTIL_NAME 
        Run_Command
## RDA
        UTIL_NAME=rda
        UTIL_PARAM="-rda_summary"
        JAVA_PARMS="oracle.sysman.da.cli.RdaCli ${UTIL_PARAM} ${UTIL_PARAM2}"
        CMD_DESCR="Running RDA with parameter ${UTIL_PARAM} ${UTIL_PARAM2}"
        export JAVA_PARMS CMD_DESCR UTIL_NAME
        Run_Command
## OCM
        UTIL_NAME=ocm
        UTIL_PARAM="-ocm_summary"
        JAVA_PARMS="oracle.sysman.da.cli.OcmCli ${UTIL_PARAM} ${UTIL_PARAM2}"
        CMD_DESCR="Running OCM with parameter ${UTIL_PARAM} ${UTIL_PARAM2}"
        export JAVA_PARMS CMD_DESCR UTIL_NAME
        Run_Command
}

Run_collect_all ()
{
## ADR
        UTIL_NAME=adr
        UTIL_PARAM="-collect"
        JAVA_PARMS="oracle.sysman.da.cli.AdrCli ${UTIL_PARAM} ${UTIL_PARAM2}"
        CMD_DESCR="Running ADR with parameter ${UTIL_PARAM} ${UTIL_PARAM2}"
        export JAVA_PARMS CMD_DESCR UTIL_NAME
        Run_Command
## RDA
        UTIL_NAME=rda
        UTIL_PARAM="-rda_collect"
        JAVA_PARMS="oracle.sysman.da.cli.RdaCli ${UTIL_PARAM} ${UTIL_PARAM2}"
        CMD_DESCR="Running RDA with parameter ${UTIL_PARAM} ${UTIL_PARAM2}"
        export JAVA_PARMS CMD_DESCR UTIL_NAME
        Run_Command
## OCM
        UTIL_NAME=ocm
        UTIL_PARAM="-collect"
        JAVA_PARMS="oracle.sysman.da.cli.OcmCli ${UTIL_PARAM} ${UTIL_PARAM2}"
        CMD_DESCR="Running OCM with parameter ${UTIL_PARAM} ${UTIL_PARAM2}"
        export JAVA_PARMS CMD_DESCR UTIL_NAME
        Run_Command
}

##
## Compares DA Install User with current user running DA
##  - DA is not supported unless they are the same even though
##  - it is possible to change permissions on files to make it work.
##  - may change in future to support this due to dba group etc.
##
## If non-Solaris platform, requires DA installed Software owner unix_id to
## match the current exection owner, or be root.
##
Check_User_Permissions ()
{
  DA_INSTALL_USER=`ls -l bin/da.sh | ${AWK} '{print $3}'`
  # DA_CURRENT_USER=`who am i | ${AWK} '{print $1}'`
  # Had a problem finding this when running from a cron job, so using who and
  # added as alias as well at top.
  DA_CURRENT_USER=`${WHO} | tail -1 | ${AWK} '{print $1}'`
  if [ "${DA_INSTALL_USER}" != "${DA_CURRENT_USER}" -a "${PLATFORM}" != "SunOS" -a  "${DA_CURRENT_USER}" != "root" ];then
    NOT_SOFTWARE_OWNER="Installed as: ${DA_INSTALL_USER} not same as: ${DA_CURRENT_USER}"
    ${ECHO} "ERROR: Not supported to execute DA as different Unix User."
    ${ECHO} "       Install unix id not the same as current user"
    ${ECHO} "       Installed as: ${DA_INSTALL_USER} not same as: ${DA_CURRENT_USER}" 
    exit 1
  fi
  
  # Sun Check for correct group if not root
  if [ "${PLATFORM}" = "SunOS" -a "${DA_CURRENT_USER}" != "root" -a "${DA_HOME}" = "/usr/lib/rda/da" ];then
    GROUP_OK=`groups | egrep 'root|bin'`
    if [ "${GROUP_OK}" = "" ];then
      NOT_CORRECT_GROUP=`groups`
      ${ECHO} "ERROR: On SunOS user must be either root or in root or bin group."
      ${ECHO} "       a) Run as root or"
      ${ECHO} "       b) have ${DA_CURRENT_USER} added to bin group."                
      exit 1
    fi
  fi
}


## ============================================================================
## MAIN PROGRAM
## ============================================================================
if [ "${DEBUG}" = "" ]; then
  DEBUG="off"
  export DEBUG
fi

ARGS="$*"
export ARGS

## Do our setup before we run...
Set_Command_Vars
Set_DA_Home
Set_Java_Home
Check_Java_Install
# Hard Failure if Wrong Java Version or Type - UI Messages in Check_Java_Install
if [ "${JAVA_HOME_SETUP_OK}" = "false" ];then
 exit
fi

## 12-MAR-2012 Vikki - Bug 13487011 - Add trap command
trap 'Trap_Signal' 1 2 15

cd  "${DA_HOME}"
if [ "${SKIP_USER_CHECK}" = "" ];then
  Check_User_Permissions
fi

## Run DaDiscovery first!

Debug  "Executing command ${JAVA_HOME}/bin/java -classpath ${DA_HOME}/lib/dacore.jar  "
Debug "oracle.sysman.da.discover.DaDiscovery -discover_menu " 
 
 ## If DEBUG is on in java, we get all kinds of stdout, but just need the last 
 ## "word" to get the filename
 
DISC_RESULTS=`${JAVA_HOME}/bin/java -classpath "${DA_HOME}/lib/dacore.jar" \
	  oracle.sysman.da.discover.DaDiscovery -discover_menu `

ENV_FILE=`${ECHO} ${DISC_RESULTS} | ${AWK} '{print $NF}'`

## If DEBUG is turned in da.sh, then show all that debug stuff we got back from java
if [ "${DEBUG}" = "on" ]; then
   Debug "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
   Debug "DEBUGGING INFO:"
   Debug "${DISC_RESULTS}"
   Debug "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
fi

## Now, as long as we can read the file, source it
  if [ -r "${ENV_FILE}" ]; then
    . "${ENV_FILE}"
    
    # Bug 14257670
    if  [ ! -w "${DA_OUTPUT}/da_collection.log" -o ! -w "${DA_OUTPUT}/log/diagnostic_assistant.log" -o ! -r "${DA_OUTPUT}/spool" ]; then
      ${FIND} ${DA_OUTPUT} -name "*.*" -exec ${CHMOD} u+rw {} \;       
    fi
    if [ ! -w "${DA_HOME}/config/da.properties" ];then
      ${FIND} "${DA_HOME}/config" -name '*.properties' -exec ${CHMOD} u+w {} \;
    fi  
  else
    echo "======================================================================"
    echo "ERROR: Unable to generate and source environment file ${ENV_FILE}"
    echo "Diagnostic Assistant cannot function without this file."
    echo "======================================================================"
    exit 1
  fi

  ## After sourcing, remove it unless DEBUG is on
  if [ "${DEBUG}" = "off" ]; then
    rm -rf "${ENV_FILE}"
  else 
    echo "ENV_FILE =  ${ENV_FILE}"
  fi

  ## If it's one of the special "ALL" commands, peel off and do those differently...
  UTIL_CMD=`${ECHO} ${ARGS} | ${AWK} '{print $1}'`
  if [ "${UTIL_CMD}" = "summary" ]; then
    Run_summary_all
  elif  [ "${UTIL_CMD}" = "collect" ]; then
    Run_collect_all 
   ## This is the "normal" case for all other commands
  else
    Debug "Calling Parse_Args"
    Parse_Args
    Debug "Calling Run_command"
    Run_Command
  fi

