#!/bin/sh

######################################################################
# Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved.
#
#  phnguyen  5/17/04   Create and support
#                          -jdk, -jre, -oh
#  shgangul  6/21/04   Check for OPATCH_DEBUG env variable
#  shgangul  7/12/04   opatch can be invoked from any directory
#  shgangul  7/15/04   use jdk to invoke opatch, otherwise use jre
#  shgangul  7/16/04   Display the Java call for debug
#  phnguyen  7/19/04   add "./" to class path
#  phnguyen  7/31/04   more jre parsing, error if can't find java
#  shgangul  8/05/04   change opatch to oracle.opatch package
#  shgangul  8/27/04   sync up with opatch.bat to support OPATCH_PLATFORM_ID
#  phnguyen  8/04/04   Support OPATCH_PLATFORM_ID=integer
#  shgangul  8/27/04   add fallback schemes for jre/jdk
#  phnguyen  8/30/04   Print "OPatch Succeeded" if OK
#  shgangul  9/01/04   Further changes for jre/jdk priorities
#  shgangul  9/07/04   java not present in jdk/jre option, error out
#  shgangul  12/15/04  Supply PATH variable to java
#  shgangul  02/02/05  Minor bug in parsing -jdk option
#  phnguyen  02/01/05  Introduce OPATCH_NO_FUSER to bypass fuser check
#  vsriram   02/28/05  Print "OPatch Succeeded" if exit code is b/w 171 and 200
#  shgangul  03/15/05  Pass in properties to OPatch
#  phnguyen  05/14/05  add opatchprereq.jar and opatchutil.jar to class path 
#  shgangul  07/18/05  Do not pass PATH env var to OPatch JVM
#  vsriram   12/06/05  Change the permissions of .patch_storage and set umask
#  vsriram   12/13/05  Use -d inside if condition, as -e doesnot work on Solaris.
#  vsriram   01/24/06  Remove umask setting and don't change the perm of 
#                      .patch_storage contents
#  vsriram   05/10/06  Return 0 as exit code, even for warnings.
#  vsriram   06/15/06  Put the OPatch/jlib/xmlparserv2.jar in classPath
#  vsriram   06/21/06  Look for Jre 1.5 and then fall back to JDK.
#  vsriram   08/01/06  Remove dependency on xmlparserv2.
#  vsriram   08/17/06  Add opatchactions.jar into classpath
#  phnguyen  10/25/07  Get JRE_MEMORY_OPTIONS fr oui/oraparam.ini, bugsnhkcnt
#  vganesan  02/27/08  Pass $BASE (running directory of 'opatch') as a property
#                      to java invocation. This is needed to locate ocm.zip in 
#                      OPatch.
#  vganesan  03/04/08  Add 'emocmutl.jar' to the classpath
#  vganesan  08/19/08  Check osInfo API/class in emocmutl.jar for IBM based
#                      platforms if 'ocm.zip' is bundled
#  phnguyen  05/20/08  Bug bmmbhmb
#  phnguyen  05/20/08  Bug bmmbhmb
#  vganesan  05/16/08  Bug bkbtkcm
#  vganesan  05/16/08  Bug bkbtkcm
#  phnguyen  10/25/07  Get JRE_MEMORY_OPTIONS fr oui/oraparam.ini, bug-snhkcnt
#  phnguyen  10/25/07  Get JRE_MEMORY_OPTIONS fr oui/oraparam.ini, bug6520958
#  vganesan  03/13/09  Add 'orai18n-mapping.jar' to the classpath
#  phnguyen  06/05/09  Support 'opatch auto [-rollback]'. Need to deal with "abc"
#  phnguyen  06/08/09  Error out of 'opatch auto' is called on a non-crs bundle
#  vganesan  06/23/09  Add 'opatchext.jar' to OPatch classpath 
#  supal     06/29/09  Set MW_HOME, ORACLE_HOME when invoked from FMW Oracle Home
#  vganesan  07/04/09  Add 'opatchfmw.jar' to OPatch classpath
#  supal     10/05/09  Better messages for MW/OH consistency check
#  vganesan  09/09/09  Fix Bug #bkbtkcm
#  vganeasn  10/20/09  Initialize FMW_ERROR to -1
#  phnguyen  11/13/09  Support 11.2 auto_patch.pl
#  supal     11/11/09  Pass Common Home Location to OPatch
#  phnguyen  05/10/10  Remove custom/server check in 'opatch auto'
#  cawan     12/07/10  Fix Bug #10225431, #10212388
#  vganesan  11/12/10  Add BIP classpath
#  vganesan  11/01/10  Fix Bug #9698266
#  vganesan  10/22/10  Add ojmisc.jar, emCfg.jar to classpath
#  vganesan  10/15/10  Add correct ldif path to the classpath
#  vganesan  10/07/10  Add LDIF_PATH to support LDIF classpath temporary
#  cawan     04/07/11  Change oui location logic
#  cawan     05/19/11  Add oraInst.loc of patching OH to system property
#  billi     11/07/12  Fix Bug #15837001
#  billi     12/01/12  Add domain config jar from oracle_common home for fmw12 
#  billi     03/04/13  Fix Bug #16393828 
#  naagrawa  25/03/13  Support for JDK and JRE with white spaces in the path Bug - 16178626
#  billi     03/01/13  Fix Bug #16179038
#  sisiwu    04/19/13  Revert Bug #16178626
#  fisong    09/22/13  Fix Bug #17452748
#  yanxizha  12/13/13  Fix Bug #17881514
#  mencheng  11/24/13  Fix bug #20076933 #19451341 
####################################################################


get_opatch_version(){
    opatch_version_txt=${BASE}/version.txt
   if [ -r ${opatch_version_txt} ]; then
	 opatch_version=`grep "OPATCH_VERSION:" ${opatch_version_txt} | sed 's/OPATCH_VERSION://'`
	echo $opatch_version
   else 
	echo "version_not_readable"
   fi
} 

# OPatch version	JDK version (used in compilation, which is the minimum
#			version needed in runtime)
#
# 11.1			1.6
# 11.2			1.5
# 12.*			1.6
# 13.*			1.6 (opatch13.1 compiled with jdk1.7, target jdk1.6 
#			for backward compatible)

check_java_version_compatible() {
    opatch_version=get_opatch_version
    OPATCH_VERSION=${opatch_version}
    # short_opatch_version is the first two digits of opatch_vesion
    # e.g. for opatch 13.1.0.0.0, short_opatch_version is 13.1
    if [ "$opatch_version" = "version_not_readable" ]; then
        # we didn't manager to get an OPatch version, return 0 indicating passing
        # compatible checking as default
        return 0;
    fi
     short_opatch_version=`echo $opatch_version | cut -c1-4`
    # java_version_digit is the second digit of jdk version
    # e.g. for jdk1.6 java_version_digit is 6
    java_version_digit=`$JAVA -version 2>&1 | awk '/version/ {print $3}' | awk ' BEGIN {FS="."} { print $2 }'`
    if [ "${short_opatch_version}" = "11.2" ]; then
        MIN_JAVA_VERSION="1.5"
        java_version_digit_expected=5
    else
        MIN_JAVA_VERSION="1.6"
        java_version_digit_expected=6
    fi
    if [ ${java_version_digit} -ge ${java_version_digit_expected} ]; then
        return 0;
    else
        return 1;
    fi
    # we didn't manage to do a checking in this case, return 0 indicating passing
    # compatible checking as default
    return 0;
}

init()
{
  BASE=`dirname $0`;
  PWD=`pwd`;
  argCount=$#
  args=$@
   
  # Look for OPATCH_DEBUG env variable
  DEBUG=${OPATCH_DEBUG}
  # Check for OPATCH_DEBUG
  DEBUGVAL=false
  if [ "$DEBUG" = "TRUE" ]; then
     DEBUGVAL=true;
  fi
  if [ "$DEBUG" = "true" ]; then
     DEBUGVAL=true;
  fi
  
  # Look for APPLY_MAKE env variable
  MAKE=${APPLY_MAKE}
  # Check for APPLY_MAKE
  MAKEVAL=false
  if [ "$MAKE" = "TRUE" ]; then
     MAKEVAL=true;
  fi
  if [ "$MAKE" = "true" ]; then
     MAKEVAL=true;
  fi
  
  # Get ORACLE_HOME from environment variable "ORACLE_HOME"
  OH=${ORACLE_HOME}

  # Get OPATCH_JRE_MEMORY_OPTIONS from environment variable "OPATCH_JRE_MEMORY_OPTIONS"
  JRE_MEMORY_OPTIONS=${OPATCH_JRE_MEMORY_OPTIONS}

  # Get Middleware Home from environment variable "MW_HOME"
  MWH=${MW_HOME}

  # Look for OPATCH_PLATFORM_ID
  PLATFORM=${OPATCH_PLATFORM_ID}

  # Look for OPATCH_NO_FUSER
  NO_FUSER=${OPATCH_NO_FUSER}

  # need implicit Oracle Home?
  NO_IMPLICIT_ORACLE_HOME=${OPATCH_NO_IMPLICIT_OH}

  # Look for ORACLE_OCM_SERVICE
  oracleOcmService=""
  if [ "$ORACLE_OCM_SERVICE" != "" ] ; then
     oracleOcmService="-Docm.endpoint=${ORACLE_OCM_SERVICE}"
  fi


  # Preserve the PATH environment variable
  PATHENV=${PATH}

  # BugFix for 4745222
  PLATFORMNAME=`uname`;
  if [ "$PLATFORMNAME" = "AIX" ] ; then
     OBJECT_MODE="32_64"
     export OBJECT_MODE
  fi
  
}

opatchAutoDetect()
{
   autopatch=0;
   autohelp=0;


  if [ "$1" = "auto" ]; then
     autopatch=1
  fi

  if [ $autopatch = 1 ]; then
    if [ $argCount -gt 1 ]; then
      if [ "$2" = "-h" ]; then
         autohelp=1
      elif [ "$2" = "-help" ]; then
         autohelp=1
      fi
    fi
  fi

   i=1
   CMD_ID_EXIST=
  while [ -n "`echo "$PATH" | cut -d: -f${i}`" ] ; do
        if [ -s "`echo "$PATH" | cut -d: -f${i}`/id" ] ; then
                CMD_ID_EXIST="`echo "$PATH" | cut -d: -f${i}`/id"
                break
        fi
        i=`expr $i + 1`
  done


  if [ -z "$CMD_ID_EXIST" ]; then
        if [ $autopatch = 1 ]; then
                echo id command not avaliable!
                echo opatch auto can not proceed without id command!
                exit 1
        fi
  fi
   UID_INFO=`id`
   IS_ROOT=`echo $UID_INFO | grep "^uid=0("`
  if [ ! "$IS_ROOT" = "" ]; then
     if [ "$1" = "-h" ]; then
        autohelp=1
     elif [ "$1" = "-help" ]; then
        autohelp=1
     fi
  fi

  if [ $autohelp = 1 ]; then
    $BASE/crs/auto_patch.pl -h
     exit 
  fi

  if [ $autopatch = 1 ]; then
  # it must be 
  # 'opatch auto'
  # 'opatch auto <patch loc>'
  # 'opatch auto -rollback'
  # 'opatch auto -rollback <patch loc>' 

      if [ $argCount -eq 1 ]; then
         # this must be just 'opatch auto'
         givenLoc=$PWD
         patchdir=`dirname $givenLoc`
         id=`basename $givenLoc`

         # Check to make sure <patch_loc>/custom/server exist
         # if [ ! -d $givenLoc/custom/server ]; then
         #    echo "$givenLoc is not a valid CRS bundle patch location."
         #    $BASE/crs/auto_patch.pl -h
         #    exit -1;         
         # fi

         shift
         # echo $BASE/crs/auto_patch.pl -patchdir $patchdir -patchn $id
         $BASE/crs/auto_patch.pl -patchdir $patchdir -patchn $id
         exit

      elif [ $argCount -gt 1 ] && [ $2 != "-rollback" ]; then
         # either 'opatch auto [other-args]' or 'opatch auto <patch_loc> [other-args]'

         givenLoc=$2
         if [ -d $givenLoc ]; then
            # must be 'opatch auto <patch_loc> other-args'
            # echo "opatch auto <patch_loc> [other-args]"
            givenLoc=$2
            patchdir=`dirname $givenLoc`
            id=`basename $givenLoc`       

            # Check to make sure <patch_loc>/custom/server exist
            # if [ ! -d $givenLoc/custom/server ]; then
            #   echo "$givenLoc is not a valid CRS bundle patch location."
            #   $BASE/crs/auto_patch.pl -h
            #   exit -1;
            # fi

            shift
            shift
            # echo $BASE/crs/auto_patch.pl -patchdir $patchdir -patchn $id $@
            $BASE/crs/auto_patch.pl -patchdir $patchdir -patchn $id $@
            exit
         else
            # must be 'opatch auto [other-args]' or bad patch loc
            # just let auto_patch decide, assume it is 'opatch auto [other-args]
            # echo "opatch auto [other-args]"
            givenLoc=$PWD
            patchdir=`dirname $givenLoc`
            id=`basename $givenLoc`

            # Check to make sure <patch_loc>/custom/server exist
            # if [ ! -d $givenLoc/custom/server ]; then
            #   echo "$givenLoc is not a valid CRS bundle patch location."
            #   $BASE/crs/auto_patch.pl -h
            #   exit -1;
            # fi

            shift
            # echo $BASE/crs/auto_patch.pl -patchdir $patchdir -patchn $id $@
            $BASE/crs/auto_patch.pl -patchdir $patchdir -patchn $id $@
            exit 
         fi 

      elif [ $argCount -gt 1 ] && [ $2 = "-rollback" ]; then
         givenLoc=$2
         # either 'opatch auto -rollback [other-args] or 'opatch auto -rollback <patchloc> [other-args]'
         if [ $argCount -eq 2 ]; then
            # must be just 'opatch auto rollback' 
            givenLoc=$PWD
            patchdir=`dirname $givenLoc`
            id=`basename $givenLoc`

            # Check to make sure <patch_loc>/custom/server exist
            # if [ ! -d $givenLoc/custom/server ]; then
            #   echo "$givenLoc is not a valid CRS bundle patch location."
            #   $BASE/crs/auto_patch.pl -h
            #   exit -1;
            # fi

            shift
            shift
            # echo $BASE/crs/auto_patch.pl -rollback -patchdir $patchdir -patchn $id $@
            $BASE/crs/auto_patch.pl -rollback -patchdir $patchdir -patchn $id $@
            exit
        
         elif [ -d $3 ]; then
            # must be 'opatch auto -rollback <patch_loc> [other-args]
            # echo "opatch auto -rollback <patch_loc> [other-args]"
            givenLoc=$3
            patchdir=`dirname $givenLoc`
            id=`basename $givenLoc`

            # Check to make sure <patch_loc>/custom/server exist
            # if [ ! -d $givenLoc/custom/server ]; then
            #  echo "$givenLoc is not a valid CRS bundle patch location."
            #   $BASE/crs/auto_patch.pl -h
            #   exit -1;
            # fi

            shift
            shift
            shift
            # echo $BASE/crs/auto_patch.pl -rollback -patchdir $patchdir -patchn $id $@
            $BASE/crs/auto_patch.pl -rollback -patchdir $patchdir -patchn $id $@
            exit
         else
            # must be 'opatch auto -rollback [other-args]' or bad patch loc
            # just let auto_patch decide, assume it is 'opatch auto -rollback [other-args]
            # echo "opatch auto -rollback [other-args]"
            givenLoc=$PWD
            patchdir=`dirname $givenLoc`
            id=`basename $givenLoc`

            # Check to make sure <patch_loc>/custom/server exist
            # if [ ! -d $givenLoc/custom/server ]; then
            #   echo "$givenLoc is not a valid CRS bundle patch location."
            #   $BASE/crs/auto_patch.pl -h
            #   exit -1;
            # fi

            shift
            shift
            # echo $BASE/crs/auto_patch.pl -rollback -patchdir $patchdir -patchn $id $@
            $BASE/crs/auto_patch.pl -rollback -patchdir $patchdir -patchn $id $@
            exit

         fi
      else 
     
        echo "Please run 'opatch auto [-rollback] <patch location>'"
        # echo "           'opatch auto [-rollback]' if you are in the patch location." 
        exit -1
      fi
  fi
}

parseCommandLineOPtions()
{

  CMDLINE_OUI=0
  # If -oh is specified, use it to over-ride env. var. ORACLE_HOME
   getOH=0

  # All the OPatch properties to be passed in to Java
  # Format for properties is abc=xyz
  PROPERTIES=""

  # If -jre or -jdk are specified, use it to launch opatch,
  #   with -jdk > -jre.  And we expect there is a "bin/java" underneath
  #   the value supplied
   getJRE=0
   getJDK=0
   getOUI=0
  getInv=0

  JDK=""
  JRE=""
  OUI_LOCATION=""
  FINAL_OUI_LOCATION=""

  # If -mw_home is specified, use it for the next of the session 
  # after verification of its integrity
   getMWHOME=0

  for arg in "$@"; do
    if [ $getOH = 1 ]; then
       OH=$arg
       getOH=0
    fi
    if [ $getJRE = 1 ]; then
       JRE=$arg
       getJRE=0
    fi
    if [ $getJDK = 1 ]; then
       JDK=$arg
       getJDK=0
    fi
    if [ $getMWHOME = 1 ]; then
       MWH=$arg
       getMWHOME=0
    fi
    if [ $getOUI = 1 ]; then
       OUI_LOCATION=$arg
       FINAL_OUI_LOCATION=$arg
       if [ "$DEBUGVAL" = "true" ]; then
          echo OPatch is provided with 'oui_loc' option as $OUI_LOCATION
       fi
       getOUI=0
    fi

    if [ "$arg" = "-oh" ]; then
       getOH=1;
    fi
    if [ "$arg" = "-jre" ]; then
       getJRE=1;
    fi
    if [ "$arg" = "-jdk" ]; then
       getJDK=1;
    fi
    if [ "$arg" = "-mw_home" ]; then
       getMWHOME=1;
    fi
    if [ "$arg" = "-oui_loc" ]; then
       getOUI=1;
       CMDLINE_OUI=1;
    fi
    if [ `echo "$arg" | tr "[A-Z]" "[a-z]"` = "-invptrloc" ]; then
       getInv=1;
    fi
  done
}

setUpHomeDirs()
{
  # Error out if OH is not set and env var OPATCH_NO_IMPLICIT_OH is set to 'true'
  if [ "$OH" = "" ] && [ "$NO_IMPLICIT_ORACLE_HOME" = "true" ]; then
    echo Oracle Home is not set. OPatch cannot proceed!
    echo "OPatch returns with error code = 1"
    exit 1
  fi

  # Calculate the ORACLE_HOME/MW_HOME relative to this script...
  if [ -z "$OH" ]; then

     # Note: this will not work if the script is sourced (. ./wlst.sh)
     SCRIPTNAME=$0
     case ${SCRIPTNAME} in
     /*)  SCRIPTPATH=`dirname ${SCRIPTNAME}` ;;
      *)  SCRIPTPATH=`dirname ${PWD}/${SCRIPTNAME}` ;;
     esac

     C_ORACLE_HOME=`cd ${SCRIPTPATH}/.. ; pwd`
     C_MW_HOME=`cd ${C_ORACLE_HOME}/.. ; pwd`
     if [ "$DEBUGVAL" = "true" ]; then
        echo ORACLE_HOME is NOT set at OPatch invocation 
     fi
  else  
     # User set Oracle Home, check later if MW home is consistently set too
     if [ ! -d "${OH}" ]; then
        echo The Oracle Home $OH is not valid directory. Please give proper Oracle Home.
        echo "OPatch returns with error code = 1"
        exit 1;
     fi
     if [ ! -z "${FMW_COMPONENT_HOME}" ]; then
        C_ORACLE_HOME=${FMW_COMPONENT_HOME}
     else
        if [ -x "${OH}/common/bin/setHomeDirs.sh" ] && [ -x "${OH}/common/bin/setWlstEnv.sh" ]; then
           C_ORACLE_HOME=${OH}
           FMW_COMPONENT_HOME=${OH}
        else
           TEMP_MW_HOME=`cd ${OH}/.. ; pwd`
           for SUB_DIR in $TEMP_MW_HOME/*
           do
              if [ -x "${SUB_DIR}/common/bin/setHomeDirs.sh" ] && [ -x "${SUB_DIR}/common/bin/setWlstEnv.sh" ]; then
                 FMW_COMPONENT_HOME=$SUB_DIR
                 C_ORACLE_HOME=$SUB_DIR
              fi
           done
           if [ -z "${FMW_COMPONENT_HOME}" ]; then
              if [ "$DEBUGVAL" = "true" ]; then
                 echo OPatch was not able to set FMW_COMPONENT_HOME by itself.
              fi
              C_ORACLE_HOME=${OH}
           fi
        fi

     fi
     # Calculate Middleware Home simply by moving up IFF User set Oracle Home
     C_MW_HOME=`cd ${C_ORACLE_HOME}/.. ; pwd`
  fi

  # Check consistency of Oracle Home and Middleware Home values (within each
  # OPatch cmd only if applicable)
  if [ ! -z "${MWH}" ] ; then
     # The user could have set Middleware Home either with the cmd line option
     # or by setting the environment variable MW_HOME, it is captured in MWH
     # Fixup if they put the PATH separator at the end
     #
     MWH=`echo $MWH | sed -e 's|/$||g'`
  fi
  
  if [ -f "${C_MW_HOME}/registry.dat" -o -f "${C_ORACLE_HOME}/inventory/registry.xml" ]; then
     if [ ! -x "${C_ORACLE_HOME}/common/bin/setHomeDirs.sh" ]; then
        MW_HOME=${C_ORACLE_HOME}
        if [ -x "${MW_HOME}/oracle_common/common/bin/setHomeDirs.sh" ]; then
           MWH=${MW_HOME}
        fi
     fi
     if [ "$MWH" = "" ]; then
        MWH=${C_MW_HOME}
     fi
     if [ "$OH" = "" ]; then
        OH=${C_ORACLE_HOME}
     fi
  else
     # Regular Oracle Home - We allow implicit setting of Oracle Home for OUI based homes
     if [ "$OH" = "" ]; then
        if [ ! -d "${C_ORACLE_HOME}/oui" ]  ; then
           echo The Oracle Home $C_ORACLE_HOME is not OUI based home. Please give proper Oracle Home.
           exit 1;
        fi
        OH=${C_ORACLE_HOME}
     fi
  fi
}

setUpOUILocation()
{
  if [ "$OUI_LOCATION" = "" -o ! -d "${OUI_LOCATION}" ]; then
     OUI_LOCATION=$OH/oui
     FINAL_OUI_LOCATION=$OH/oui
     if [ "$OUI_LOCATION" = "" -o ! -d "${OUI_LOCATION}" ]; then
        SCRIPTNAME=$0
        case ${SCRIPTNAME} in
        /*)  SCRIPTPATH=`dirname ${SCRIPTNAME}` ;;
         *)  SCRIPTPATH=`dirname ${PWD}/${SCRIPTNAME}` ;;
        esac
        if [ -d "${SCRIPTPATH}/../oui" ]; then
           OUI_LOCATION=`cd ${SCRIPTPATH}/../oui ; pwd`
           FINAL_OUI_LOCATION=$OUI_LOCATION
        fi
     fi
  fi
}

setUpInvPtrLoc()
{
   # use oraInst.loc of patching oracle home as INVPTRLOC
   invptr=
   if [ -r "${OH}/oraInst.loc" ]; then
      if [ $argCount -ge 1 -a $getInv -eq 0 ]; then
         invptr=" -invPtrLoc ${OH}/oraInst.loc"
      fi
   fi
}

setUpJava()
{
   # Use JRE if supplied
   if [ "$JRE" != "" ]; then # from -jre
      JAVA=$JRE/bin/java
      JAVA_HOME=$JRE
   fi


   # Use JDK if supplied
   if [ "$JDK" != "" ]; then # now from -jdk
      JAVA=$JDK/bin/java
      JAVA_HOME=$JDK
   fi

   if [ "$JAVA" = "" ]; then
    . "${BASE}/scripts/opatch_jvm_discovery"
   fi 

   # Now check if Java executable exists and has execute permission, exit otherwise
   # Because from this point on we cannot proceed without Java 
   if [ "$JAVA" = "" ]; then
      echo Java could not be located. OPatch cannot proceed!
      echo "OPatch returns with error code = 1"
      exit 1
   fi
   if [ ! -x "$JAVA" ]; then
      echo $JAVA is not a valid executable for this platform. OPatch cannot proceed!
      echo "OPatch returns with error code = 1"
      exit 1
   fi
   # Check whether the $JAVA version is compatible with the java version used in compilation time
   #check_java_version_compatible
   #if [ $? -gt 0 ]; then
   #     echo OPatch ${OPATCH_VERSION} requires jdk$MIN_JAVA_VERSION or later
   #     echo The java version at $JAVA is `$JAVA -version 2>&1 | awk '/version/ {print $3}'` 
   #     exit 1
   #fi
   if  [ "$DEBUGVAL" = "true" ]; then
       _osArch=`$JAVA -cp $BASE/jlib/opatch.jar oracle.opatch.JavaSystemProp os.arch`
       _javaVMSpecVersion=`$JAVA -cp $BASE/jlib/opatch.jar oracle.opatch.JavaSystemProp java.vm.specification.version`
       _javaVMSpecVendor=`$JAVA -cp $BASE/jlib/opatch.jar oracle.opatch.JavaSystemProp java.vm.specification.vendor`
       _javaVMSpecName=`$JAVA -cp $BASE/jlib/opatch.jar oracle.opatch.JavaSystemProp java.vm.specification.name`
       _javaVMVendor=`$JAVA -cp $BASE/jlib/opatch.jar oracle.opatch.JavaSystemProp java.vm.vendor`
       _javaJRESpecVersion=`$JAVA -cp $BASE/jlib/opatch.jar oracle.opatch.JavaSystemProp java.specification.version`
       _javaJRESpecVendor=`$JAVA -cp $BASE/jlib/opatch.jar oracle.opatch.JavaSystemProp java.specification.vendor`
       _javaJRESpecName=`$JAVA -cp $BASE/jlib/opatch.jar oracle.opatch.JavaSystemProp java.specification.name`
       _javaSupportedClassVersion=`$JAVA -cp $BASE/jlib/opatch.jar oracle.opatch.JavaSystemProp java.class.version`
       if [ -x "$JAVA_HOME/bin/javap" ]; then
          _javaCompiledClassMajorVersion=`$JAVA_HOME/bin/javap -verbose -classpath $BASE/jlib/opatch.jar oracle.opatch.JavaSystemProp |grep major|sed 's/^ *\(.*\) *$/\1/'`
          _javaCompiledClassMinorVersion=`$JAVA_HOME/bin/javap -verbose -classpath $BASE/jlib/opatch.jar oracle.opatch.JavaSystemProp|grep minor|sed 's/^ *\(.*\) *$/\1/'`
       fi
       _unameall=`uname -a`
       echo "Machine Info: $_unameall"
       echo "_osArch is $_osArch"
       echo "_javaVMSpecVersion is $_javaVMSpecVersion"
       echo "_javaVMSpecVendor is $_javaVMSpecVendor"
       echo "_javaVMSpecName is $_javaVMSpecName"
       echo "_javaVMVendor is $_javaVMVendor"
       echo "_javaJRESpecVersion is $_javaJRESpecVersion"
       echo "_javaJRESpecVendor is $_javaJRESpecVendor"
       echo "_javaJRESpecName is $_javaJRESpecName"
       echo "_javaSupportedClassVersion is $_javaSupportedClassVersion"
       echo "OPatch compiled with $_javaCompiledClassMajorVersion, $_javaCompiledClassMinorVersion"
   fi
}

setUpJREMemoryOPtions()
{
   # JRE_MEMORY_OPTIONS 
   if [ -z "${JRE_MEMORY_OPTIONS}" ]; then
      JRE_MEMORY_OPTIONS=""
      if [ -r $FINAL_OUI_LOCATION/oraparam.ini ]; then
         JRE_MEMORY_OPTIONS=`grep -v "^#" $FINAL_OUI_LOCATION/oraparam.ini | grep "^JRE_MEMORY_OPTIONS=" | sed 's/JRE_MEMORY_OPTIONS=//' | head -1`
         if [ -z "`echo $JRE_MEMORY_OPTIONS | grep "\-X\?mx[0-9]\+m"`" ]; then
            JRE_MEMORY_OPTIONS=" -Xmx768m $JRE_MEMORY_OPTIONS"
         else
            JRE_MEMORY_OPTIONS=`echo $JRE_MEMORY_OPTIONS | sed 's/\-X\?mx[0-9]\+m/-Xmx768m/'`
         fi
         JROCKIT=`echo $JDK | grep "jrockit"`;
         if [ ! -z "${JROCKIT}" ]; then
            JRE_MEMORY_OPTIONS=`echo $JRE_MEMORY_OPTIONS | sed 's/XX:MaxPermSize=/ms/'`;
         fi
      fi
   else
      if [ -z "`echo $JRE_MEMORY_OPTIONS | grep "\-X\?mx[0-9]\+m"`" ]; then
         JRE_MEMORY_OPTIONS=" -Xmx768m $JRE_MEMORY_OPTIONS"
      fi
      D64_OPTIONS=`echo $JRE_MEMORY_OPTIONS | grep "\-d64"`
      if [ -z "${D64_OPTIONS}" ]; then
         if [ -r $FINAL_OUI_LOCATION/oraparam.ini ]; then
            D64_OPTIONS=`grep -v "^#" $FINAL_OUI_LOCATION/oraparam.ini | grep "^JRE_MEMORY_OPTIONS=" | sed 's/JRE_MEMORY_OPTIONS=//' | head -1 | grep " \-d64"`
         fi
         if [ ! -z "${D64_OPTIONS}" ]; then
            D64=" -d64"
            JRE_MEMORY_OPTIONS=$JRE_MEMORY_OPTIONS$D64
         fi
      fi
   fi
   # Remove double quotes globally - whatever u get
   JRE_MEMORY_OPTIONS=`echo $JRE_MEMORY_OPTIONS | sed 's/\"//g'`
}

setUpPatchStorage()
{
   # Change the permission of OH/.patch_storage directory and set umask.
   # umask 0007 
   # Do not set umask.
   patchStorage="$OH/.patch_storage"
   chmodResult=0
   if [ -d $patchStorage ]; then
      chmod o-rwx $patchStorage  > /dev/null
      chmodResult=$?
   fi

   if [ $chmodResult != 0 ]; then
      echo "The chmod command failed for ".$patchStorage.". It is possible that you have no permission to access it. OPatch cannot proceed!"
      echo "OPatch returns with error code = 1"
      exit 1
   fi
}

setUpLibraryPath()
{
    IS_NEXT_GEN=false
   if [ "$OUI_LOCATION" != "" ] ; then
      #for NextGen OUI home, we use 'modules' directory as opposed to 'jlib' directory
      CP=$OUI_LOCATION
      if [ -d "$OUI_LOCATION/modules" ] ; then
         IS_NEXT_GEN=true
      fi
   else
      CP=$OH/oui
      if [ -d "$OH/oui/modules" ] ; then
         IS_NEXT_GEN=true
      fi
   fi

   if [ "$IS_NEXT_GEN" = "true" ] ; then
      CP="$CP/modules"
      # for NextGen OUI, classpath attribute of OraInstaller.jar manifest contains all related jar files
      OUI_JARS="$CP/OraInstaller.jar"

   else
      CP="$CP/jlib"
      OUI_JARS="$CP/OraInstaller.jar:$CP/OraInstallerNet.jar:$CP/OraPrereq.jar:$CP/share.jar:$CP/orai18n-mapping.jar:$CP/xmlparserv2.jar:$CP/emCfg.jar:$CP/ojmisc.jar"
   fi

   # Below setting copied from oplan
   PLATFORM=`uname`

   case $PLATFORM in
      HP-UX)
         LD_LIBRARY_PATH=$OH/lib:$OH/srvm/lib
         export LD_LIBRARY_PATH
         SHLIB_PATH=
         export SHLIB_PATH
         ;;
      AIX)
         LIBPATH=$OH/lib:$OH/srvm/lib:$LIBPATH
         export LIBPATH
         ;;
      Linux)
         LD_LIBRARY_PATH=$OH/lib:$OH/srvm/lib:$LD_LIBRARY_PATH
         # Linux ( ppc64 || s390x ) => LD_LIBRARY_PATH lib32
         ARCH=`uname -m`;
         if [ "$ARCH" = "ppc64" -o "$ARCH" = "s390x" ]
         then
            LD_LIBRARY_PATH=$OH/lib32:$OH/srvm/lib32:$LD_LIBRARY_PATH
         fi
         export LD_LIBRARY_PATH
         ;;
      SunOS)
         LD_LIBRARY_PATH_64=$OH/lib:$OH/srvm/lib:$LD_LIBRARY_PATH_64
         export LD_LIBRARY_PATH_64
         LD_LIBRARY_PATH=$OH/lib:$OH/srvm/lib:$LD_LIBRARY_PATH
         export LD_LIBRARY_PATH
         ;;
      OSF1) LD_LIBRARY_PATH=$OH/lib:$OH/srvm/lib:$LD_LIBRARY_PATH
         export LD_LIBRARY_PATH
         ;;
      Darwin)
         DYLD_LIBRARY_PATH=$OH/lib:$OH/srvm/lib:$DYLD_LIBRARY_PATH
         export DYLD_LIBRARY_PATH
         ;;
      *)    
         if [ -d $OH/lib32 ];
         then
            LD_LIBRARY_PATH=$OH/lib32:$OH/srvm/lib32:$LD_LIBRARY_PATH
         else
            LD_LIBRARY_PATH=$OH/lib:$OH/srvm/lib:$LD_LIBRARY_PATH
         fi
         export LD_LIBRARY_PATH
         ;;
   esac
}

setUpClassPath()
{
   # set _bootClassPath for IBM platforms (bug 7038091 and 7114214)
   _osArch=""
   if [ -r $BASE/ocm/lib/emocmcommon.jar ] && [ -r $BASE/ocm/ocm.zip ]; then
      _osArch=`$JAVA -cp $BASE/ocm/lib/emocmcommon.jar OsInfo`
   fi
   _bootClassPath=""

   if  [ "$DEBUGVAL" = "true" ]; then
       echo "_osArch (from OCM API) is $_osArch"
   fi
   if [ "${_osArch}" = "ppc" -o "${_osArch}" = "ppc64" -o "${_osArch}" = "s390"  -o "${_osArch}" = "s390x" ]; then
      _bootClassPath="-Xbootclasspath/a:${BASE}/ocm/lib/emocmclnt.jar:${BASE}/ocm/lib/emocmcommon.jar:${BASE}/ocm/lib/emocmclnt-14.jar:${BASE}/ocm/lib/osdt_core3.jar:${BASE}/ocm/lib/osdt_jce.jar:${BASE}/ocm/lib/http_client.jar:${BASE}/ocm/lib/regexp.jar:${BASE}/ocm/lib/jcert.jar:${BASE}/ocm/lib/jnet.jar:${BASE}/ocm/lib/jsse.jar:${BASE}/ocm/lib/log4j-core.jar:${BASE}/ocm/lib/xmlparserv2.jar"
      if  [ "$DEBUGVAL" = "true" ]; then
        echo "IBM platforms: set _bootClassPath to $_bootClassPath"
      fi
   fi

   #set opatch class path
   opatchClassPath="$BASE/ocm/lib/emocmclnt.jar:$OUI_JARS:$BASE/jlib/opatch.jar:$BASE/jlib/opatchsdk.jar:$BASE/oplan/jlib/automation.jar:$BASE/oplan/jlib/apache-commons/commons-cli-1.0.jar:$BASE/jlib/oracle.opatch.classpath.jar:$BASE/oplan/jlib/jaxb/activation.jar:$BASE/oplan/jlib/jaxb/jaxb-api.jar:$BASE/oplan/jlib/jaxb/jaxb-impl.jar:$BASE/oplan/jlib/jaxb/jsr173_1.0_api.jar:$BASE/oplan/jlib/OsysModel.jar:$BASE/oplan/jlib/osysmodel-utils.jar:$BASE/oplan/jlib/CRSProductDriver.jar:$BASE/oplan/jlib/oracle.oplan.classpath.jar"

}

setUpOPatchOPtions()
{
   if [ ! "$WL_HOME" = "" ]; then
      if [ -f "${WL_HOME}/server/lib/fusion_trust.jks" ]; then
         FUSION_TRUST_OPTION="-Dweblogic.security.SSL.trustedCAKeyStore=$WL_HOME/server/lib/fusion_trust.jks"
      fi
   fi
}

callOPatch()
{

   if [ $CMDLINE_OUI = 0 ]; then
      OUI_LOCATION=
   fi

   if [ "$DEBUGVAL" = "true" ]; then
      echo "$JAVA $JAVA_VM_OPTION $JRE_MEMORY_OPTIONS -cp $opatchClassPath -DOPatch.ORACLE_HOME=$OH -DOPatch.DEBUG=$DEBUGVAL -DOPatch.MAKE=$MAKEVAL -DOPatch.RUNNING_DIR=$BASE -DOPatch.MW_HOME=$MWH -DOPatch.WL_HOME=$WL_HOME -DOPatch.COMMON_COMPONENTS_HOME=$COMMON_COMPONENTS_HOME -DOPatch.OUI_LOCATION=$OUI_LOCATION -DOPatch.FMW_COMPONENT_HOME=$FMW_COMPONENT_HOME -DOPatch.OPATCH_CLASSPATH=$CLASSPATH -DOPatch.WEBLOGIC_CLASSPATH=$WEBLOGIC_CLASSPATH $FUSION_TRUST_OPTION ${oracleOcmService} ${_bootClassPath} oracle/opatch/OPatch $args $invptr"
   fi


   $JAVA $JAVA_VM_OPTION $JRE_MEMORY_OPTIONS -cp $opatchClassPath  -DOPatch.ORACLE_HOME="$OH" -DOPatch.DEBUG="$DEBUGVAL" -DOPatch.MAKE="$MAKEVAL" -DOPatch.RUNNING_DIR="$BASE" -DOPatch.MW_HOME="$MWH" -DOPatch.WL_HOME="$WL_HOME" -DOPatch.COMMON_COMPONENTS_HOME="$COMMON_COMPONENTS_HOME" -DOPatch.OUI_LOCATION="$OUI_LOCATION" -DOPatch.FMW_COMPONENT_HOME="$FMW_COMPONENT_HOME" -DOPatch.OPATCH_CLASSPATH="$CLASSPATH" -DOPatch.WEBLOGIC_CLASSPATH="$WEBLOGIC_CLASSPATH"  $FUSION_TRUST_OPTION ${oracleOcmService} ${_bootClassPath} oracle/opatch/OPatch $args $invptr

   RESULT=$?

   if [ $argCount -ge 1 ] && [ "$1" = "lspatches" ]; then
      exit ${RESULT}
   fi

   if [ $RESULT -ge  5 ] && [ $RESULT -le 7 ]; then
      echo
      echo "OPatch stopped on request."
      RESULT=0
   elif [ $RESULT -eq 8 ] ;then
      echo
      echo "OPatch completed with warnings.";
      RESULT=0
   elif [ $RESULT != 0 ]; then
      echo
      echo "OPatch failed with error code $RESULT";
   else
      echo 
      echo "OPatch succeeded."
   fi

   exit ${RESULT}

}

#OPatch Script Main Entry
main()
{
  init $@

  opatchAutoDetect $args

  parseCommandLineOPtions $args

  setUpHomeDirs $0

  setUpOUILocation

  setUpInvPtrLoc

  setUpJava

  setUpJREMemoryOPtions

  setUpLibraryPath

  setUpClassPath

  setUpOPatchOPtions

  callOPatch
}

main $@
