#!/bin/sh
# $Header: emll/bin/setupCCR /st_emll_10.3.4/2 2010/07/29 07:32:47 jsutton Exp $
#
# {setup|config}CCR
#
# Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. 
#
#    NAME
#      {setup|config}CCR - OCM software configuration
#
#    DESCRIPTION
#      This script is invoked by the user to install the software
#      which is the OCM collector. It also configures it for a 
#      collection.
#
#      The script is retained as configCCR for reconfiguration post
#      installation.
#
#    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 '_'.
#--

# Note that the TTY terminal settings will be used 
#
#++
#
# This is strictly a wrapper around package deployment. This will be obsoleted
# once full auto-updating capabilities are built into the system
#
#--
# set restrictive file creation mask
umask 077

# 
# Reset the locale to ENGLISH for command line operations.
LC_ALL=C
export LC_ALL

# Constant declarations for exit values.
SUCCESS=0
ERR_PREREQ_FAILURE=1
ERR_INVALID_ARG=2
ERR_INVALID_USAGE=3
ERR_LOCK_FAILURE=4
ERR_UNEXPECTED_FAILURE=11
ERR_LICENSE_DECLINED=12

#
# Fail on command error
#
set -e

# Define the paths for /usr/bin. These are used in subsequent path
# specifications for native commands.
_binDir=/bin
_usrBinDir=/usr/bin
_usrLocalBinDir=/usr/local/bin

# Set the variables that map to explicit paths to prevent from trojan
# horse type attacks and allow for more consistent installation experience
# by eliminating the use of aliases.
BC=${_usrBinDir}/bc
BINMORE=${_binDir}/more
CAT=${_binDir}/cat
CHMOD=${_binDir}/chmod
CP=${_binDir}/cp
CRONTAB=${_usrBinDir}/crontab
DATE=${_binDir}/date
DIFF=${_usrBinDir}/diff
DIRNAME=${_usrBinDir}/dirname
ECHO=${_binDir}/echo
FIND=${_usrBinDir}/find
ID=${_usrBinDir}/id
LS=${_binDir}/ls
MKDIR=${_binDir}/mkdir
MKDIRP="${_binDir}/mkdir -p"
MV=${_binDir}/mv
RM=${_binDir}/rm
RMF="$RM -f"
RMRF="$RM -rf"
SED=${_binDir}/sed
STTY=${_binDir}/stty
TOUCH=${_binDir}/touch
TTY=${_usrBinDir}/tty
TR=${_usrBinDir}/tr

if [ -f ${_binDir}/cut ]
then
    CUT=${_binDir}/cut
elif [ -f ${_usrBinDir}/cut ]
then
    CUT=${_usrBinDir}/cut
fi

if [ -f ${_binDir}/uname ]
then
    UNAME=${_binDir}/uname
elif [ -f ${_usrBinDir}/uname ]
then
    UNAME=${_usrBinDir}/uname
fi

AWK=${_binDir}/awk
PLATFORM=`$UNAME | $CUT -f1`
if [ "$PLATFORM" = "SunOS" ]
then
    if [ -f ${_binDir}/nawk ]
    then
        AWK=${_binDir}/nawk
    elif [ -f ${_usrBinDir}/nawk ]
    then
        AWK=${_usrBinDir}/nawk
    fi
fi

if [ -f ${_binDir}/egrep ]
then
    EGREP=${_binDir}/egrep
elif [ -f ${_usrBinDir}/egrep ]
then
    EGREP=${_usrBinDir}/egrep
fi

LOCKFILE=""
if [ -f ${_usrBinDir}/lockfile ]
then
    LOCKFILE=${_usrBinDir}/lockfile
elif [ -f ${_usrLocalBinDir}/lockfile ]
then
    LOCKFILE=${_usrLocalBinDir}/lockfile
fi

if [ -f ${_usrBinDir}/printf ]
then
    PRINTF=${_usrBinDir}/printf
elif [ -f ${_binDir}/printf ]
then
    PRINTF=${_binDir}/printf
fi

if [ -z "${CCR_INSTALL_DEBUG}" ]
then
    VERBOSE=
else
    VERBOSE="${_binDir}/sh -x"
fi

# Bug 5931631 - getopts issue with /bin/sh on SunOS
# If SunOS, run this script with /usr/xpg4/bin/sh (if available)
if [ $PLATFORM = "SunOS" ]
then
    if [ -f /usr/xpg4/bin/sh ]
    then
        if [ -z "${_xpg4ShAvbl_setupCCR}" ]
        then
            _xpg4ShAvbl_setupCCR=1
            export _xpg4ShAvbl_setupCCR
            /usr/xpg4/bin/sh $0 "$@"
            exit $?
        fi
    fi
fi

if [ $PLATFORM = "OSF1" ]
then
    if [ -z "${BIN_SH}" ]
    then
        BIN_SH=xpg4
        export BIN_SH
        $0 "$@"
        exit $?
    fi
fi

# Determine if this is a console device.
set +e
IS_CONSOLE=0
${TTY} -s
if [ $? -eq 0 ]; then
    IS_CONSOLE=1
fi
set -e

# Define of global static variable
TRUE=1
FALSE=0

# G_ConfigurationRequest is used to indicate whether a configuration, or removal 
# of configuration is requested. Valid values are "", "config" or "deconfig".
G_ConfigurationRequest=""

# G_configurationCompleted is used to denote that a configuration request was 
# explicitly requested or implicitly made thru a new installation and the 
# setup of writeable trees was completed. Values are 0 for false and 1 for true.
G_ConfigurationCompleted=$FALSE

# G_OCMConfigured indicates that the OCM Home/OCM Configuration Home contains 
# configuration information. The valid values are 'undefined' prior to calls
# to isOCMConfigured, and $TRUE or $FALSE otherwise
G_OCMConfigured="undefined"

# Indicates that this is a new install
G_NewInstall=$FALSE

# G_ORACLE_CONFIG_HOME_VAR defines a string that is used on CRON operations.
# Default value is "". Changes for a pattern match whether the installation
# supports a shared home config and ORACLE_CONFIG_HOME is set in the env.
G_ORACLE_CONFIG_HOME_VAR=""

# G_INIT_DISCONN_STATE defines a string that identifies the initial disconnect
# state of the collector when a configuration or reconfiguration is being
# performed
G_INIT_DISCONN_STATE="false"

#G_ADD_CRON is set by configInstance() for storing information that, is crontab 
#should b added or not. If yes it will be set to ture.
G_ADD_CRON="false"

ROOTCHAR=`$DIRNAME $0 | $CUT -b1`
if [ "${ROOTCHAR}" != "/" -a -z "${PWD}" ]
then
    $ECHO "The current shell is not supported for executing commands using relative paths."
    $ECHO "Either execute the command under the bash or ksh shells, or execute the "
    $ECHO "command using the absolute path."
    exit 1
fi

# operation collision semaphore
semTakenOp=0
semTakenUpd=0

#++
# 
# Extracts the Value for the property specified from the base configuration
# file. Value returned in the variable _returnData
# 
# The algorithm iterates thru all the files in precidence order, taking the
# first one present. Order is:
#     
#   (1) $CCR_CONFIG_HOME/config
#   (2) $CCR_CONFIG_HOME/config/default
#   (3) $CCR_HOME/config
#   (4) $CCR_HOME/config/default
#
# Args:
#    property-name, i.e. ccr.disconnected
#    config-basename, i.e. ccr.properties or collector.properties
#
#--
getProperty()
{
   _propertyName=$1
   _propertyFile=$2
   _returnData=""
      
   if [ -z "${_propertyFile}" -o -z "${_propertyName}" ]; then
       $ECHO "INTERNAL ERR (getProperty()) - Missing arguments"
       exit $ERR_UNEXPECTED_FAILURE
   fi
   
   if [ -f ${CCR_CONFIG_HOME}/config/${_propertyFile} ]; then
       _returnData=`$EGREP "^$_propertyName=" ${CCR_CONFIG_HOME}/config/${_propertyFile} | \
                          $SED -e "s/$_propertyName=\s*//"`
   fi
   
   # check alternate properties files if we come up empty, just in case
   if [ -z "${_returnData}" ] ; then
      if [ -f ${CCR_CONFIG_HOME}/config/default/${_propertyFile} ] ; then
         _returnData=`$EGREP "^$_propertyName=" ${CCR_CONFIG_HOME}/config/default/${_propertyFile} | \
                      $SED -e "s/$_propertyName=\s*//"`
      fi
   fi
   if [ -z "${_returnData}" ] ; then
      if [ -f ${CCR_HOME}/config/${_propertyFile} ] ; then
         _returnData=`$EGREP "^$_propertyName=" ${CCR_HOME}/config/${_propertyFile} | \
                      $SED -e "s/$_propertyName=\s*//"`
      fi
   fi
   if [ -z "${_returnData}" ] ; then
      if [ -f ${CCR_HOME}/config/default/${_propertyFile} ] ; then
         _returnData=`$EGREP "^$_propertyName=" ${CCR_HOME}/config/default/${_propertyFile} | \
                      $SED -e "s/$_propertyName=\s*//"`
      fi
   fi
}

# Backup file specified from srcdir to destdir
# destdir is an optional directory specification
backupFile()
{
   _srcdir=$1
   _file=$2
   _destdir=$3
   if [ -z "${_destdir}" ]; then
       _destdir=${_srcdir}
   fi

   if [ -f $CCR_HOME/${_srcdir}/${_file} ]; then
       $CP -f $CCR_HOME/${_srcdir}/${_file} $CCR_HOME/${_destdir}/${_file}.save
   fi
}

# Backup key setup Files
backupSetupFiles()
{
   # Save the setupCCR (it does, as this is the script)
   $CP -f $CCR_HOME/bin/setupCCR $CCR_HOME/bin/setupCCR.save

   # Save the deployPackages if it exists.
   backupFile bin deployPackages

   # Save OsInfo.class if it exists.
   backupFile lib OsInfo.class bin

   # Save the license agreement
   backupFile doc jsse_license.html

   # Save the ocmResponse generator jar and associated required pieces
   backupFile lib emocmclnt.jar bin
   backupFile lib emocmclnt-14.jar bin
   backupFile lib emocmcommon.jar bin
   backupFile lib osdt_core3.jar bin
   backupFile lib osdt_jce.jar bin
   backupFile lib http_client.jar bin
   backupFile lib jcert.jar bin
   backupFile lib jnet.jar bin
   backupFile lib jsse.jar bin
   backupFile lib log4j-core.jar bin
   backupFile lib regexp.jar bin
   backupFile lib xmlparserv2.jar bin

   # Save the ocmResponse generator
   backupFile bin emocmrsp

   # Save the lockfile script
   backupFile bin lockfile
}

# Read no echo
#
# Return string/value is returned in variable '_PROMPT_RESULT'
readNoEcho()
{
   if [ ${IS_CONSOLE} -eq 1 ]; then
       OLD_STTY=`${STTY} -g`
       ${STTY} -echo
   fi

   read _PROMPT_RESULT

   if [ ${IS_CONSOLE} -eq 1 ]; then
       ${STTY} ${OLD_STTY}
   fi
}

# Restore jar files backedup to bin back to lib
restoreFile()
{
   _srcdir=$1
   _file=$2
   _destdir=$3

   if [ -z "${_destdir}" ]; then
       _destdir=${_srcdir}
   fi

   if [ -f $CCR_HOME/${_srcdir}/${_file}.save ]
   then
      if [ ! -d ${CCR_HOME}/${_destdir} ]
      then
         $MKDIRP ${CCR_HOME}/${_destdir}
         $CHMOD 740 ${CCR_HOME}/${_destdir}
      fi
      $MV -f $CCR_HOME/${_srcdir}/${_file}.save $CCR_HOME/${_destdir}/${_file}
   fi
}

# Restore key setup Files
restoreSetupFiles()
{
   # Restore the setupCCR backup
   $MV -f $CCR_HOME/bin/setupCCR.save $CCR_HOME/bin/setupCCR

   # Restore the saved emocmrsp.save to emocmrsp
   restoreFile bin emocmrsp

   # Restore the saved deployPackages.save to deployPackages
   restoreFile bin deployPackages

   # Restore the saved OsInfo.class.save to OsInfo.class
   restoreFile bin OsInfo.class  lib

   # restore the jars necessary for the response generator
   restoreFile bin emocmclnt.jar     lib
   restoreFile bin emocmclnt-14.jar  lib
   restoreFile bin emocmcommon.jar   lib
   restoreFile bin osdt_core3.jar    lib
   restoreFile bin osdt_jce.jar      lib
   restoreFile bin http_client.jar   lib
   restoreFile bin jcert.jar         lib
   restoreFile bin jnet.jar          lib
   restoreFile bin jsse.jar          lib
   restoreFile bin log4j-core.jar    lib
   restoreFile bin regexp.jar        lib
   restoreFile bin xmlparserv2.jar   lib

   # Restore the license agreement:
   restoreFile doc jsse_license.html 

   # Restore the saved lockfile
   restoreFile bin lockfile
}

# cleanup backed up setup Files
removeBackupSetupFiles()
{
    $RMF $CCR_HOME/bin/setupCCR.save
    $RMF $CCR_HOME/bin/deployPackages.save
    $RMF $CCR_HOME/bin/OsInfo.class.save
    $RMF $CCR_HOME/bin/emocmclnt.jar.save
    $RMF $CCR_HOME/bin/emocmclnt-14.jar.save
    $RMF $CCR_HOME/bin/emocmcommon.jar.save
    $RMF $CCR_HOME/bin/osdt_core3.jar.save
    $RMF $CCR_HOME/bin/osdt_jce.jar.save
    $RMF $CCR_HOME/bin/http_client.jar.save
    $RMF $CCR_HOME/bin/jcert.jar.save
    $RMF $CCR_HOME/bin/jnet.jar.save
    $RMF $CCR_HOME/bin/jsse.jar.save
    $RMF $CCR_HOME/bin/log4j-core.jar.save
    $RMF $CCR_HOME/bin/regexp.jar.save
    $RMF $CCR_HOME/bin/xmlparserv2.jar.save
    $RMF $CCR_HOME/doc/jsse_license.html.save
    $RMF $CCR_HOME/bin/emocmrsp.save
    $RMF $CCR_HOME/bin/lockfile.save
}

# This function makes a backup of all modified configuration files. Constants
# are declared to be used to refer to the backups. The backup variables follow
# the form [USER|SYSTEM]_<basename-prop-file>_BACKUP
#
# For example, the file $CCR_HOME/config/ccr.properties would have its backup
# named: USER_CCR_BACKUP
# 
# Note, previous backups are replaced.
backupConfigFiles()
{
   if [ -f ${CCR_CONFIG_HOME}/config/ccr.properties ]
   then
       USER_CCR_BACKUP=${CCR_CONFIG_HOME}/config/ccr.properties.$$
       $CP -f ${CCR_CONFIG_HOME}/config/ccr.properties $USER_CCR_BACKUP
   fi
   if [ -f ${CCR_CONFIG_HOME}/config/default/ccr.properties ]
   then
       USERDEF_CCR_BACKUP=${CCR_CONFIG_HOME}/config/default/ccr.properties.$$
       $CP -f ${CCR_CONFIG_HOME}/config/default/ccr.properties $USERDEF_CCR_BACKUP
   fi

   if [ -f ${CCR_CONFIG_HOME}/config/collector.properties ]
   then
       USER_COLLECTOR_BACKUP=${CCR_CONFIG_HOME}/config/collector.properties.$$
       $CP -f ${CCR_CONFIG_HOME}/config/collector.properties $USER_COLLECTOR_BACKUP
   fi
   if [ -f ${CCR_CONFIG_HOME}/config/default/collector.properties ]
   then
       USERDEF_COLLECTOR_BACKUP=${CCR_CONFIG_HOME}/config/default/collector.properties.$$
       $CP -f ${CCR_CONFIG_HOME}/config/default/collector.properties $USERDEF_COLLECTOR_BACKUP
   fi
}

# Restore config files restores the file contents if needed.
restoreConfigFiles()
{
    if [ ! -z "${USER_CCR_BACKUP}" ]
    then
        if [ -f $USER_CCR_BACKUP ]
        then
            $MV -f $USER_CCR_BACKUP \
                   ${CCR_CONFIG_HOME}/config/ccr.properties
        fi
    else
        $RMF ${CCR_CONFIG_HOME}/config/ccr.properties
    fi
    if [ ! -z "${USERDEF_CCR_BACKUP}" ]
    then
        if [ -f $USERDEF_CCR_BACKUP ]
        then
            $MV -f $USERDEF_CCR_BACKUP \
                   ${CCR_CONFIG_HOME}/config/default/ccr.properties
        fi
    else
        $RMF ${CCR_CONFIG_HOME}/config/default/ccr.properties
    fi

    if [ ! -z "${USER_COLLECTOR_BACKUP}" ]
    then
        if [ -f $USER_COLLECTOR_BACKUP ]
        then
            $MV -f $USER_COLLECTOR_BACKUP \
                   ${CCR_CONFIG_HOME}/config/collector.properties
        fi
    else
        $RMF ${CCR_CONFIG_HOME}/config/collector.properties
    fi
    if [ ! -z "${USERDEF_COLLECTOR_BACKUP}" ]
    then
        if [ -f $USERDEF_COLLECTOR_BACKUP ]
        then
            $MV -f $USERDEF_COLLECTOR_BACKUP \
                   ${CCR_CONFIG_HOME}/config/default/collector.properties
        fi
    else
        $RMF ${CCR_CONFIG_HOME}/config/default/collector.properties
    fi

}

# Remove/cleanup all the backup configuration files
#
removeBackupConfigFiles()
{
    if [ ! -z "${USER_CCR_BACKUP}" ]
    then
        $RMF $USER_CCR_BACKUP
    fi
    if [ ! -z "${USERDEF_CCR_BACKUP}" ]
    then
        $RMF $USERDEF_CCR_BACKUP
    fi

    if [ ! -z "${USER_COLLECTOR_BACKUP}" ]
    then
        $RMF $USER_COLLECTOR_BACKUP
    fi

    if [ ! -z "${USERDEF_COLLECTOR_BACKUP}" ]
    then
        $RMF $USERDEF_COLLECTOR_BACKUP
    fi
}

# Called from checkPrerequisite, this function performs conditional logic
# on the type of message to return with corrective action
reportInvalidJDKError()
{
    # If this is a prereq check in a complete install, refer to
    # emSnapshotEnv, otherwise just give the error and terminate.
    if [ -f ${CCR_HOME}/bin/emCCR ]
    then
        $ECHO "Redefine JAVA_HOME to refer to a JDK/JRE 1.2.2 or greater and invoke "
        $ECHO "  $ORACLE_HOME/ccr/bin/emSnapshotEnv."
    else
        $ECHO "Redefine JAVA_HOME to refer to a JDK/JRE 1.2.2 or greater."
    fi
}

checkPrerequisites()
{
    set +e
    if [ ! -z "${JAVA_HOME_CCR}" ]
    then
        _JAVA_HOME=${JAVA_HOME_CCR}
        _JAVA_BIN=${JAVA_HOME_CCR}/bin
        _javaLoc="The JAVA_HOME_CCR environment variable"
    elif [ ! -z "${JAVA_HOME}" ]
        then
            _JAVA_HOME=$JAVA_HOME
            _JAVA_BIN=${JAVA_HOME}/bin
            _javaLoc="JAVA_HOME"
        else
            _CCR_PARENT=`$DIRNAME ${CCR_HOME}`
            _JAVA_HOME=${_CCR_PARENT}/jdk
            _JAVA_BIN=${_JAVA_HOME}/bin
            _javaLoc="The ORACLE_HOME"
    fi

    # find jre home, if jdk home is not found
    if [ ! -f ${_JAVA_BIN}/java ]
    then
         _JAVA_HOME=${_CCR_PARENT}/jre
         _JAVA_BIN=${_JAVA_HOME}/bin
    fi

    if [ ! -f ${_JAVA_BIN}/java ]
    then
        $ECHO "${_javaLoc} does not contain java."
        $ECHO "${_javaLoc} does not contain a valid JDK/JRE."
        reportInvalidJDKError
        _EXIT $ERR_PREREQ_FAILURE
    fi

    java_version=`${_JAVA_BIN}/java -version 2>&1`
    cmd_exit=$?
    java_version=`$ECHO $java_version | \
                  $EGREP 'java version' | $CUT -d'"' -f2 | $CUT -d'"' -f1`
    java_major_version=`$ECHO $java_version | $CUT -d'.' -f1`
    java_minor_version=`$ECHO $java_version | $CUT -d'.' -f2`

    if [ $cmd_exit != 0 -o \
         -z "${java_major_version}" -o \
         -z "${java_minor_version}" ]
    then
        $ECHO "${_javaLoc} does not contain a valid JDK/JRE."
        reportInvalidJDKError
        _EXIT $ERR_PREREQ_FAILURE
    fi

    if [ "$java_major_version" -ne "1" -o \
         "$java_minor_version" -eq "1" ]
    then
        $ECHO "Java Version $java_version is less than minimum required (1.2.2)."
        $ECHO "${_javaLoc} does not contain a valid JDK/JRE."
        reportInvalidJDKError
        _EXIT $ERR_PREREQ_FAILURE
    fi

    JAVA_HOME=${_JAVA_HOME}
    export JAVA_HOME
    set -e
}

presentLicenseAgreement()
{
    _signature="$@"
    if [ -f ${CCR_CONFIG_HOME}/config/collector.properties ]
    then
        set +e
        _storedAcceptance=`$EGREP '^ccr.agreement_signer=' ${CCR_CONFIG_HOME}/config/collector.properties | $CUT -f2 -d= | $CUT -f1`
        _TMP_COLLECTOR_PROPS=${CCR_TEMP}/collector_properties.`$DATE +%m-%d-%Y_%H.%M.%S`.$$
        $EGREP -v '^ccr.agreement_signer=' ${CCR_CONFIG_HOME}/config/collector.properties > \
              ${_TMP_COLLECTOR_PROPS}
        $MV -f ${_TMP_COLLECTOR_PROPS} ${CCR_CONFIG_HOME}/config/collector.properties
        set -e
    fi

    if [ -z "${_signature}" -a ! -z "${_storedAcceptance}" ]
    then
        _signature=${_storedAcceptance}
    fi

    if [ -z "${_signature}" ]
    then
        $ECHO "Visit http://www.oracle.com/support/policies.html for Oracle Technical Support policies."
        _signature="true"
    fi

    $TOUCH ${CCR_CONFIG_HOME}/config/collector.properties
    $ECHO "ccr.agreement_signer=${_signature}" >> \
              ${CCR_CONFIG_HOME}/config/collector.properties
}

#
# Stop the scheduler on reconfiguration. This is done based upon a final
# requested state. It should not be called except in specific cases.
stopSchedulerOnReconfig()
{
    _RequestedSchedState=$1

    # If this is a disconnected case, attempt the stop of the scheduler.
    # This is done before the state changes to make certain that the command
    # is still available before switching from connected to disconnected.
    if [ ! -z "${_RequestedSchedState}" -a "${_RequestedSchedState}" = "true" ]; then
        if [ $_a_option -eq $FALSE -a $_r_option -eq $FALSE ]; then
            if [ -f ${CCR_HOME}/bin/emCCR -a \
                   "$G_INIT_DISCONN_STATE" = "false" ]; then
                # Set ignore to avoid exiting if scheduler was already stopped
                set +e
                ${CCR_HOME}/bin/emCCR stop > /dev/null 2>&1
                set -e
            fi
        fi
    fi
}

#
# Note, the scheduler should be stopped before the processDisconn is invoked.
# The logic needed to be decoupled due to bug 7.  
processDisconn()
{
    _disconn=$1

    # Get the current state of the configuration
    if [ -f ${CCR_CONFIG_HOME}/config/collector.properties ]
    then
        set +e
        # Strip out any previously stored connection state in the config_home settings
        _TMP_COLLECTOR_PROPS=${CCR_TEMP}/collector_properties.`$DATE +%m-%d-%Y_%H.%M.%S`.$$
        $EGREP -v "^ccr.disconnected=" ${CCR_CONFIG_HOME}/config/collector.properties > \
                                         ${_TMP_COLLECTOR_PROPS}
        set -e

        $MV -f ${_TMP_COLLECTOR_PROPS} \
               ${CCR_CONFIG_HOME}/config/collector.properties
    fi

    # Store the new state of disconnection.
    $ECHO ccr.disconnected=${_disconn} >> ${CCR_CONFIG_HOME}/config/collector.properties

    # If the status is to go disconnected, remove all previous state files
    if [ "$_disconn" = "true" ]; then
        if [ $G_NewInstall -eq $FALSE -a "$G_INIT_DISCONN_STATE" = "false" -a $_a_option -eq $FALSE -a $_r_option -eq $FALSE ]; then
          # Do a collection so that oracle_livelink target's status is uploaded
          $LOCKFILE -5 -r 60 -l 600 ${_collectorLock} > /dev/null 2>&1
          if [ $? -eq 0 ]; then
              set +e
              ${CCR_LIB}/emCCRCollector -silent -connect discover collect upload "-collection=Oracle Configuration Manager,oracle_livelink" > /dev/null 2>&1
              set -e
              _tmpCollLock=`$LS -l ${_collectorLock} | $AWK '{print $NF}'`
              $RMF ${_collectorLock}
              $RMF ${_tmpCollLock}
          fi
        fi
        $RMF ${CCR_CONFIG_HOME}/state/previous/*.ser
    fi
}

rollbackCore()
{
   if [ ! -z "$1" ]; then
      _exitCode=$1
   else
      _exitCode=$ERR_UNEXPECTED_FAILURE
   fi

   # _silent is passed as arg 2 if a rollback with no echo is
   # desired
   _silent=$2

   set +e
   if [ "${PLATFORM}" = "Linux" -o "${PLATFORM}" = "SunOS" ]; then
       trap 0
   else
       trap '' ERR
   fi

   # If in the install code path (and not the reconfiguration path)
   if [ ! -z "$CCR_INSTALL_CODEPATH" ]
     then
     if [ $CCR_INSTALL_CODEPATH -eq 1 ]
     then

       # If the emCCRenv exists thru the install, remove it.
       $RMF ${CCR_CONFIG_HOME}/config/emCCRenv

       # Uninstall the CORE package if it was successfully deployed.
       if [ -f $CCR_HOME/inventory/core.jar ]
       then
           $CCR_HOME/bin/deployPackages -d $CCR_HOME/inventory/core.jar
       fi

       # Remove the product registration on a failed installation
       $RMF ${CCR_CONFIG_HOME}/config/default/uplinkreg.bin

       # Restore archived backup files used in setup
       restoreSetupFiles

       if [ -f $CCR_HOME/inventory/core.jar ]
       then
           $MV $CCR_HOME/inventory/core.jar \
               $CCR_HOME/inventory/pending
       fi

       # Remove the collector.properties as it did not exist on the onset
       $RMF ${CCR_CONFIG_HOME}/config/collector.properties
     else
       if [ -z "${_silent}" ]; then
           $ECHO ""
           $ECHO "** Configuration changes restored to previous values... **"
       fi
     fi
   fi

   # Restore all the user specified config files
   restoreConfigFiles
   removeBackupConfigFiles

   _EXIT $_exitCode
}


# Add the crontab entry if switching to connected mode
# This method can be called only if crontab access is verified (eg: warnIfCronDisallowed)
addCronTabIfNeeded()
{
    if [ -z "${CCR_DISABLE_CRON_ENTRY}" ]
    then
        #
        # Turn off command exit's terminating the shell temporarily, as 
        # this is a handled condition
        if [ "${PLATFORM}" = "HP-UX" -o "${PLATFORM}" = "AIX" -o "${PLATFORM}" = "OSF1" ]; then
            trap '' ERR
        fi
        set +e
        $CRONTAB -l > ${_tmpCrontab} 2>${_tmpCrontab}.err

        # Entries to be added are conditionally specified using the ORACLE_CONFIG_HOME=
        # strings, only if this is a sharedHome supported config.
        _entryFound=`$EGREP -c "(JAVA_HOME=[^ ]*)? ${G_ORACLE_CONFIG_HOME_VAR}${CCR_HOME}/bin/emCCR " ${_tmpCrontab}`
        _betaEntryFound=`$EGREP -c "^[0-9]+ [0-9]+ \* \* \*.* ${CCR_HOME}/bin/emCCR " ${_tmpCrontab}`

        if [ "${PLATFORM}" = "HP-UX" -o "${PLATFORM}" = "AIX" -o "${PLATFORM}" = "OSF1" ]; then
            trap 'rollbackCore' ERR
        fi
        set -e

        # if the beta entry was found or there was no crontab entry
        if [ ${_entryFound} -eq 0 -o \
             ${_betaEntryFound} -ne 0 ]
        then
            # If the beta entry was found remove it from the list of 
            # scheduled crontab jobs.
            if [ ${_betaEntryFound} -ne 0 ]
            then
                set +e
                $EGREP -v "^[0-9]+ [0-9]+ \* \* \*.* ${CCR_HOME}/bin/emCCR " \
                          ${_tmpCrontab} > ${_tmpCrontab}.2
                set -e
                $MV ${_tmpCrontab}.2 ${_tmpCrontab}
            fi

            # Add the entry
            if [ -f ${CCR_HOME}/admin/scripts/crontab.entry.template ]
            then

              $SED -e "s?%ORACLE_HOME%?${ORACLE_HOME}?g" \
                   -e "s?%ORACLE_CONFIG_HOME%?${G_ORACLE_CONFIG_HOME_VAR}?g" \
              ${CCR_HOME}/admin/scripts/crontab.entry.template > \
              ${CCR_CONFIG_HOME}/config/default/crontab.entry
              $EGREP -v "#" ${CCR_CONFIG_HOME}/config/default/crontab.entry >> ${_tmpCrontab}
              $RMF ${CCR_CONFIG_HOME}/config/default/crontab.entry
              $CRONTAB ${_tmpCrontab} 2>/dev/null
            fi
        fi

    #
    # Clean up after the addition of the crontab entry.
    if [ -f ${_tmpCrontab} ]
    then
        $RMF ${_tmpCrontab}
    fi
    $RMF ${_tmpCrontab}.err
fi
}

# Remove the crontab entry for the current home collector.
removeCronTabIfNeeded()
{
  # make certain crontab commands do not cause this to fail.
  set +e
  if [ "${PLATFORM}" = "HP-UX" -o "${PLATFORM}" = "AIX" -o "${PLATFORM}" = "OSF1" ]; then
      trap '' ERR
  fi
  $CRONTAB -l > /dev/null 2>&1
  # Proceed only if crontab command succeeded (eg. crontab is not disabled)
  if [ $? -eq 0 ]
  then
    $CRONTAB -l > ${_tmpCrontab}
    
    $EGREP -v "(JAVA_HOME=[^ ]*)? ${G_ORACLE_CONFIG_HOME_VAR}${CCR_HOME}/bin/emCCR " ${_tmpCrontab} > ${_tmpCrontab}.1
    $DIFF ${_tmpCrontab}.1 ${_tmpCrontab} > /dev/null 2>&1
    if [ $? -ne 0 ]
    then
       $CRONTAB ${_tmpCrontab}.1
    fi
    $RMF ${_tmpCrontab}
    $RMF ${_tmpCrontab}.1
  fi
  if [ "${PLATFORM}" = "HP-UX" -o "${PLATFORM}" = "AIX" -o "${PLATFORM}" = "OSF1" ]; then
        trap 'rollbackCore' ERR
  fi
  set -e
}

#
# semaphore operations (maintain count of semaphore usage)
#
initSemaphores()
{
  $LOCKFILE -2 -r 7 -l 15 ${_semaphoreLock} > /dev/null 2>&1
  if [ $? -ne 0 ]; then
     $ECHO "Unable to initialize semaphore lock, aborting."
     _EXIT $ERR_LOCK_FAILURE
  fi

  if [ ! -s ${_semaphoreOp} ] ; then
    $ECHO 0 > ${_semaphoreOp}
  else
    check=`$CAT ${_semaphoreOp}`
    check2=`$ECHO ${check} | $TR -dc "[0-9]"`
    if [ -z "${check}" -o "${check}" != "${check2}" ] ; then
      $ECHO 0 > ${_semaphoreOp}
    fi
  fi

  if [ ! -s ${_semaphoreUpdate} ] ; then
    $ECHO 0 > ${_semaphoreUpdate}
  else
    check=`$CAT ${_semaphoreUpdate}`
    check2=`$ECHO ${check} | $TR -dc "[0-9]"`
    if [ -z "${check}" -o "${check}" != "${check2}" ] ; then
      $ECHO 0 > ${_semaphoreUpdate}
    fi
  fi
  _tmpSemLock=`$LS -l ${_semaphoreLock} | $AWK '{print $NF}'`
  $RMF ${_semaphoreLock}
  $RMF ${_tmpSemLock}
}

incrSemaphore()
{
  if [ "$1" = "${_semaphoreOp}" ] ; then
    _conflict=${_semaphoreUpdate}
  else
    _conflict=${_semaphoreOp}
  fi
  # check the value of the opposing semaphore
  $LOCKFILE -2 -r 7 -l 15 ${_semaphoreLock} > /dev/null 2>&1
  if [ $? -ne 0 ]; then
     $ECHO "Unable to acquire semaphore lock to synchronize operation, aborting."
     _EXIT $ERR_LOCK_FAILURE
  fi
  _mustWait=`$CAT ${_conflict}`
  if [ -z "${_mustWait}" ]; then
     _mustWait=0
  fi
  _tmpSemLock=`$LS -l ${_semaphoreLock} | $AWK '{print $NF}'`
  $RMF ${_semaphoreLock}
  $RMF ${_tmpSemLock}

  if [ ${_mustWait} -gt 0 ] ; then
    $ECHO "Operation blocked, waiting..."
    _willWait=120
    while [ ${_mustWait} -gt 0 -a ${_willWait} -gt 0 ] ; do
      sleep 1
      _willWait=`expr ${_willWait} - 1`

      # recheck after sleep
      $LOCKFILE -2 -r 7 -l 15 ${_semaphoreLock} > /dev/null 2>&1
      if [ $? -ne 0 ]; then
         $ECHO "Unable to acquire semaphore lock to synchronize operation, aborting."
         _EXIT $ERR_LOCK_FAILURE
      fi
      _mustWait=`$CAT ${_conflict}`
      if [ -z "${_mustWait}" ]; then
         _mustWait=0
      fi
      _tmpSemLock=`$LS -l ${_semaphoreLock} | $AWK '{print $NF}'`
      $RMF ${_semaphoreLock}
      $RMF ${_tmpSemLock}
    done
    if [ ${_mustWait} -gt 0 ] ; then
      $ECHO "Operation still blocked; aborting!"
      _EXIT $ERR_UNEXPECTED_FAILURE
    fi
  fi

  $LOCKFILE -5 -r 60 -l 600 ${_semaphoreLock} > /dev/null 2>&1
  if [ $? -eq 0 ]; then
    semUseCount=`$CAT $1`
    semUseCount=`expr $semUseCount + 1`

    if [ "$1" = "${_semaphoreOp}" ] ; then
      semTakenOp=1
    else
      semTakenUpd=1
    fi

    $ECHO $semUseCount > $1
    _tmpSemLock=`$LS -l ${_semaphoreLock} | $AWK '{print $NF}'`
    $RMF ${_semaphoreLock}
    $RMF ${_tmpSemLock}
  else
    $ECHO "Unable to synchronize operation, aborting."
    _EXIT $ERR_LOCK_FAILURE
  fi
}

decrSemaphore()
{
  if [ -d ${CCR_CONFIG_HOME}/state -a -f $1 ] ; then
    $LOCKFILE -5 -r 60 -l 600 ${_semaphoreLock} > /dev/null 2>&1
    if [ $? -eq 0 ]; then
      semUseCount=`$CAT $1`
      semUseCount=`$ECHO $semUseCount - 1 | $BC`

      if [ "$1" = "${_semaphoreOp}" ] ; then
        semTakenOp=0
      else
        semTakenUpd=0
      fi

      $ECHO $semUseCount > $1
      _tmpSemLock=`$LS -l ${_semaphoreLock} | $AWK '{print $NF}'`
      $RMF ${_semaphoreLock}
      $RMF ${_tmpSemLock}
    else
      $ECHO "Unable to synchronize operation, aborting."
      _EXIT $ERR_LOCK_FAILURE
    fi
  fi
}

semaphoreTrap()
{
  if [ ${semTakenOp} -ne 0 ] ; then
      decrSemaphore ${_semaphoreOp}
  fi

  if [ ${semTakenUpd} -ne 0 ] ; then
      decrSemaphore ${_semaphoreUpdate}
  fi
 
  # Do not terminate normally - exit here or the path may double decrement
  # the semaphores.
  if [ "${PLATFORM}" = "Linux" -o "${PLATFORM}" = "SunOS" ]; then
      trap 0
  else
      trap '' ERR
  fi
  exit $ERR_UNEXPECTED_FAILURE
}

# Exit routine to clean up and then exit
_EXIT()
{
  if [ ${semTakenOp} -ne 0 ] ; then
      decrSemaphore ${_semaphoreOp}
  fi

  if [ ${semTakenUpd} -ne 0 ] ; then
      decrSemaphore ${_semaphoreUpdate}
  fi

  if [ ${G_ConfigurationCompleted} -eq $TRUE -a ! -z "$1" ] ; then
    if [ $1 -ne $SUCCESS ]; then
      deConfigInstance
      $RMF $CCR_CONFIG_HOME/config/collector.properties
    fi
  fi

  exit $1
}

usage()
{
   cat <<EOF
Usage: $0 [ -s ] [ -d | -C <OracleSupportHubUrl> ] [ -a | -r ] [<csi-number> [<MyOracleSupportId>]]
       $0 [ -R <response-file> ]
EOF
if [ `basename $0` = "configCCR" ]
then
   cat <<EOF
       $0 -D [ -v ] [ -T <target type> [ -N <target name> [ -P <property name> ]]]
EOF
fi
   cat <<EOF

   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.

      -s                  Indicates acceptance of the license agreement found in
                          http://www.oracle.com/support/policies.html.

      -a                  Configures OCM for the current host or ORACLE_CONFIG_HOME.

      -r                  Removes OCM configuration for the current host or ORACLE_CONFIG_HOME.

      -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

EOF
if [ `basename $0` = "configCCR" ]
then
   cat <<EOF
      -D                  Configure missing diagcheck properties.

      -v                  Used with configuring diagnostic checks (-D qualifier).
                          Verifies target properties are sufficiently configured.

      -T                  Target type for the target property to be configured
                          or verified. This is used strictly with Diagnostic Checks
                          (-D qualifier).

      -N                  Target name for the target property to be configured
                          or verified. Target type (-T qualifier) must be specified.
                          This is used strictly with Diagnostic Checks (-D qualifier).

      -P                  Name of the target property to be configured or
                          verified. Value for the property will be prompted.
                          Target type (-T) and target name (-N) must be specified.
                          This is used strictly with Diagnostic Checks (-D qualifier).

EOF
fi
}

setHostName()
{
  CCR_HOST_NAME=`hostname`
  export CCR_HOST_NAME
}

isOCMConfigured()
{
  _verbose=$1
  if [ -z "$_verbose" ]; then
    _verbose=$FALSE
  fi

  G_OCMConfigured=$FALSE

  if [ -d ${CCR_CONFIG_HOME}/config -a -d ${CCR_CONFIG_HOME}/config/default -a \
       -d ${CCR_CONFIG_HOME}/state -a -d ${CCR_CONFIG_HOME}/state/diagnostic -a \
       -d ${CCR_CONFIG_HOME}/state/previous -a -d ${CCR_CONFIG_HOME}/state/review -a \
       -d ${CCR_CONFIG_HOME}/state/temp -a -d ${CCR_CONFIG_HOME}/state/upload -a \
       -d ${CCR_CONFIG_HOME}/log ] ; then

    checkIfDisconnected

    if [ "$_disconnState" = "true"  -o -f ${CCR_CONFIG_HOME}/config/default/uplinkreg.bin ] ; then

        getProperty ccr.agreement_signer collector.properties
        _acceptee=${_returnData}
        
        if [ ! -z "${_acceptee}" ] ; then
          G_OCMConfigured=1
        elif [ $_verbose -eq $TRUE ]; then
            $ECHO "The Oracle Configuration Manager license agreement has not been accepted."
        fi
    elif [ "$_disconnState" = "false" -a \
           ! -f ${CCR_CONFIG_HOME}/config/default/uplinkreg.bin -a \
           -z "$G_ConfigurationRequest" -a \
           -z "${_responseFile}" -a -z "${_repeaterOption}" ]; then
      $ECHO "The configuration of Oracle Configuration Manager is unregistered."
      $ECHO "Please run the $ORACLE_HOME/bin/emCCR register command."
    fi
  elif [ $_verbose -eq $TRUE ]; then
     $ECHO "The Oracle Configuration Manager state/writeable directory structure is incomplete."
  fi
}

checkIfDisconnected()
{
  getProperty ccr.disconnected collector.properties
  _disconnState=${_returnData}
}

setOCMDirPaths()
{
  if [ ${G_SharedHomesSupported} -eq 0 ]
  then
    # Check whether its a shared OCM install
    if [ -z "${ORACLE_CONFIG_HOME}" ]
    then
      CCR_CONFIG_HOME="${CCR_HOME}/hosts/${CCR_HOST_NAME}"
    elif [ -d "${ORACLE_CONFIG_HOME}" ]
    then
      set +e
      _isRelative=`$ECHO ${ORACLE_CONFIG_HOME} | $EGREP -c '^/'`
      if [ ${_isRelative} -eq 0 ] ; then
        $ECHO 'ORACLE_CONFIG_HOME refers to a relative path.'
        $ECHO 'Redefine ORACLE_CONFIG_HOME to refer to an absolute path, or'
        $ECHO 'unset it if the configuration state is in the ccr directory tree.'
        exit $ERR_PREREQ_FAILURE
      set -e
      else
        # Determine the owner of the ORACLE_CONFIG_HOME directory. This is not
        # foolproof, but will indicate the owner of the home.
        _UID=`$ID | $CUT -d'=' -f2 | $CUT -d'(' -f1`
        OCH_OWNER=`$LS -Llnd $ORACLE_CONFIG_HOME |$AWK '{print $3}'`
        if [ "${_UID}" != "${OCH_OWNER}" ]; then
          echo "*****"
          echo "Only the ORACLE_CONFIG_HOME owner can install or configure the Oracle Configuration Manager in an"
          echo "ORACLE_CONFIG_HOME structure. The ORACLE_CONFIG_HOME (${ORACLE_CONFIG_HOME}) is owned by the UID $OCH_OWNER"
          echo "*****"
          _EXIT $ERR_PREREQ_FAILURE
        fi
        # strip any trailing dirsep
        ORACLE_CONFIG_HOME=`$ECHO ${ORACLE_CONFIG_HOME} | $SED -e 's/\/*$//'`
        CCR_CONFIG_HOME="${ORACLE_CONFIG_HOME}/ccr"
      fi
    else
      $ECHO 'ORACLE_CONFIG_HOME refers to a non-existent directory.'
      $ECHO 'Redefine ORACLE_CONFIG_HOME to refer to the correct location or'
      $ECHO 'unset it if the configuration state is in the ccr directory tree.'
      exit $ERR_PREREQ_FAILURE
    fi
  else
     CCR_CONFIG_HOME=${CCR_HOME}
  fi

  export CCR_CONFIG_HOME
}

configInstance()
{
  # It should be a multiple host supporting installation OR its the first/only host
  if [ ${G_SharedHomesSupported} -eq 0 ]; then
    isOCMConfigured 
    if [ ${G_OCMConfigured} -eq $FALSE ]; then
      #
      # create the subtrees under CCR_CONFIG_HOME
      #
      for LL_SUBDIRS in config config/default state state/review state/previous state/upload  state/upload/external state/temp state/diagnostic log
      do
        path=${CCR_CONFIG_HOME}/${LL_SUBDIRS}
        if [ ! -d $path ]; then
          $MKDIRP $path
          $CHMOD 700 $path
        fi
      done
      #
      # copy base properties, NOT defaults
      #
      if [ "${CCR_HOME}" != "${CCR_CONFIG_HOME}" ]; then
        # The following line is commented to fix bug 7019958
        # $CP -f $CCR_HOME/config/ccr.properties $CCR_CONFIG_HOME/config/
        # $CP -f $CCR_HOME/config/default/ccr.properties $CCR_CONFIG_HOME/config/default/
        if [ -f $CCR_HOME/config/collector.properties ] ; then 
          $CP -f $CCR_HOME/config/collector.properties $CCR_CONFIG_HOME/config/
        fi
        # if [ -f $CCR_HOME/config/default/collector.properties ] ; then 
        #   $CP -f $CCR_HOME/config/default/collector.properties $CCR_CONFIG_HOME/config/default/
        # fi
      fi

      # Add the location of ccr.binHome to the collector.properties in the 
      # CCR_CONFIG_HOME/config directory if it is not present already.
      set +e
      _ccrBinFound=0
      if [ -f $CCR_CONFIG_HOME/config/collector.properties ]; then
          _ccrBinFound=`$EGREP -c '^ccr.binHome=' \
                             $CCR_CONFIG_HOME/config/collector.properties`
      fi
      if [ $_ccrBinFound -eq 0 -a \
           -f $CCR_CONFIG_HOME/config/default/collector.properties ]; then
          _ccrBinFound=`$EGREP -c '^ccr.binHome=' \
                             $CCR_CONFIG_HOME/config/default/collector.properties`
      fi
      set -e
      if [ $_ccrBinFound -eq 0 ]; then
          $ECHO "ccr.binHome=${CCR_HOME}" >> \
                $CCR_CONFIG_HOME/config/collector.properties
      fi

      #
      # enable add crontab entry
      #
      G_ADD_CRON="true"
      #
      # instantiate scheduler properties file
      #
      if [ ! -f ${CCR_CONFIG_HOME}/config/default/sched.properties -a -f ${CCR_HOME}/config/default/sched.properties.template ]; then
        _frequency=DAILY
        _hour=`$DATE +%H`
        _minute=`$DATE +%M`
        _dow=`$DATE +%u`
        $SED -e "s?%FREQUENCY%?$_frequency?g" \
             -e "s?%HOUR%?$_hour?g" \
             -e "s?%MINUTE%?$_minute?g" \
             -e "s?%DAY_OF_WEEK%?$_dow?g" \
                    ${CCR_HOME}/config/default/sched.properties.template > \
                    ${CCR_CONFIG_HOME}/config/default/sched.properties
                                                                                                       
      fi

      ${VERBOSE} ${CCR_BIN}/emSnapshotEnv

    else
        $ECHO "This installation is already configured for OCM. Please remove existing configuration first."
        _EXIT $ERR_PREREQ_FAILURE
    fi
  else
     $ECHO "This OCM install can support only one instance."
     _EXIT $ERR_PREREQ_FAILURE
  fi

  # Indicate the configuration phase completed.
  G_ConfigurationCompleted=$TRUE
}

deConfigInstance()
{
  if [ ${G_SharedHomesSupported} -eq 0 ]
  then
    if [ "${G_ConfigurationRequest}" = "deconfig" -a \
         ! -z "$ORACLE_CONFIG_HOME" -a \
         "$ORACLE_CONFIG_HOME" = "$ORACLE_HOME" ]; then
      $ECHO "Removing the configuration where \$ORACLE_CONFIG_HOME is the same as "
      $ECHO "the parent directory of the ccr directory ($CCR_HOME) is not permitted."
      _EXIT $ERR_PREREQ_FALURE
    fi

    isOCMConfigured $FALSE

    set +e 
   
    if [ $G_ConfigurationCompleted -eq $TRUE -o \
         "${G_ConfigurationRequest}" = "deconfig" ]; then
      if [ -f $CCR_BIN/emCCR -a $G_OCMConfigured -eq $TRUE ] ; then
          
          checkIfDisconnected
          
          if [ "${_disconnState}" != "true" ]; then
              $ECHO "Stopping Oracle Configuration Manager"
              $CCR_BIN/emCCR stop_abort
          fi
      fi
    fi

    # remove crontab entry for this ORACLE_CONFIG_HOME
    # this can be done only if the user has permissions
    # to create cron jobs
    $CRONTAB -l > ${_tmpCrontab} 2>/dev/null
    if [ $? -eq 0 ] ; then 
       $EGREP -v "(JAVA_HOME=[^ ]*)? ${G_ORACLE_CONFIG_HOME_VAR}${CCR_HOME}/bin/emCCR " ${_tmpCrontab} > ${_tmpCrontab}.1
       $DIFF ${_tmpCrontab}.1 ${_tmpCrontab} > /dev/null 2>&1
       if [ $? -ne 0 ]
       then
          $CRONTAB ${_tmpCrontab}.1
       fi
    fi
    set -e
    $RMF ${_tmpCrontab}
    $RMF ${_tmpCrontab}.1

    if [ "${CCR_HOME}" != "${CCR_CONFIG_HOME}" ]; then
        if [ "${G_ConfigurationRequest}" = "deconfig" ]; then
            $ECHO "Removing writeable/state directories under $CCR_CONFIG_HOME"
        fi

        if [ "${G_ConfigurationRequest}" = "deconfig" -o \
             $G_ConfigurationCompleted -eq $TRUE ]; then
            $RMRF $CCR_CONFIG_HOME/config
            $RMRF $CCR_CONFIG_HOME/state
        fi

        # Only in an explicit deconfig request do we remove the log directory. 
        # This is to retain logs in the cases of failures.
        if [ "${G_ConfigurationRequest}" = "deconfig" ]; then
            $RMRF $CCR_CONFIG_HOME/log
        fi
    fi
  else
    # Only present the error if this is in a deconfiguration request.
    if [ "${G_ConfigurationRequest}" = "deconfig" ]; then
      $ECHO "This OCM install can support only one instance."
      _EXIT $ERR_PREREQ_FAILURE 
    fi
  fi
}

#
# Checks to see that the current environment is sync'd up with the invocation
# of the command in the reconfig mode of the OCH, or a deconfig operation.
#
# Requires that setOCMDirPaths to have been called previously
configMatchesHome()
{
    if [ ${G_SharedHomesSupported} -eq 0 ]; then
        _definedHomePath=""
        if [ -f ${CCR_CONFIG_HOME}/config/collector.properties ]; then
            _definedHomePath=`$EGREP '^ccr.binHome=' \
                              ${CCR_CONFIG_HOME}/config/collector.properties | \
                                  $SED -e 's?^ccr.binHome=??'`
        fi

        if [ -z "${_definedHomePath}" -a \
             -f ${CCR_CONFIG_HOME}/config/default/collector.properties ]; then
            _definedHomePath=`$EGREP '^ccr.binHome=' \
                              ${CCR_CONFIG_HOME}/config/default/collector.properties | \
                                  $SED -e 's?^ccr.binHome=??'`
        fi

        if [ "${_definedHomePath}" != "${CCR_HOME}" ]; then
            # Before we error out, check another case for Solaris only
            # Check absolute paths, sh behaves differently on Solaris
            # sh sets pwd to canonical path, replacing all symlinks
            if [ "${PLATFORM}" = "SunOS" ]; then
                _definedHomePath_Abs=`cd $_definedHomePath && pwd -P`
                CCR_HOME_Abs=`cd $CCR_HOME && pwd -P`
            else
                _definedHomePath_Abs=${_definedHomePath}
                CCR_HOME_Abs=${CCR_HOME}
            fi

            if [ "${_definedHomePath_Abs}" != "${CCR_HOME_Abs}" ]; then
                $ECHO "Error: This OCM configuration location corresponds to the installation in "
                $ECHO "the directory: \"${_definedHomePath}\"."
                exit $ERR_PREREQ_FAILURE
            fi
        fi
    fi
}

warnIfCronDisallowed()
{
    if [ -z "$CCR_DISABLE_CRON_ENTRY" ]; then
        $RMF ${_tmpCrontab}
        $CRONTAB -l > ${_tmpCrontab} 2>${_tmpCrontab}.err
        if [ $? -ne 0 ]; then
            #
            # a crontab -l with no crontab entry returns a non-zero status.
            # In this case, now try to re-add an empty line and see if a 
            # error still occurs.
            
            $ECHO "#OCMComment" > ${_tmpCrontab}_comment
            $CRONTAB ${_tmpCrontab}_comment > /dev/null 2>&1
            if [ $? -ne 0 ]; then
                $ECHO "This account does not have permission to use cron. The Oracle Configuration Manager"
                $ECHO "will not be automatically started on system reboot. Add the command:"
                $ECHO ""
                $ECHO "    ${ORACLE_HOME}/ccr/bin/emCCR start -silent"
                $ECHO ""
                $ECHO "to your system startup procedures."
                CCR_DISABLE_CRON_ENTRY=true
                export CCR_DISABLE_CRON_ENTRY
            else
                $CRONTAB ${_tmpCrontab}
            fi
            $RMF ${_tmpCrontab}_comment
        fi
        $RMF ${_tmpCrontab}
        $RMF ${_tmpCrontab}.err
    fi
}

configDiagcheckProps()
{
  if [ -d ${CCR_CONFIG_HOME}/state ] ; then
    initSemaphores
    trap 'semaphoreTrap' INT

    incrSemaphore ${_semaphoreOp}
  fi

  _originalShellFlags=$-
  set +e
  ${CCR_LIB}/emCCRCollector diagchecks $_diagcheckVerifyOnly "$_diagcheckTargetType" "$_diagcheckTargetName" "$_diagcheckPropertyName"

  # Reset original shell flags only if there were any
  if [ ! -z "${_originalShellFlags}" ]
    then
      set ${_originalShellFlags}
  fi

  if [ -d ${CCR_CONFIG_HOME}/state -a -f ${_semaphoreOp} -a ${semTakenOp} -ne 0 ] ; then
    decrSemaphore ${_semaphoreOp}
  fi
}

#
# Determine the absolute path for the CCR location.
#
CCR_BIN=`$DIRNAME $0 | $TR -s '/'`
# First remove './'s in the beginning
CCR_BIN=`$ECHO $CCR_BIN | $AWK '{ if (match($0,/^(\.\/)*/)){ sub(/^(\.\/)*/,"",$0) }; print $0; }'`
# Next replace all '/./'s in between with '/'
CCR_BIN=`$ECHO $CCR_BIN | $AWK '{ if (match($0,/\/(\.\/)+/)){ gsub(/\/(\.\/)+/,"/",$0) }; print $0;}'`
# Lastly remove '/.' at the end
CCR_BIN=`$ECHO $CCR_BIN | $AWK '{ if (match($0,/\/\.$/)){ sub(/\/\.$/,"",$0) }; print $0; }'`
# Now convert to absolute path
CCR_BIN=`$ECHO $CCR_BIN | $AWK -f ${CCR_BIN}/strip_path.awk PWD=$PWD`
CCR_LIB=`$DIRNAME $CCR_BIN`/lib

#
# Now extract the real variables that are needed.
#
CCR_HOME=`$DIRNAME $CCR_BIN`

# Determine the owner of the ORACLE_HOME directory. This is not
# foolproof, but will indicate the owner of the home.
ORACLE_HOME=`$DIRNAME $CCR_HOME`
_UID=`$ID | $CUT -d'=' -f2 | $CUT -d'(' -f1`
OH_OWNER=`$LS -Llnd $ORACLE_HOME |$AWK '{print $3}'`
if [ "${_UID}" != "${OH_OWNER}" ]; then
    echo "*****"
    echo "Only the Oracle home owner can install or configure the Oracle Configuration Manager in an"
    echo "ORACLE_HOME structure. The ORACLE_HOME (${ORACLE_HOME}) is owned by the UID $OH_OWNER"

    echo "*****"
    _EXIT $ERR_PREREQ_FAILURE
fi

if [ `basename $0` = "setupCCR" ]
then
   # make our version of lockfile executable
   $CHMOD +x ${CCR_BIN}/lockfile

   # Create the ccr/hosts directory
   $MKDIRP ${CCR_HOME}/hosts
   $CHMOD 740 ${CCR_HOME}/hosts

   # Create the ccr/state directory (per bug 7185914)
   $MKDIRP ${CCR_HOME}/state
   $CHMOD 740 ${CCR_HOME}/state

   # set file protections on config files
   $FIND ${CCR_HOME}/config -type f -exec $CHMOD 600 {} \;
   $FIND ${CCR_HOME}/config -type d -exec $CHMOD 700 {} \;

   # We need to configure OCM for this host/home implicitly if its the setup.
   G_ConfigurationRequest="config"

   # Indicate this is a new install
   G_NewInstall=$TRUE
fi

#
# Determine if Shared Oracle Home support is available. This is determined
# thru the new directory 'hosts' under the CCR_HOME.
#
if [ -d "${CCR_HOME}/hosts" ]; then
    G_SharedHomesSupported=0
else
    G_SharedHomesSupported=1
fi

# Set the hostname environment variable
setHostName

# set the paths for config/state/log directory before doing anything else
setOCMDirPaths

# Sets the state of the disconnected-ness of the collector when this
# was invoked.
checkIfDisconnected
G_INSTALL_DISCONN_STATE=${_disconnState}

# sets the G_ORACLE_CONFIG_HOME_VAR to a value if this is a shared home config
# and ORACLE_CONFIG_HOME is specified.
if [ ${G_SharedHomesSupported} -eq 0 -a \
     ! -z "${ORACLE_CONFIG_HOME}" ]; then
    G_ORACLE_CONFIG_HOME_VAR="ORACLE_CONFIG_HOME=${ORACLE_CONFIG_HOME} "
fi

# 
# Snapshot the current environment
#
${CHMOD} 700 ${CCR_BIN}/emSnapshotEnv

# semaphores for operation collision prevention
#
_collectorLock=${CCR_CONFIG_HOME}/state/collector.lock
_semaphoreLock=${CCR_CONFIG_HOME}/state/semaphore.lock
_semaphoreOp=${CCR_CONFIG_HOME}/state/semaphore.op
_semaphoreUpdate=${CCR_CONFIG_HOME}/state/semaphore.update

# Default the temporary directory to /tmp for where temporary files are written.
if [ -z "${CCR_TEMP}" ]
then
    CCR_TEMP=/tmp
    export CCR_TEMP
fi

# Save the variable for future reference
_tmpCrontab=${CCR_TEMP}/crontab.$$

# Source the user specified environment that is present in the CCR environment
# snapshot file (maintained by emSnapshotEnv).
if [ -f "${CCR_CONFIG_HOME}/config/emCCRenv" ]
then
    . ${CCR_CONFIG_HOME}/config/emCCRenv
fi

checkPrerequisites

_disconn=false
_a_option=$FALSE
_r_option=$FALSE
_repeaterOption=""
_diagcheckTargetType=""
_diagcheckTargetName=""
_diagcheckPropertyName=""
_isDiagchecksCmd=$FALSE
_diagcheckVerifyOnly="false"

while getopts ":C:R:S:V:T:N:P:shdarDv" _option
do
    if [ $? -eq 0 ]
    then
        #
        # Note, that within the case clause, we can ONLY record the request
        # that is made. Direct dispatch to satisfy the request will eliminate
        # CLI validation where conflicting qualifiers are specified or
        # qualifiers are additive in functions requested. ala -a -d.
        #
        case ${_option}
        in
            h)  usage
                _EXIT $SUCCESS;;
           
            a)
                if [ $G_NewInstall -eq $TRUE ]; then
                    $ECHO "Specification of -a on a new installation is not permitted."
                    _EXIT $ERR_INVALID_USAGE
                fi
                _a_option=$TRUE
                G_ConfigurationRequest="config";;

            r)
                if [ $G_NewInstall -eq $TRUE ]; then
                    $ECHO "Specification of -r during a new installation is not permitted."
                    _EXIT $ERR_INVALID_USAGE
                fi
                _r_option=$TRUE
                G_ConfigurationRequest="deconfig";;

            d)
                _disconnQualSpecified="yes"
                _disconn=true;;

            s)
                _signature=true;;

            D)
                _isDiagchecksCmd=$TRUE;;

            v)
                _diagcheckVerifyOnly="true";;

            R)
                _responseFile=${OPTARG};;

            C)
                _repeaterURL=${OPTARG};;

            S) 
                _softwareSource=${OPTARG};;

            V)
                _softwareSourceVers=${OPTARG};;

            T)
                if [ ! -z ${_diagcheckTargetType} ]; then
                  $ECHO "only one -T qualifier is allowed"
                  usage
                  _EXIT $ERR_INVALID_USAGE
                fi
                _diagcheckTargetType=${OPTARG};;

            N)
                if [ ! -z ${_diagcheckTargetName} ]; then
                  $ECHO "only one -N qualifier is allowed"
                  usage
                  _EXIT $ERR_INVALID_USAGE
                fi
                _diagcheckTargetName=${OPTARG};;

            P)
                if [ ! -z ${_diagcheckPropertyName} ]; then
                  $ECHO "only one -P qualifier is allowed"
                  usage
                  _EXIT $ERR_INVALID_USAGE
                fi
                _diagcheckPropertyName=${OPTARG};;

            :) 
                $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

# If adding a config and removing a config were both specified. inidicate a mutual
# exlusion violation
if [ $_a_option -eq $TRUE -a $_r_option -eq $TRUE ]; then
    $ECHO "Options -a and -r are mutually exclusive."
    _EXIT $ERR_INVALID_USAGE
fi

# bug 9478596, diagcheck options are not allowed for setupCCR command
if [ `basename $0` = "setupCCR" ]; then
    if [ ${_isDiagchecksCmd} -eq $TRUE -o \
         ${_diagcheckVerifyOnly} = "true" -o \
         ! -z "${_diagcheckTargetType}" -o \
         ! -z "${_diagcheckTargetName}" -o \
         ! -z "${_diagcheckPropertyName}" ]; then
        $ECHO "Diagchecks options -D, -v, -T, -N and -P are invalid for setupCCR command."     
        usage
        _EXIT $ERR_INVALID_USAGE    
    fi
fi

if [ ${_isDiagchecksCmd} -eq $TRUE ]; then
  if [ $_a_option -eq $TRUE -o \
       $_r_option -eq $TRUE -o \
       "$_disconn" = "true" -o \
       "$_signature" = "true" -o \
       ! -z "${_responseFile}" -o \
       ! -z "${_repeaterURL}" -o \
       ! -z "${_softwareSource}" -o \
       ! -z "${_softwareSourceVers}" ]; then
    $ECHO "Option -D is for diagcheck only and cannot be combined with other actions such as -a, -r, -d, -s, -R or -C"
    usage
    _EXIT $ERR_INVALID_USAGE
  fi
fi

if [ ${_diagcheckVerifyOnly} = "true" -o \
     ! -z "${_diagcheckTargetType}" -o \
     ! -z "${_diagcheckTargetName}" -o \
     ! -z "${_diagcheckPropertyName}" ]; then
  if [ ${_isDiagchecksCmd} -ne $TRUE ]; then
    $ECHO "options -v, -T -N -P are only valid when -D option is used"
    usage
    _EXIT $ERR_INVALID_USAGE
  fi
fi

if [ ! -z "$_diagcheckTargetName" -a -z "$_diagcheckTargetType" ]; then
  $ECHO "Can't use -N without specifying -T."
  usage
  _EXIT $ERR_INVALID_USAGE
fi

if [ ! -z "$_diagcheckPropertyName" ]; then
  if [ -z "$_diagcheckTargetType" -o -z "$_diagcheckTargetName" ]; then
    $ECHO "Can't use -P without specifying both -T and -N."
    usage
    _EXIT $ERR_INVALID_USAGE
  fi
fi

if [ -z "${LOCKFILE}" ]; then
    LOCKFILE=$CCR_HOME/bin/lockfile
    # We now 'distribute' the lockfile script in the core package
    if [ ! -f $LOCKFILE ]; then
        $ECHO "Error: The Oracle Configuration Manager lockfile script is missing. Exiting..."
        exit $ERR_PREREQ_FAILURE
    fi
fi

if [ ${_isDiagchecksCmd} -eq $TRUE ]; then
  configDiagcheckProps
  _EXIT $SUCCESS
fi

_shiftPos=`$ECHO $OPTIND - 1 | $BC`
shift $_shiftPos

# If the R (Response file) was specified, it can't be joined with CSI, Metalink
# ID arguments or the -s qualifiers
if [ ! -z "${_responseFile}" ]; then
   if [ ! -z "${_disconnQualSpecified}" -o \
        ! -z "${_signature}" -o \
        $_r_option -eq $TRUE -o \
        ! -z "$1" ]; then
       $ECHO "A response file can not be specified with -s, -d, -C, -r or command line arguments."
       _EXIT $ERR_INVALID_USAGE
   fi
fi

# If the C (Support Hub/Repeater URL) was specified, it can't be joined with the
# response file (-R), -d, or -r options
if [ ! -z "${_repeaterURL}" ]; then
   if [ ! -z "${_responseFile}" -o \
        ! -z "${_disconnQualSpecified}" -o \
        $_r_option -eq $TRUE ]; then
       $ECHO "The Oracle Support Hub URL can not be specified with -R, -d or -r options."
       _EXIT $ERR_INVALID_USAGE
   fi
   _repeaterOption="-repeater ${_repeaterURL}"
fi

#
#At this stage, we expect csi, mlid, and cc. If there are more arguments, throw error
#
if [ $# -gt 3 ]; then
    $ECHO "Invalid number of arguments"
    $ECHO ""
    usage
    _EXIT $ERR_INVALID_USAGE
fi

# Insure the ORACLE_CONFIG_HOME != ORACLE_HOME when the configCCR -a is called.
# this is invalid in this case.
if [ $_a_option -eq $TRUE -a \
     ! -z "${ORACLE_CONFIG_HOME}" -a \
     "${ORACLE_CONFIG_HOME}" = "${ORACLE_HOME}" ]; then
    $ECHO "ORACLE_CONFIG_HOME can not be the same value as the ORACLE_HOME when adding"
    $ECHO "another OCM configuration."
    _EXIT $ERR_INVALID_USAGE
fi

# OCM should be configured for this host/home by now, if its NOT
# Exit
if [ "${G_ConfigurationRequest}" = "config" ] 
then
   configInstance
else
   isOCMConfigured $TRUE

   if [ $G_OCMConfigured -eq $FALSE -a \
        -z "${_responseFile}" -a -z "${_repeaterOption}" ] ; then
      $ECHO "OCM is not configured for this host or ORACLE_CONFIG_HOME. Please configure OCM first."
      exit -1
   fi

   # Verify the configuration matches what we should be performing
   configMatchesHome

   if [ "${G_ConfigurationRequest}" = "deconfig" ]; then
       deConfigInstance
       _EXIT $SUCCESS
   fi
fi

if [ -d ${CCR_CONFIG_HOME}/state ] ; then
  initSemaphores
  trap 'semaphoreTrap' INT

  incrSemaphore ${_semaphoreOp}
fi

# Backup the contents of the current configuration files
backupConfigFiles

if [ -f "${CCR_HOME}/bin/emCCR" ]; then
    CCR_INSTALL_CODEPATH=0
else
    CCR_INSTALL_CODEPATH=1

    # Backup the setup files
    backupSetupFiles
fi

if [ "${_disconn}" != "true" ]; then
    # Check to see if a response file was specified on the command
    # line. if present, use it, otherwise, provide the interactive
    # interrogation.
    _TMP_RES=${CCR_TEMP}/ocm.rsp.`$DATE +%m-%d-%Y_%H.%M.%S`.$$
   
    if [ -z "${_responseFile}" ]; then
        _responseFile=${_TMP_RES}
        _tmpResponseUsed=1
        
        # If the signature was specified on the command line, don't
        # interrogate for it. 
        if [ ! -z "${_signature}" ]; then
            _licenseQual="-license"
        else
            _licenseQual=""
        fi

        set +e

        # If the core.jar exists in inventory/pending, then this is a
        # reconfiguration.
        if [ $CCR_INSTALL_CODEPATH -eq 1 ]; then
            ${CCR_HOME}/bin/emocmrsp -no_banner ${_licenseQual} -InstallPath \
                          ${_repeaterOption} -output ${_responseFile} $*
        else   
            # This is a reconfiguration, so use the info
            # from the previous setup.
            ${CCR_HOME}/bin/emocmrsp -no_banner ${_licenseQual} -reconfig \
                          ${_repeaterOption} -output ${_responseFile} $*
        fi
        
        _retCode=$?
        if [ $_retCode -ne 0 ]; then
            rollbackCore $_retCode SILENT
        fi

        set -e
    else
        _tmpResponseUsed=0
    fi

    set +e

    _backup_ccr_debug=${CCR_DEBUG}
    CCR_DEBUG=
    export CCR_DEBUG

    # Check to see if the license was accepted.
    _licenseAccepted=`${CCR_HOME}/bin/emocmrsp -no_banner -response_file ${_responseFile} -query license.accepted`
    _retCode=$?
    if [ $_retCode -ne 0 ]; then
        rollbackCore $_retCode SILENT
    fi

    if [ -z "${_licenseAccepted}" ]; then
        if [ $_tmpResponseUsed -eq 1 ]; then
             $RMF $_responseFile
        fi
        $CAT <<EOM
Oracle Configuration Manager has been installed but not configured. OCM enables
Oracle to provide superior, proactive support for our customers. Oracle
strongly recommends customers configure OCM. To complete the configuration of
OCM, refer to the OCM Installation and Administration Guide
(http://www.oracle.com/technology/documentation/ocm.html).
EOM
       #remove .save files
       rollbackCore $ERR_LICENSE_DECLINED SILENT
    elif [ "${_licenseAccepted}" != "true" ]; then
        if [ $_tmpResponseUsed -eq 1 ]; then
             $RMF $_responseFile
        fi
        $CAT <<EOM
Oracle Configuration Manager has been installed but not configured. OCM enables
Oracle to provide superior, proactive support for our customers. Oracle
strongly recommends customers configure OCM. To complete the configuration of
OCM, refer to the OCM Installation and Administration Guide
(http://www.oracle.com/technology/documentation/ocm.html).
EOM
       #remove .save files
       rollbackCore $ERR_LICENSE_DECLINED SILENT
    fi

    # Set the disconnected flaf from the response file.
    _disconn=`${CCR_HOME}/bin/emocmrsp -no_banner -response_file ${_responseFile} -query network_config.disconnected`
    #
    # Re-enable DEBUG
    CCR_DEBUG=${_backup_ccr_debug}
    export CCR_DEBUG

    # Stop the scheduler if going into disconnected mode
    stopSchedulerOnReconfig ${_disconn}
 
    if [ "${_disconn}" = "true" ];then
      # When we are moving to disconnected mode from being configured against
      # a repeater earlier (where the repeater was pointing to a different
      # endpoint than the one originally in ccr.endpoint), stripping out the
      # registration values causes the upload in processDisconn() to fail.
      # So in this case, we run the 'emocmrsp -export' after processDisconn()
      processDisconn ${_disconn}
      # Strip out the previous values for registration from the file and
      # populate with contents of response file
      ${CCR_HOME}/bin/emocmrsp -no_banner -export ${_responseFile}
    else
      # If we are moving to connected mode, running 'emocmrsp -export' after 
      # 'processDisconn()' also strips out the ccr.disconnected property which 
      # we add in processDisconn(). Hence, we run processDisconn() first only 
      # when moving to disconnected mode
      ${CCR_HOME}/bin/emocmrsp -no_banner -export ${_responseFile}
      processDisconn ${_disconn}
    fi

    set -e

    if [ ! -z "${CCR_INSTALL_DEBUG}" ]; then
        $ECHO ""
        $ECHO "${CCR_CONFIG_HOME}/config/ccr.properties"
        $ECHO "========================================"
        $CAT ${CCR_CONFIG_HOME}/config/ccr.properties

        $ECHO ""
        $ECHO "${CCR_CONFIG_HOME}/config/collector.properties"
        $ECHO "=============================================="
        $CAT ${CCR_CONFIG_HOME}/config/collector.properties
        $ECHO ""
    fi
    if [ $_tmpResponseUsed -eq 1 ]; then
        $RMF ${_responseFile}
    fi
else
    presentLicenseAgreement ${_signature}
    stopSchedulerOnReconfig ${_disconn}
    processDisconn ${_disconn}
fi


# If the configuration is new, or being added and its not into disconnected
# mode, then display a warning message if the collector is to disable the 
# cron entry.
if [ "${_disconn}" != "true" ]; then
    if [ "${_r_option}" != "$TRUE" ]; then
        set +e
        warnIfCronDisallowed
        set -e
    fi
fi


if [ ! -f ${CCR_HOME}/inventory/core.jar ]
then 

    # Save the -S and -V qualifier values in the collector property file,
    # replacing the other version.
    _TMP_COLLECTOR_PROPS=${CCR_TEMP}/collector_properties.`$DATE +%m-%d-%Y_%H.%M.%S`.$$
    if [ ! -z "${_softwareSource}" ]; then
        if [ ! -f $CCR_HOME/config/collector.properties ]; then
            $TOUCH $CCR_HOME/config/collector.properties
        fi
        set +e
        $EGREP -v '^ocm.install_source=' \
               $CCR_HOME/config/collector.properties > \
               ${_TMP_COLLECTOR_PROPS}
        set -e
        $ECHO "ocm.install_source=${_softwareSource}" >> \
              ${_TMP_COLLECTOR_PROPS}
        $MV ${_TMP_COLLECTOR_PROPS} $CCR_HOME/config/collector.properties
    fi
    if [ ! -z "${_softwareSourceVers}" ]; then
        if [ ! -f $CCR_HOME/config/collector.properties ]; then
            $TOUCH $CCR_HOME/config/collector.properties
        fi
        set +e
        $EGREP -v '^ocm.install_source.version=' \
               $CCR_HOME/config/collector.properties > \
               ${_TMP_COLLECTOR_PROPS}
        set -e
        $ECHO "ocm.install_source.version=${_softwareSourceVers}" >> \
              ${_TMP_COLLECTOR_PROPS}
        $MV ${_TMP_COLLECTOR_PROPS} $CCR_HOME/config/collector.properties
    fi

    ${VERBOSE} ${CCR_BIN}/emSnapshotEnv

    $ECHO ""
    $ECHO "** Installing base package **"
    CCR_INSTALL_CODEPATH=1
    export CCR_INSTALL_CODEPATH

    $CHMOD +x ${CCR_BIN}/deployPackages

    if [ "${PLATFORM}" = "Linux" -o "${PLATFORM}" = "SunOS" ]; then
        trap 'rollbackCore' EXIT
    else
        trap 'rollbackCore' ERR
    fi

    ${VERBOSE} ${CCR_BIN}/deployPackages -i ${CCR_HOME}/inventory/pending/core.jar
fi

# Toggle crontab only during switching i.e.
# if it is not an install codepath
if [ $CCR_INSTALL_CODEPATH -eq 0 ]
then
  # Need to rollback if cron entry could not be added
  if [ "${PLATFORM}" = "Linux" -o "${PLATFORM}" = "SunOS" ]; then
      trap 'rollbackCore' EXIT
  else
      trap 'rollbackCore' ERR
  fi
  if [ "${_disconn}" != "true" ]
  then
    G_ADD_CRON="true"
  else
    removeCronTabIfNeeded
  fi
  if [ "${PLATFORM}" = "Linux" -o "${PLATFORM}" = "SunOS" ]; then
      trap 0
  else
      trap '' ERR
  fi
fi

#
# add crontab entry, if configInstance is successful or if CCR_INSTALL_CODPATH is not set
# i.e., if G_ADD_CRON is set
#
if [ "${_disconn}" != "true" -a -f ${CCR_HOME}/admin/scripts/crontab.entry.template -a "${G_ADD_CRON}" = "true" ]; then
  #making it safe that access violations are clear for _tmpCrontab before calling addCronTabIfNeeded
  $TOUCH ${_tmpCrontab};
  # Need to rollback if cron entry could not be added
  if [ "${PLATFORM}" = "Linux" -o "${PLATFORM}" = "SunOS" ]; then
      trap 'rollbackCore' EXIT
  else
      trap 'rollbackCore' ERR
  fi
    addCronTabIfNeeded
  if [ "${PLATFORM}" = "Linux" -o "${PLATFORM}" = "SunOS" ]; then
      trap 0
  else
      trap '' ERR
  fi
fi


if [ -f ${CCR_LIB}/emCCRCollector ]
then
    if [ "${_disconn}" != "true" ]; then
        $ECHO ""
        if [ $CCR_INSTALL_CODEPATH -eq 1 ]
        then
            $ECHO "** Registering installation with Oracle Configuration Manager server(s) **"
        else
            $ECHO "** Validating configuration changes with Oracle Configuration Manager server(s) **"
        fi
        CCR_NOUPDATE=1
        export CCR_NOUPDATE

        if [ "${PLATFORM}" = "Linux" -o "${PLATFORM}" = "SunOS" ]; then
            trap 'rollbackCore' EXIT
        else
            trap 'rollbackCore' ERR
        fi

        ${CCR_LIB}/emCCRCollector -silent register
    fi

    if [ "${PLATFORM}" = "Linux" -o "${PLATFORM}" = "SunOS" ]; then
        trap 0
    else
        trap '' ERR
    fi

    CCR_NOUPDATE=
    export CCR_NOUPDATE
fi

# Connectivity/registration information in tact and validated - it is now safe
# to remove the backups to the configuration files
removeBackupConfigFiles

# Remove the archived backed-up setup Files
removeBackupSetupFiles

# Remove setupCCR
$RMF ${CCR_HOME}/bin/setupCCR

_displayInstallMsgs=""
if [ $CCR_INSTALL_CODEPATH -eq 1 ]
then
    # Display the wellness messages.
    _displayInstallMsgs="true"
    
    # first deploy the remaining install packages
    ${VERBOSE} ${CCR_BIN}/deployPackages
else
    $RMF ${CCR_HOME}/inventory/pending/*.jar
fi

set +e

if [ $CCR_INSTALL_CODEPATH -eq 1 -a "${_disconn}" != "true" ]; then
    # Get any updates to packages from the CCR ContentServer
    $ECHO ""
    $ECHO "** Getting package updates from ContentServer **"

    ${CCR_LIB}/emCCRCollector -silent getupdates

    retCode=$?

    # Continue only if getupdates succeeds (returns 0) or there are 
    # package updates from ContentServer (returns 5)
    # or if there are non mandatory updates and download failed (returns 6)
    # or if unable to contact the content server (returns 3)
    if [ $retCode -ne 0 -a $retCode -ne 5 -a $retCode -ne 6 -a $retCode -ne 3 ]
    then
        _EXIT $retCode
    fi
    if [ $retCode -eq 3 ]
    then
      $ECHO ""
      $ECHO "Unable to determine whether updates to OCM are present."
      $ECHO "The service is unreachable. Continuing with the installation."
    fi
 
    # At this point packages part of the install are present and deployed.
    # Disable the install code path and allow the remaining packages to 
    # be deployed normally for upgrade.
    CCR_INSTALL_CODEPATH=
    export CCR_INSTALL_CODEPATH

    $LS ${CCR_HOME}/inventory/pending/*.jar > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
        ${VERBOSE} ${CCR_BIN}/deployPackages
    fi
fi

# take stock of what we have here
${VERBOSE} ${CCR_BIN}/deployPackages -l | awk '{if (index ($0,"pending deployment")==0) print $0; else exit}' \
  | $EGREP '^Package' | $CUT -d' ' -f2,4 | $SED -e 's/, /=/g' > ${CCR_CONFIG_HOME}/config/default/collector_config.inventory

# Start the scheduler
SCHEDULER_RUNNING=0
if [ -z "${ORACLE_CCR_DEV}" ]
then
    ${CCR_HOME}/bin/emCCR status > /dev/null 2>&1
    if [ $? -eq 0 -o $? -eq 55 ]
    then 
        SCHEDULER_RUNNING=1
    fi
fi

if [ -z "${ORACLE_CCR_DEV}" -a $SCHEDULER_RUNNING -eq 0 -a "${_disconn}" != "true" ]
then
    $ECHO ""
    $ECHO "** Starting the Oracle Configuration Manager Scheduler **"
    options=""
    if [ ! -z "${CCR_INSTALL_DEFER_COLLECT}" ] ; then
        options="-noCollect"
    fi
    $CCR_HOME/bin/emCCR $options start
fi

# Run the ebs_createCtxLocXml.sh 
if [ -f "${CCR_BIN}/ebs_createCtxLocXml.sh" ]
then
    ${VERBOSE} ${CCR_BIN}/ebs_createCtxLocXml.sh -silent
fi

# Display the messages in cases of types of installation.
if [ ! -z "${_displayInstallMsgs}" ]; then
    checkIfDisconnected
    if [ "$_disconnState" = "true" ]; then
        $CAT <<EOM_DISCONN

Oracle Configuration Manager has been configured in disconnected mode. If the
target ORACLE_HOME is running a database, please refer to the
"Post-installation Database Configuration" section of the OCM Installation
and Administration Guide
(http://www.oracle.com/technology/documentation/ocm.html) to complete the
installation.

View configuration data reports and access valuable configuration best
practices by going to My Oracle Support.
EOM_DISCONN
    else
        $CAT <<EOM_CONN

Oracle Configuration Manager has been configured in connected mode. If the
target ORACLE_HOME is running a database, please refer to the
"Post-installation Database Configuration" section of the OCM Installation
and Administration Guide
(http://www.oracle.com/technology/documentation/ocm.html) to complete the
installation.
EOM_CONN
        getProperty ccr.registration_mode ccr.properties
        _registrationMethod=${_returnData}

        if [ "${_registrationMethod}" != "anon" ]; then
            $CAT <<EOM_NOT_ANON

View configuration data reports and access valuable configuration best
practices by going to My Oracle Support.
EOM_NOT_ANON
        fi
    fi
fi

if [ -d ${CCR_CONFIG_HOME}/state -a -f ${_semaphoreOp} -a ${semTakenOp} -ne 0 ] ; then
  decrSemaphore ${_semaphoreOp}
fi

if [ "${PLATFORM}" = "Linux" -o "${PLATFORM}" = "SunOS" ]; then
    trap 0
else
    trap '' ERR
fi

