#!/bin/ksh
#
#     09/01/05  TR #15461, convert -o to -s for or and oy products
# @22 03/08/05 LCL Add ITMinstall. to JREEXE invocations
# @21 03/02/05 LCL Call CandleDBAgent for or/oy agents
# @20 10/30/03 LCL Safe mode supported in multi-agent mode.
# @19 09/08/03 LCL env.config created in wrong directory (shd be /config)
# @18 06/20/03 LCL TZ handling for Linux
# @17 10/16/02 LCL TZ regenerated each time; 1-20932901
# @16 07/26/02 LCL Replace "line" with "head -1" for Linux
# @15 06/24/02 LCL Stop multi-agent process for codes > 2 chars.
# @14 06/20/02 LCL Suppress cinfo error msgs
# @13 06/06/02 LCL Use cinfo to clean RunInfo before java
# @12 05/29/02 LCL Fix persistent -p when only -o is used
# @11 04/25/02 LCL Add -p option
# @10 04/10/01 LCL ud agent sets umask for um general file access
# @09 01/09/00 LCL Fix looping for "all" used with only 1 agent
# @08 09/29/00 LCL Fix duplicate/uninstalled agent processing for "all"
# @07 09/21/00 LCL Fix multi-agent test for Tru64
# @06 08/02/00 LCL Add safe mode
# @05 07/10/00 LCL Capture cmd line
# @04 06/02/00 LCL Fix duplicate agent processing. Merge versions.
# @03 11/02/99 KLK(lcl) Add special "ea" agent processing, batch option
# @02 11/04/99 LCL Repl imbedded blanks w/commas in -o arg
# @01 11/02/99 LCL Support multi-agent start/stop
#
# This script is a shell wrapper for CandleAgent.class. 
# It checks command line arguments and passes them to CandleAgent.class for 
# further processing.


Err_report() {
   case $1 in
      #$NLS-E$ "$PROGNAME warning: $2,continuing ..."
	  warn) print -u2 "`nls_replace 'KCI0250I' $PROGNAME \"$2\"`"
            sleep 2
            return
            ;;
      #$NLS-E$ "$PROGNAME failure: $2."
	  fail) print -u2 "`nls_replace 'KCI0251I' $PROGNAME \"$2\"`"
            exit 2
            ;;
           info) print -u2 "$PROGNAME        : $2."
            return
            ;;
   esac
}

Use_report() {
    print -u2 "\n$PROGNAME [-l] [-n] [ -h install_dir ] [ -o option ] [ -p option ] [-m] [-c] [-f] start|stop pc\n Use -c option to NOT regenerate config file.\n "
    exit 2
}

###################################################################
#                         Main Routine                            #
###################################################################
bindir=`pwd`/$(dirname $0)
[ "$(print $0 | grep '\./')" = "" ] && [ "$(print $0 | grep '^/.*')" = "" ] && [ `pwd` = '/' ] && bindir=`pwd`$(dirname $0)
[ "$(print $0 | grep '^/.*')" != "" ] && bindir=$(dirname $0)

export TEXTDOMAINDIR=$bindir/../config/nls/msg
export PATH=$bindir:$PATH

export PATH=/usr/bin:$PATH
if [[ -z "$ITMCMD" ]]
then
    PROGNAME=$(basename $0)
else
    PROGNAME="$ITMCMD"
fi

UsrCmd="$0 $*"
SAFE_MODE=""
CONFIGOPT=""
FORCEOPT=""
LOGOPT=""
NOPIDCHECKOPT=""
BATCHOPT=""
OOPTION=""
POPTION=""
binArch=""
MULTIOPT=""
arglist=$*

while getopts ":cfbmlnh:o:p:" OPTS
do case $OPTS in
     c) CONFIGOPT="-c"
        ;;
     f) FORCEOPT="-f"
        ;;		
     h) CANDLEHOME=$OPTARG
        ;;
     l) LOGOPT="-l"
        ;;
     n) NOPIDCHECKOPT="-n"
        ;;
     m) MULTIOPT="-m"
     	;;
     b) BATCHOPT="-batch"
	;;
     o) OOPTION="$OPTARG"
        ;;
     p) POPTION="$OPTARG"
        ;;
     ?) Use_report
        ;;
   esac
done
shift $((OPTIND-1))

if [ $# -lt 2 ]
then
   Use_report
fi

action="$1"; shift; product="$1"; 

if [[ "$action" != "start" && "$action" != "stop" ]]
then
  Use_report
fi

[ -n "$CANDLEHOME" ] || CANDLEHOME=$(cd $(dirname $0) ; dirname $(pwd) )
export CANDLEHOME

if [ ! -d "$CANDLEHOME" ] 
then
   #$NLS-E$ "Cannot set CANDLEHOME environment variable"
   Err_report fail "`nls_replace 'KCI0252E'`"
fi

if [ $(print "$CANDLEHOME" | wc -w) -ne 1 ]
then
  #$NLS-E$ "Blanks are not permitted in install_dir"
  Err_report fail "`nls_replace 'KCI0253E'`"
fi

if [[ "$product" = "ud" && -n "$OOPTION" ]]
then
   productSave=$product
   actionSave=$action
   eval sqlRoot=~"$OOPTION/sqllib"
   UDBINSTANCEDIR=$sqlRoot
   export UDBINSTANCEDIR
   UDB=$sqlRoot/lib
   export UDB
   profFile="$sqlRoot/db2profile"
   if [ -f "$profFile" ]
   then
      print Sourcing db2profile for user $OOPTION
      . $profFile
   else
      Err_report fail "Unable to source db2profile for user $OOPTION"
   fi
   product=$productSave
   action=$actionSave
fi

CurRegPath=$CANDLEHOME/registry
ArchTbl=$CurRegPath/archdsc.tbl 
DynShl=$CANDLEHOME/bin/dynarch.shl

#Defect 17185/17898, the dynarch.shl source intermittently caused a
# shell-init error when this script is run from agent deploy. The cd 
# was added to workaround what's apparently a ksh bug. 
cd $PWD
. $DynShl $ArchTbl

# EJF (#17239) run ulimit on linux
os=$(print $cArch|cut -c1-2)
[[ $os = "li" || $os = "ls" ]] && ulimit -s unlimited

setJavaEnv $cArch

# @01 Test for  multi-agent processing
# Isolate the product list from the rest of the line (follows start/stop)
# Start/stop are reserved words and should not occur as options elsewhere!
product=${arglist#*$action}

# Check if product list does not contain '-' character.
# It is protection against optional arguments at the end of line, after product list.
if [[ $product = *-* ]]; 
then
  Use_report
fi

#  Justify/Shift/trim any user entered uppercase to lower in the product list
product=$(print $product)

if [ ${#product} -gt 2 ]
then

#  Start multi-agent processing

#  For "all" we scan .ConfigData to find configured agents and build a list.
#  k<pp>env files are searched. Criteria is "BINARCH" followed by the OS type
#  of the current system (ie aix, sol).

#  User specified "all" configured agents
   if [ "$product" = "all" ]
   then
      tmp=$CANDLEHOME/tmp/CandleAgentTmp1.$$
      rm -f $tmp

      # Here we build our installed agent list @09

      # build a list of k*env files that apply to this platform
      # check for no k*env files (no agents)
      grep "BINARCH|${cArch%%[0-9]*}" \
         $CANDLEHOME/config/.ConfigData/*env > /dev/null 2>&1
      #$NLS-E$ "No agents in this CANDLEHOME"
	  [ $? -gt 0 ] && Err_report fail "`nls_replace 'KCI0254E'`"

      # we have agents!
      grep -l "BINARCH|${cArch%%[0-9]*}" \
         $CANDLEHOME/config/.ConfigData/*env | grep -v kms | grep -v kcj | grep -v kcq | grep -v kiw | grep -v kkf >> $tmp

#     Agents installed on the same platform, but at an unsupported OS level
#     relative to the running system will not be processed.
#     (ie, installed/configured on aix433 but we are running on aix43 ,
#     for which there may be no agent binaries).
      
      agents=""
      OS=${cArch%%[0-9]*}
      registry="$CANDLEHOME/registry"
      typeset -i min cur
      while read product
      do
	 # get the agent product code
         agent=${product%%env}
         agent=${agent#*.ConfigData/k}

         installed="no"

	 # installed if we find a ver file for this prod/architecture
         if [ -f $registry/${agent}${cArch}.ver ]
         then
           installed="yes"
         else
	   # installed if we find the architecture as a runArch in a ver file
           grep "runArch = $cArch$" $registry/${agent}${OS}*.ver > /dev/null 2>&1
           if [ $? -eq 0 ]
           then
		     #$NLS-Q$
             installed="yes"
           else
	     # now we look for runArch=open in the ver files
             verfile=$(grep -l "runArch = open" $registry/${agent}${OS}*.ver 2> /dev/null)
             if [ $? -eq 0 ]
             then

	       # if we found "open", we look in that ver file for the first
	       # runArch (the minimum architecture) and the product is installed
	       # if 1) the minArch is "open" or 2) the minArch is lower than the
	       # current architecture.

               minArch=$(grep -h runArch $verfile|cut -d" " -f 3|head -1)
               if [ $minArch = "open" ]
               then
			     #$NLS-Q$
                 installed="yes"
               else
		 # check the OS version numbers.  Convert 2 digit to 3 digits.
                 min=${minArch##*[a-z]}
                 cur=${cArch##*[a-z]}
		 [ $min -lt 100 ] && min=$min*10
		 [ $cur -lt 100 ] && cur=$cur*10
                 [ $min -lt $cur ] && installed="yes"
               fi
             fi
           fi
         fi
		 #$NLS-Q$
         [ "$installed" = "no" ] && continue

         agents=$agents${agent}" "

      done < $tmp 

      #$NLS-E$ "Processing all configured agents: $agents"
	  nls_replace 'KCI0255I' $agents
      rm -f $tmp
      if [ -z "$agents" ]
      then
	 #$NLS-E$ "No configured agents in this CANDLEHOME"
	 Err_report fail "`nls_replace 'KCI0256E'`"
      fi

#  Otherwise, for user supplied list of multiple products, strip any commas 
   else
      agents=$(print $product | tr ',' ' ')
   fi

#  We now have a list of agents to process, so we invoke CandleAgent script
#  recursively for each agent.  

   let agent_ct=0
   let agent_fail=0
   let operation_already_done=0
   [ -n "$SAFE_MODE" ] && SAFE_MODE="-s"
   for product in $agents
   do
      #$NLS-E$ "$product is an invalid product code"
	  [ ${#product} -gt 2 ] && Err_report fail "`nls_replace 'KCI0257E' $product`"
      #$NLS-E$ "Multi-agent $action: $product"
      if [ "$action" = "start" ]
      then
         nls_replace 'KCI0258I' $product
      else
         nls_replace 'KCI1206I' $product
      fi
      $CANDLEHOME/bin/CandleAgent         \
		${LOGOPT:+"-l"}           \
		${NOPIDCHECKOPT:+"-n"}    \
		-h $CANDLEHOME            \
		$SAFE_MODE                \
		${OOPTION:+"-o"} $OOPTION \
		$CONFIGOPT                \
		$FORCEOPT                 \
		$MULTIOPT                 \
		$action $product
      lastcc=$?
      if [ $lastcc -ne 0 ]
      then
    	 if [ $lastcc -eq 2 ]
	 then
	 let operation_already_done=operation_already_done+1
	 else
	 let agent_fail=agent_fail+1
	 fi
      fi
      let agent_ct=agent_ct+1
   done
   if [ agent_fail -gt 0 ]
   then
      #$NLS-E$ "Multi-agent $action failed for $agent_fail of $agent_ct agents"
      if [ "$action" = "start" ]
      then
         Err_report warn \
         "`nls_replace 'KCI0259I' $agent_fail $agent_ct`"
      else 
         Err_report warn \
         "`nls_replace 'KCI1207I' $agent_fail $agent_ct`"
      fi   
   fi
   if [ operation_already_done -gt 0 ]
   then
     
     if [ "$action" = "start" ]
     then     
        #$NLS-E$ "$operation_already_done agents that has already been started."
        Err_report warn \
		"`nls_replace 'KCI1202I' $operation_already_done`"
     fi
     
     if [ "$action" = "stop" ]
     then     
        #$NLS-E$ $operation_already_done agents that has already been stopped.
        Err_report warn \
		"`nls_replace 'KCI1203I' $operation_already_done`"
     fi
     
   fi
   
   #$NLS-E$ "Multi-agent $action completed"
   if [ "$action" = "start" ]
   then      
      nls_replace 'KCI0260I'
   else
      nls_replace 'KCI1208I'
   fi    
   exit 0
fi

# End of multi-agent processing

setBinLibArchs $cArch $product

# We regenerate the TZ= variable each time because of platform differences  @17
envConfig=$CANDLEHOME/config/env.config
envTmp=$envConfig.tmp
if [ -f $envConfig ]
then
  cat $envConfig|sed "/TZ=/d" > $envTmp
  # Feature 15381
  #mv $envTmp $envConfig
  cp $envTmp $envConfig
  rm -f $envTmp
  # Feature 15381 END
fi

# Store the timezone.  Check for TIMEZONE and ZONE since they're used in 
# different Linux distributions. @18
[ -n "$TZ" ] && print "TZ='$TZ'" >> $envConfig
[[ -z "$TZ" && -n "$TIMEZONE" ]] && print "TZ='$TIMEZONE'" >> $envConfig
[[ -z "$TZ" && -n "$ZONE" ]] && print "TZ='$ZONE'" >> $envConfig

if [ "$product" = "ux" -o "$product" = "ul" ]
then
   cd $CANDLEHOME/$binArch/$product/bin
fi

umask 022                               # tighten permissions in general
[ "$product" = "ud" ] && umask 000	# ud/um makes files needing r/w access

oParms=""
pParms=""
if [ -n "$OOPTION" ] 
then
  OOPTION=$(print $OOPTION | tr ' ' ',')
  oParms="-o $OOPTION"
fi

if [ -n "$POPTION" ] 
then
  POPTION=$(print $POPTION | tr ' ' ',')
  pParms="-p $POPTION"
fi

# Update agent status in RunInfo before starting
$CANDLEHOME/bin/cinfo -R > /dev/null 2>&1

# ---> set to "print" for testing or "" for run
print=""

if [[ "$product" = "or" || "$product" = "oy" ]]
then
  # defect 15461, translate the -o option to the -s option for products or and oy
  if [ -n "$OOPTION" ] 
  then
     $print $CANDLEHOME/bin/CandleDBAgent -s $OOPTION $action $product
  else
     $print $CANDLEHOME/bin/CandleDBAgent $action $product
  fi
else
  [ "$action" = "stop" ] && [ "$product" = "kf" ] && [ -n "$CDNAME" ] && [ -z "$DEPLOY_MODE" ] && [ -z "$FORCEOPT" ] && FORCEOPT="-f"	
  $print $JREEXE -classpath $CLASSPATH $SAFE_MODE -DGlobalDbgLevel="$TRACE_LEVEL" -DInstallRASConfig="$CANDLEHOME/config/ITMConfigRAS.properties" ITMinstall.CandleAgent -ch $CANDLEHOME $BATCHOPT $LOGOPT $NOPIDCHECKOPT $CONFIGOPT $MULTIOPT $FORCEOPT $oParms $pParms -a $cArch $action $product
fi
