#!/bin/sh
# $Header: emll/bin/deriveCCR /main/19 2012/12/10 11:50:39 fmorshed Exp $
#
# deriveCCR
#
# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. 
#
#    NAME
#      deriveCCR
#
#    DESCRIPTION
#      This script is invoked by the user to do an in place derivation for
#      purposes of cloning.  After derivation, there may be subsequent steps
#      such as db instrumentation to complete the cloning
#
#    EXIT CODES
#      0 - Success
#      1 - Prerequisite failure
#      2 - Invalid argument specified
#      3 - Invalid Usage
#      11 - Unexpected Installation failure
#      12 - License Agreement declined
#
#    NOTES / Conventions
#      Global variables which are used across functions within the module
#      should either be prededed by a 'G_' or be entirely in UPPER case.
#      Variables local to a function should be prefixed with strictly a '_'.
#
#--

# source common stuff
_OCMBinDir=`/usr/bin/dirname $0`
. ${_OCMBinDir}/common

_TEMP_RESPONSE_FILE="./tempocm.rsp"

usage()
{
   $CAT <<EOF
Usage: $0 [ -d | -C <OracleSupportHubUrl> ] [<csi-number> [<MyOracleSupportId>]]
       $0 [ -R <response-file> ]

   where:

      <csi-number>        Oracle Customer Support Identifier (CSI)
      <MyOracleSupportId> My Oracle Support user name registered for the CSI
      <response-file>     Response file generated by emocmrsp

      -d                  Indicates that the installation will be done in the
                          disconnected mode. All other qualifiers and arguments
                          are ignored.

      -R                  Configures OCM using a specified response file.

      -C                  url for Oracle Support Hub used to connect to
                          Oracle. If NONE is specified, no Oracle Support
                          Hub is to be used to communicate with Oracle
                          
      When no parameters are provided then the configuration information is gleaned
      from the OCM installation and used to re-configure the derived home if its 
      connectivity can be verified.
      
      To successfuly run a collection OCM must be in sync with its environment.  See 
      the OCM installation and administration guide for the list of environment 
      variables that are needed for each type of installation.  These variables are 
      captured when you setup OCM.  deriveCCR will issue a warning for each variable 
      that is not set but was set in the original home.
EOF
}

determineSharedHomesSupported
setOCMDirPaths

if [ $# -ne 0 ]; then
    while getopts ":C:R:hd" _option
    do
        if [ $? -eq 0 ]
        then
            case ${_option}
            in
                h)  usage
                    exit $SUCCESS;;            
                d)
                    ;;
                R)
                    ;;
                C)
                    ;;
                :) 
                    $ECHO "Required value for option \"-${OPTARG}\" is missing."
                    $ECHO ""
                    usage
                    exit $ERR_INVALID_USAGE;;
    
                *)
                    $ECHO "Invalid command qualifier specified \"-${OPTARG}\""
                    $ECHO ""
                    usage
                    exit $ERR_INVALID_USAGE;;
            esac
        fi
    done
fi

determineOCMHome

# OCM is expanded into a home, so the the parent of the install *IS* the Oracle home
ORACLE_HOME=`$DIRNAME ${OCM_HOME}`
export ORACLE_HOME

# If ORACLE_CONFIG_HOME is defined, use it.
_OCH=""
if [ ! -z "${ORACLE_CONFIG_HOME}" ]; then
    _OCH="-DORACLE_CONFIG_HOME=${ORACLE_CONFIG_HOME}"
fi

# Warn user if original snapshot environment variables are not currently defined

INTERESTING_VARS="CRS_HOME|CLUSTER_NAME|LD_PRELOAD|JAVA_HOME|TNS_ADMIN|ORAINST_LOC|EMTAB|EMAGENT_PERL_TRACE_LEVEL|TZ|ORACLE_HOME|ORACLE_CONFIG_HOME|ORACLE_OCM_SERVICE|IAS_CONFIG_HOME|WL_HOME|BEA_HOME|ORACLE_INSTANCE|ORACLE_CCR_TESTS"
VARS_THAT_ARE_SET=`env | $EGREP -e "^($INTERESTING_VARS)=" | $CUT -f1 -d'='`
VARS_THAT_WERE_SNAPSHOT=""
if [ -f ${CCR_CONFIG_HOME}/config/emCCRenv ]; then
    VARS_THAT_WERE_SNAPSHOT=`$EGREP -e "=" ${CCR_CONFIG_HOME}/config/emCCRenv | $CUT -f1 -d'='` 
fi
for s1 in $VARS_THAT_WERE_SNAPSHOT
do 
   _snapshot_var_val=`$EGREP -e "${s1}=" ${CCR_CONFIG_HOME}/config/emCCRenv | $CUT -f2 -d'='` 
   # If the value of a snapshot variable is nothing then treat it as not defined!
   # Catches the "setenv x" cases in the original home
   if [ -z "${_snapshot_var_val}" ]; then 
       continue
   fi           
    _FOUND=$FALSE
    for s2 in $VARS_THAT_ARE_SET
    do
       if [ "${s1}" = "${s2}" ]; then
       	   # Only if the set env variable has a value we consider it set!
           # Catches the "setenv x" cases in the current environment (cloned home).
           _set_var_val=`env | $EGREP -e "${s2}=" | $CUT -f2 -d'='`
       	   if [ ! -z "${_set_var_val}" ]; then 
               _FOUND=$TRUE
               break
       	   fi
       fi
    done
    if [ $_FOUND -eq $FALSE ]; then
        $ECHO "WARNING:  $s1 is currently not defined but it was originally defined for this OCM installation."
    fi
done

# Determine whether we should check for a running collector or able to glean configuration
# information.  If the config directory is not present then we cannot do either.
_config_home_is_present=$FALSE
if [ -d ${CCR_CONFIG_HOME}/config ]; then
	_config_home_is_present=$TRUE
else
    $ECHO "OCM configuration home is not setup."     
fi

# if the JAVA_HOME can be determined from the cloned environment then use it.  Otherwise, try to use 
# the JAVA_HOME from the original home.
set +e
determineJavaHome $FALSE
if [ $? -ne $SUCCESS ]; then
    if [ "${_config_home_is_present}" -eq $TRUE ]; then
        JAVA_HOME_CCR_THAT_WAS_SNAPSHOT=`$EGREP -e "^JAVA_HOME_CCR=" ${CCR_CONFIG_HOME}/config/emCCRenv | $CUT -d'=' -f2` 
        if [ ! -z "$JAVA_HOME_CCR_THAT_WAS_SNAPSHOT" ]; then
            JAVA_HOME_CCR="$JAVA_HOME_CCR_THAT_WAS_SNAPSHOT"
            $ECHO "Setting JAVA_HOME_CCR to the snapshot saved in original home: " ${JAVA_HOME_CCR}
            export JAVA_HOME_CCR
        fi
  	    JAVA_HOME_THAT_WAS_SNAPSHOT=`$EGREP -e "^JAVA_HOME=" ${CCR_CONFIG_HOME}/config/emCCRenv | $CUT -d'=' -f2`
        if [ ! -z "$JAVA_HOME_THAT_WAS_SNAPSHOT" ]; then
            JAVA_HOME="$JAVA_HOME_THAT_WAS_SNAPSHOT"
            $ECHO "Setting JAVA_HOME to the snapshot saved in original home: " ${JAVA_HOME}
            export JAVA_HOME
        fi
    fi
    determineJavaHome $TRUE
    if [ $? -ne $SUCCESS ]; then
        exit $?    
    fi
fi
set -e

determineOCMHome

# If not setup at all, just relegate to setupCCR
if [ ! -f ${CCR_HOME}/bin/emCCR ]; then
    $ECHO "OCM is not configured... invoking setupCCR."
    ${OCM_HOME}/bin/setupCCR $@    
    exit $?     
fi

determineOcmEndPoint
determineOcmLog
determineJavaVersion
determineHttpClientClasspath
determineBootClassPath

if [ "${_config_home_is_present}" -eq $TRUE ]; then
    # Now that we have exported the environment variables that we need, snapshot it and 
    # whatever else the user has set.  We have to do this before invoking anything else
    # in the bin directory because they may instantiate the saved environment!
	$ECHO "Snapshot the environmental variables."
    ${VERBOSE} ${CCR_BIN}/emSnapshotEnv
	
	$ECHO "Ensure OCM collector is not already running by executing emCCR status."
	set +e
    ${CCR_HOME}/bin/emCCR status > /dev/null 2>&1
	if [ $? -eq 0 -o $? -eq 55 ]; then
	    $ECHO "Error: Cannot derive an OCM collector that is already running."
	    exit $ERR_PREREQ_FAILURE
	else
	    $ECHO "OCM collector is not running... continue to derive the OCM collector installation."
	fi
	set -e
fi

# Create a temporary response file if no parameters are provided and indeed there is a config directory
_GLEANED_TEMP_RESPONSE_FILE_IS_AVAILABLE=$FALSE
if [ $# -eq 0 -a "${_config_home_is_present}" -eq $TRUE ]; then
    $ECHO "Gleaning OCM collector installation to create a temporary response file."     
    
    set +e   

# Note:  Cannot use the "-jar" because it would ignore -classpath.
    $JAVA_HOME/bin/java \
       ${G_bootClassPath} \
       ${G_ocmEndpoint} \
       ${G_ocmLog} \
       ${G_oracleCCRTests} \
       ${OCM_TEST_CLASSPATH} \
       -classpath $G_HTTP_CLIENT_CLASSPATH:${OCM_HOME}/lib/emocmclnt.jar \
       -DOCM_ROOT=${OCM_HOME} \
       -DORACLE_HOME=$ORACLE_HOME \
       -DCCR_CONFIG_HOME=${CCR_CONFIG_HOME} \
       ${_OCH} \
       oracle.sysman.ccr.collector.install.ConfigResponse -no_banner -import ${_TEMP_RESPONSE_FILE}
       
    if [ $? -ne $SUCCESS ]; then
        $ECHO "Gleaning this installation failed."
        exit $ERR_PREREQ_FAILURE
    fi
    
    # verify the response file.  If "invalid" then don't use it 
    $ECHO "Verifying the gleaned response file."
    ${OCM_HOME}/bin/emocmrsp -no_banner -verify ${_TEMP_RESPONSE_FILE}
    if [ $? -eq $SUCCESS ]; then
        _GLEANED_TEMP_RESPONSE_FILE_IS_AVAILABLE=$TRUE
        $ECHO "Derived OCM collector will be configured using the gleaned response file."
    else
        $ECHO "Gleaned response file cannot be verified.  You will be prompted for required input."     
    fi

    set -e
fi

# Remove all the configuration data as they are now obsolete
$RMRF  ${CCR_CONFIG_HOME}/config/ccr.properties
$RMRF  ${CCR_CONFIG_HOME}/config/collector.properties
$RMRF  ${CCR_CONFIG_HOME}/state
$RMRF  ${CCR_CONFIG_HOME}/log

# mv core.jar and engines.jar to "pending" to cause configCCR to re-deploy, and re-link any binaries
$MV ${OCM_HOME}/inventory/core.jar ${OCM_HOME}/inventory/pending/core.jar
$MV ${OCM_HOME}/inventory/engines.jar ${OCM_HOME}/inventory/pending/engines.jar

# Invoke configCCR
_CONFIG_STATUS=$SUCCESS
DERIVECCR_IN_PROGRESS=$TRUE
export DERIVECCR_IN_PROGRESS
if [ "${_GLEANED_TEMP_RESPONSE_FILE_IS_AVAILABLE}" -eq $TRUE ]; then
    $ECHO "Invoking configCCR to re-configure using the gleaned response file."     
    ${CCR_HOME}/bin/configCCR -a -R ${_TEMP_RESPONSE_FILE}
    _CONFIG_STATUS=$?
    $RMF ${_TEMP_RESPONSE_FILE}
else
    $ECHO "Invoking configCCR to re-configure."     
    ${CCR_HOME}/bin/configCCR -a $@
    _CONFIG_STATUS=$?
fi

# finally, mark this installation as derived

if [ $_CONFIG_STATUS -eq $SUCCESS ]; then
    $JAVA_HOME/bin/java \
       ${G_bootClassPath} \
       ${G_ocmEndpoint} \
       ${G_ocmLog} \
       ${G_oracleCCRTests} \
       ${OCM_TEST_CLASSPATH} \
       -classpath $G_HTTP_CLIENT_CLASSPATH:${OCM_HOME}/lib/emocmclnt.jar \
       -DOCM_ROOT=${OCM_HOME} \
       -DORACLE_HOME=$ORACLE_HOME \
       -DCCR_CONFIG_HOME=${CCR_CONFIG_HOME} \
       ${_OCH} \
       oracle.sysman.ccr.collector.install.ConfigResponse -no_banner -derived
fi

exit $_CONFIG_STATUS
