#!/bin/sh
# $Header: emll/bin/setupCCR /st_emll_10.3.5/2 2011/05/17 16:45:55 fmorshed Exp $
#
# {setup|config}CCR
#
# Copyright (c) 2005, 2011, 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
#
#--
# source common stuff
_OCMBinDir=`/usr/bin/dirname $0`
. ${_OCMBinDir}/common

# operation collision semaphore
semTakenOp=0
semTakenUpd=0

# 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
   $CP -f $CCR_HOME/bin/common $CCR_HOME/bin/common.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
   $MV -f $CCR_HOME/bin/common.save $CCR_HOME/bin/common

   # 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/common.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
}

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
       
       # Removing the diagcheck directories if installation fails
       $RMRF ${CCR_CONFIG_HOME}/config/diagchecks_exclude
       $RMRF ${CCR_CONFIG_HOME}/config/diagcheck_wallet
       
     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()
{
if [ `basename $0` = "configCCR" ]
then
   cat <<EOF
Usage: $0 [ -s ] [ -d | -C <OracleSupportHubUrl> ] [ -a | -r ] [<csi-number> [<MyOracleSupportId>]]
       $0 [ -R <response-file> ]
EOF
else
   cat <<EOF
Usage: $0 [ -s ] [ -d | -C <OracleSupportHubUrl> ] [<csi-number> [<MyOracleSupportId>]]
       $0 [ -R <response-file> ]
EOF
fi

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.

      -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.

      -a                  Configures OCM for the current host or ORACLE_CONFIG_HOME.

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

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

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 [ "${G_INSTALL_DISCONN_STATE}" != "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
}

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

determineSharedHomesSupported
setOCMDirPaths
checkIfDisconnected

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

# 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

determineJavaHome $TRUE
if [ $? -ne $SUCCESS ]; then
	_EXIT $?	
fi

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

# Out of place upgrade
# If the environment variable $OUT_OF_PLACE_UPGRADE_INFO is set,
# then we are doing an out of place upgrade, otherwise it is just
# a regular install.   If we are doing an out of place upgrade, 
# then we check the file at $OUT_OF_PLACE_UPGRADE_INFO to see that 
# it exists and is not empty.
_OUT_OF_PLACE_UPGRADE_INFO=${OUT_OF_PLACE_UPGRADE_INFO}
if [ ! -z "${_OUT_OF_PLACE_UPGRADE_INFO}" ] ; then
    if [ -s ${_OUT_OF_PLACE_UPGRADE_INFO} ] ; then
        # Set the classpath
        _OCMLibDir=${ORACLE_HOME}/ccr/lib
        _classpath="${_OCMLibDir}/emocmclnt.jar:${_OCMLibDir}/regexp.jar:${_OCMLibDir}/log4j-core.jar:${_OCMLibDir}/xmlparserv2.jar"
        # Set system property strings for java
        _CCR_CONFIG_HOME="-DCCR_CONFIG_HOME=${CCR_CONFIG_HOME}"
        _upgradeInfo="-DOUT_OF_PLACE_UPGRADE_INFO=${_OUT_OF_PLACE_UPGRADE_INFO}"

        # call the out of place upgrade client java file
        $JAVA_HOME/bin/java ${_upgradeInfo} ${_CCR_CONFIG_HOME} -classpath ${_classpath} oracle.sysman.ccr.collector.util.OutOfPlaceUpgradeClient
        if [ $? -ne $SUCCESS ]; then
            _EXIT $?
        fi
    else
        $ECHO "Out of place upgrade error.  File at ${OUT_OF_PLACE_UPGRADE_INFO} could not be found or is empty.  Continuing with regular OCM install.  Note: duplicate targets could be generated on CCR server with this setup."
    fi ;
fi;

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

# Ensure the ORACLE_CONFIG_HOME != ORACLE_HOME when the configCCR -a is called.
if [ -z "${DERIVECCR_IN_PROGRESS}" -a \
     $_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.
   # When deriveCCR is in progress, we don't care.  In fact, we expect the config home not to match!
   if [ -z "${DERIVECCR_IN_PROGRESS}" ]; then
       configMatchesHome
   fi

   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 [ "$G_INSTALL_DISCONN_STATE" = "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


