#!/bin/sh
# $Header: emll/bin/setupCCR /st_emll_10.3.1/2 2009/04/03 14:29:34 tsubrama Exp $
#
# {setup|config}CCR
#
# Copyright (c) 2005, 2009, 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 '_'.
#--

#++
#
# 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

_binDir=/bin
_usrBinDir=/usr/bin
_usrLocalBinDir=/usr/local/bin

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

AWK=${_binDir}/awk
BC=${_usrBinDir}/bc
DIRNAME=${_usrBinDir}/dirname
CHMOD=${_binDir}/chmod
CP=${_binDir}/cp
DATE=${_binDir}/date
ECHO=${_binDir}/echo
GREP=${_binDir}/grep
ID=${_usrBinDir}/id
LS=${_binDir}/ls
BINMORE=${_binDir}/more
MV=${_binDir}/mv
STTY=${_binDir}/stty
TTY=${_usrBinDir}/tty
MKDIRP="${_binDir}/mkdir -p"
MKDIR=${_binDir}/mkdir
FIND=${_usrBinDir}/find

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

CAT=${_binDir}/cat

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

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

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

RM=${_binDir}/rm
RMF="$RM -f"
RMRF="$RM -rf"
SED=${_binDir}/sed
TR=${_usrBinDir}/tr
TOUCH=${_binDir}/touch
CRONTAB=${_usrBinDir}/crontab

PLATFORM=`$UNAME | $CUT -f1`

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

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

if [ "$PLATFORM" = "SunOS" ]
then
    GREP=/usr/xpg4/bin/grep
    SED=/usr/xpg4/bin/sed
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"

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

# Fix for the Back-Space Key (BugFix:5711759)
set +e
${TTY} -s
if [ $? -eq 0 ]; then
trap '' TTOU    # ignore SIGTTOU if we are not interactive
${STTY} erase "^H" kill "^D" intr "^C" eof "^D" susp "^Z"
trap - TTOU     # reset the trap for SIGTTOU (if any)
fi
set -e

# 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=`$GREP -E "^$_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=`$GREP -E "^$_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=`$GREP -E "^$_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=`$GREP -E "^$_propertyName=" ${CCR_HOME}/config/default/${_propertyFile} | \
                      $SED -e "s/$_propertyName=\s*//"`
      fi
   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.
   if [ -f $CCR_HOME/bin/deployPackages ]
   then
       $CP -f $CCR_HOME/bin/deployPackages $CCR_HOME/bin/deployPackages.save
   fi

   # Save OsInfo.class if it exists.
   if [ -f $CCR_HOME/lib/OsInfo.class ]
   then
       $CP -f $CCR_HOME/lib/OsInfo.class $CCR_HOME/bin/OsInfo.class.save
   fi

   # Save the license agreement
   if [ -f $CCR_HOME/doc/jsse_license.html ]
   then
       $CP -f $CCR_HOME/doc/jsse_license.html $CCR_HOME/doc/jsse_license.html.save
   fi

   # Save the ocmResponse generator jar and associated required pieces
   if [ -f $CCR_HOME/lib/emocmutl.jar ]; then
       $CP -f $CCR_HOME/lib/emocmutl.jar $CCR_HOME/bin/emocmutl.jar.save
   fi
   if [ -f $CCR_HOME/lib/emocmclnt-14.jar ]; then
       $CP -f $CCR_HOME/lib/emocmclnt-14.jar $CCR_HOME/bin/emocmclnt-14.jar.save
   fi
   if [ -f $CCR_HOME/lib/osdt_core3.jar ]; then
       $CP -f $CCR_HOME/lib/osdt_core3.jar $CCR_HOME/bin/osdt_core3.jar.save
   fi
   if [ -f $CCR_HOME/lib/osdt_jce.jar ]; then
       $CP -f $CCR_HOME/lib/osdt_jce.jar $CCR_HOME/bin/osdt_jce.jar.save
   fi

   # Save the ocmResponse generator
   if [ -f $CCR_HOME/bin/emocmrsp ]; then
       $CP -f $CCR_HOME/bin/emocmrsp $CCR_HOME/bin/emocmrsp.save
   fi

   # Save the lockfile script
   if [ -f $CCR_HOME/bin/lockfile ]; then
       $CP -f $CCR_HOME/bin/lockfile $CCR_HOME/bin/lockfile.save
   fi
}

# 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 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
   if [ -f $CCR_HOME/bin/emocmrsp.save ]
   then
       $MV -f $CCR_HOME/bin/emocmrsp.save $CCR_HOME/bin/emocmrsp
   fi

   # Restore the saved deployPackages.save to deployPackages
   if [ -f $CCR_HOME/bin/deployPackages.save ]
   then
       $MV -f $CCR_HOME/bin/deployPackages.save $CCR_HOME/bin/deployPackages
   fi

   # Restore the saved OsInfo.class.save to OsInfo.class
   if [ -f $CCR_HOME/bin/OsInfo.class.save ]
   then
       if [ ! -d ${CCR_HOME}/lib ]
       then
       $MKDIRP ${CCR_HOME}/lib
       $CHMOD 740 ${CCR_HOME}/lib
     fi
     $MV -f $CCR_HOME/bin/OsInfo.class.save $CCR_HOME/lib/OsInfo.class
   fi

   # restore the jars necessary for the response generator
   if [ -f $CCR_HOME/bin/emocmutl.jar.save ]
   then
      if [ ! -d ${CCR_HOME}/lib ]
      then
         $MKDIRP ${CCR_HOME}/lib
         $CHMOD 740 ${CCR_HOME}/lib
      fi
      $MV -f $CCR_HOME/bin/emocmutl.jar.save $CCR_HOME/lib/emocmutl.jar
   fi
   if [ -f $CCR_HOME/bin/emocmclnt-14.jar.save ]
   then
      if [ ! -d ${CCR_HOME}/lib ]
      then
         $MKDIRP ${CCR_HOME}/lib
         $CHMOD 740 ${CCR_HOME}/lib
      fi
      $MV -f $CCR_HOME/bin/emocmclnt-14.jar.save $CCR_HOME/lib/emocmclnt-14.jar
   fi
   if [ -f $CCR_HOME/bin/osdt_core3.jar.save ]
   then
      if [ ! -d ${CCR_HOME}/lib ]
      then
         $MKDIRP ${CCR_HOME}/lib
         $CHMOD 740 ${CCR_HOME}/lib
      fi
      $MV -f $CCR_HOME/bin/osdt_core3.jar.save $CCR_HOME/lib/osdt_core3.jar
   fi
   if [ -f $CCR_HOME/bin/osdt_jce.jar.save ]
   then
      if [ ! -d ${CCR_HOME}/lib ]
      then
         $MKDIRP ${CCR_HOME}/lib
         $CHMOD 740 ${CCR_HOME}/lib
      fi
      $MV -f $CCR_HOME/bin/osdt_jce.jar.save $CCR_HOME/lib/osdt_jce.jar
   fi

   # Restore the license agreement:
   if [ -f $CCR_HOME/doc/jsse_license.html.save ]
   then
       $MV -f $CCR_HOME/doc/jsse_license.html.save $CCR_HOME/doc/jsse_license.html
   fi

   # Restore the saved lockfile
   if [ -f $CCR_HOME/bin/lockfile.save ]
   then
       $MV -f $CCR_HOME/bin/lockfile.save $CCR_HOME/bin/lockfile
   fi
}

# 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/emocmutl.jar.save
    $RMF $CCR_HOME/bin/emocmclnt-14.jar.save
    $RMF $CCR_HOME/bin/osdt_core3.jar.save
    $RMF $CCR_HOME/bin/osdt_jce.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 | \
                  $GREP '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=`$GREP -E '^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`.$$
        $GREP -v -E '^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`.$$
        $GREP -E -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 [ $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

    # Restore all the user specified config files
    restoreConfigFiles
    removeBackupConfigFiles

   _EXIT $_exitCode
}

# Called by addCronTabIfNeeded
addCrontabEntry()
{
  #
  # instantiate crontab template and add entry as needed
  #
  if [ -f ${CCR_HOME}/admin/scripts/crontab.entry.template ]
  then
    # Instantiate the crontab file.
    if [ ! -z "${JAVA_HOME_CCR}" ]; then
      JAVA_CRONPATH="JAVA_HOME=${JAVA_HOME_CCR} "
    elif [ ! -z "${JAVA_HOME}" ]; then
      JAVA_CRONPATH="JAVA_HOME=${JAVA_HOME} "
    else
      JAVA_CRONPATH=""
    fi

    $SED -e "s?%JAVA_HOME%?$JAVA_CRONPATH?g" \
         -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
    $GREP -v "#" ${CCR_CONFIG_HOME}/config/default/crontab.entry >> ${_tmpCrontab}
    $RMF ${CCR_CONFIG_HOME}/config/default/crontab.entry
    if [ "${PLATFORM}" = "HP-UX" -o "${PLATFORM}" = "AIX" -o "${PLATFORM}" = "OSF1" ]; then
        trap 'rollbackCore' ERR
    fi
    # Turn off command exit's terminating the shell temporarily, as
    # this is a handled condition
    set +e
    #checking if User have the crontab access
    $CRONTAB -l > /dev/null 2>&1
      if [ $? -eq 1 ]; then
        $ECHO "crontab: you are not authorized to use cron.  Sorry."
        rollbackCore
      fi
    # Reset the original shell flags
    set -e
    $CRONTAB ${_tmpCrontab} 2>/dev/null
    if [ "${PLATFORM}" = "HP-UX" -o "${PLATFORM}" = "AIX" -o "${PLATFORM}" = "OSF1" ]; then
        trap '' ERR
    fi
  fi
}

# Add the crontab entry if switching to connected mode
addCronTabIfNeeded()
{
    if [ -z "${CCR_DISABLE_CRON_ENTRY}" ]
    then
        #
        # Turn off command exit's terminating the shell temporarily, as 
        # this is a handled condition
        set +e

        #
        # Check to see if a crontab file already exists.
        $CRONTAB -l > /dev/null 2>&1
        if [ $? -eq 0 ]
        then
            #
            # Reset the original shell flags
            set -e

            # One exists, so create the temporary file 
            $CRONTAB -l > ${_tmpCrontab}

            # If there was no error writing the file out (out of quota, permissions,
            # disk full) check to see if there was an entry for this path already.
            # The quoted string is needed to make certain that the path
            # that we match is absolute and not some substring.

            set +e
            if [ "${PLATFORM}" = "HP-UX" -o "${PLATFORM}" = "AIX" -o "${PLATFORM}" = "OSF1" ]; then
                trap '' ERR
            fi
           
            # Entries to be added are conditionally specified using the ORACLE_CONFIG_HOME=
            # strings, only if this is a sharedHome supported config.
            _entryFound=`$GREP -cE "JAVA_HOME=[^ ]* ${G_ORACLE_CONFIG_HOME_VAR}${CCR_HOME}/bin/emCCR " ${_tmpCrontab}`
            _betaEntryFound=`$GREP -cE "^[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
                    $GREP -vE "^[0-9]+ [0-9]+ \* \* \*.* ${CCR_HOME}/bin/emCCR " \
                              ${_tmpCrontab} > ${_tmpCrontab}.2
                    set -e
                    $MV ${_tmpCrontab}.2 ${_tmpCrontab}
                fi

                # Add the entry
                addCrontabEntry
            fi
        else
            set -e
            addCrontabEntry
        fi

        #
        # Clean up after the addition of the crontab entry.
        if [ -f ${_tmpCrontab} ]
        then
            $RMF ${_tmpCrontab}
        fi
    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}
    
    $GREP -vE "JAVA_HOME=[^ ]* ${G_ORACLE_CONFIG_HOME_VAR}${CCR_HOME}/bin/emCCR " ${_tmpCrontab} > ${_tmpCrontab}.1
    $CRONTAB ${_tmpCrontab}.1
    $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 ] [ -a | -r ] [<csi-number> [[<MyOracleSupportId>] [<country>]]]
       $0 [ -R <response-file> ]

   where:

      <csi-number>        Oracle Customer Support Identifier (CSI)
      <MyOracleSupportId> My Oracle Support user name registered for the CSI
      <country>           Short character designation for country the CSI is 
                          issued in.
      <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.

EOF
}

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" ]; 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} | $GREP -cE '^/'`
      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/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=`$GREP -cE '^ccr.binHome=' \
                             $CCR_CONFIG_HOME/config/collector.properties`
      fi
      if [ $_ccrBinFound -eq 0 -a \
           -f $CCR_CONFIG_HOME/config/default/collector.properties ]; then
          _ccrBinFound=`$GREP -cE '^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

      #
      # add crontab entry
      #
      if [ "${_disconn}" != "true" -a -f ${CCR_HOME}/admin/scripts/crontab.entry.template ]; then
        addCronTabIfNeeded
      fi
      #
      # 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
       $GREP -vE "JAVA_HOME=[^ ]* ${G_ORACLE_CONFIG_HOME_VAR}${CCR_HOME}/bin/emCCR " ${_tmpCrontab} > ${_tmpCrontab}.1
       $CRONTAB ${_tmpCrontab}.1
    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=`$GREP -E '^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=`$GREP -E '^ccr.binHome=' \
                              ${CCR_CONFIG_HOME}/config/default/collector.properties | \
                                  $SED -e 's?^ccr.binHome=??'`
        fi

        if [ "${_definedHomePath}" != "${CCR_HOME}" ]; then
            $ECHO "Error: This OCM configuration location corresponds to the installation in "
            $ECHO "the directory: \"${_definedHomePath}\"."
            exit $ERR_PREREQ_FAILURE
        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
}

#
# Determine the absolute path for the CCR location.
#
CCR_BIN=`$DIRNAME $0 | $TR -s '/'`
CCR_BIN=`$ECHO $CCR_BIN | $SED -e 's/^\(\.\/\)*//g' -e 's/\/\(\.\/\)*/\//g' -e 's/\/\.$//g'`
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

while getopts ":R:S:V:shdar" _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;;

            R)
                _responseFile=${OPTARG};;

            S) 
                _softwareSource=${OPTARG};;

            V)
                _softwareSourceVers=${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

_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, -r or command line arguments."
       _EXIT $ERR_INVALID_USAGE
   fi
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

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

# 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 ]
   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 \
                          -output ${_responseFile} $*
        else   
            # This is a reconfiguration, so use the info
            # from the previous setup.
            ${CCR_HOME}/bin/emocmrsp -no_banner ${_licenseQual} -reconfig \
                          -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}
 
    # 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}

    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}
fi

processDisconn ${_disconn}

# 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
        $GREP -v -E '^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
        $GREP -v -E '^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
  $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
  if [ "${_disconn}" != "true" ]
  then
    addCronTabIfNeeded
  else
    removeCronTabIfNeeded
  fi
  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)
    if [ $retCode -ne 0 -a $retCode -ne 5 ]
    then
        _EXIT $retCode
    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}' \
  | $GREP -E '^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

