#!/bin/ksh
######################################################################
#                                                                    #
#             (C) COPYRIGHT Candle Corporation 1996                  #
#                      All Rights Reserved                           #
#                                                                    #
#        Licensed Materials - Property of Candle Corporation         #
#         Duplication or disclosure prohibited without the           #
#        expressed written consent of the Candle Corporation.        #
#                                                                    #
#                                                                    #
######################################################################
# @(#) $RCSfile: CandleDBAgent,v $ $Revision: 1.11 $ $Date: 1998/12/11 15:45:41 $
#
#
# This script is used to start DB agents and collectors on a given machine.
# Calling sequence is:
#
#  CandleDBAgent [-d table,...|all|ALL] [ -h CANDLEHOME] [-s server,...] action pc ...
#
#  -h directory overrides CANDLEHOME
#
#  -d = Enables debug tracing for the listed items, which can be
#       Table   -  Turns on KBB_RAS1 tracing for table  (korxxxx, kraxxxx)
#                  Table names are case-insensitive, ksh wildcards OK (not regexp)
#       debug   -  Turns on collector and agent internal tracing via -dddd
#       d's     -  Fine tune internal tracing level: -d, -dd, -ddd, -dddd, -ddddd
#                  (debug or ddd's also change col.out to wrap after 100000 lines,
#                   and keep col.ou[1-9]   )
#       all     -  *,debug
#       ALL     -  ddddd + all possible agent KBB_RAS1: (UNIT:K ALL)
#       any form of tracing also turns on KBB_RAS1 (UNIT:KDD ALL)
#
#       Note, -d table does not select collector tracing for the table,
#       but -d debug automatically traces all collector cursors.
#       Selective collector tracing is defined via ko?trac.ctl, and
#       enabled at collector startup or via CandleDBAgent trace.
#
#  -v = Version
#
#  action = start, stop, trace, status, csh, ksh, sh
#           csh, ksh, sh set up all environs, then enter sub-shell
#           The default action is start.
#
#  pc = or, oy, ox
#
#  servers - Database servers to be monitored. Server list must parse as a
#            single shell option, (quote or comma-delimit).  Wildcards OK.
#
#

#trap 'print "  (press enter)"; read' EXIT


Use_report() {
 print -u2 "$PROGNAME [ -d table | all ] [ -h install_dir ] [-s server, ...] action pc "
 exit 1
}


Err_report() {
   typeset what=$1
   shift
   case $what in
	 #$NLS-E$ "$PROGNAME warning: $*,continuing ..."
     (warn) print -u2 "$PROGNAME `nls_replace 'KCI0350I'`: $*,`nls_replace 'KCI0351I'` ..."
            sleep 1
	#$NLS-E$ "$PROGNAME failure: $*."		
   ;;(fail) print -u2 "$PROGNAME `nls_replace 'KCI0352I'`: $*."
            exit 2
   ;;(info) print -u2 "$PROGNAME        : $*."
   esac
}


ProdDesc  () {
  sed  "/^$1|/!d; s/^.*- //" $CANDLEHOME/registry/proddsc.tbl
}

# Delim d args... converts args into $d-delimited list
# args might contain wildcards and may use commas, blanks, tabs,
# as delimiters.
Delim() {
  typeset IFS=$1\ ,:
  shift
  print "$*"
}
######################################################################
#                              Main PROGRAM                          #
######################################################################
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
ACTIONS="status start stop trace sh ksh csh"                         # exceptable actions
if [[ -z "$ITMCMD" ]]
then
    PROGNAME=$(basename $0)
else
    PROGNAME="$ITMCMD"
fi


while getopts ":d:h:s:" OPT
do case $OPT in
      (h) CANDLEHOME=$OPTARG
   ;; (d) DEBUG=-d\ $OPTARG
   ;; (s) SRVLIST=$OPTARG
   ;; (?) Use_report
   esac
done
shift OPTIND-1

# Locate CANDLEHOME
  [[ -d ${CANDLEHOME:=$(x=$(whence $0); cd ${x%/*}/..; pwd)} ]] ||  
     #$NLS-E$ "$CANDLEHOME not a directory"
	 Err_report fail "`nls_replace 'KCI0353E' $CANDLEHOME`"
  export CANDLEHOME

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

# Parse action and product parms
#  if (( $# ))            # At least one parm
#  then [[ ${#1} -eq 2 ]] && Action=start || Action=$1 shift
#       export PROD=$1
#  else Use_report
#  fi

if [[ $# -ne 2 ]]
then 
	Use_report
else
	Action=$1
    PROD=$2
fi

if [[ "$PROD" = "ud" ]]
then
	 #$NLS-E$ "$PROD not a valid product code, use 'itmcmd agent' for $PROD"
     Err_report fail "`nls_replace 'KCI0355E' $PROD 'itmcmd agent'`"
fi
if [[ "$PROD" != "or" ]] && [[ "$PROD" != "oy" ]]
then
     #$NLS-E$ "$PROD not a valid product code, valid product codes are 'or' and 'oy'"
     Err_report fail "`nls_replace 'KCI0356E' $PROD 'or' 'oy'`"
fi

###################################################################
#                Set common environment variables                  #
###################################################################

set -a          # auto-export the following:
  CANDLELOG=$CANDLEHOME/logs
  CANDLETBL=$CANDLEHOME/tables
  CANDLECFG=$CANDLEHOME/config
  CANDLEMISC=$CANDLEHOME/misc
  CANDLETMP=$CANDLEHOME/tmp
set +a
unset CDPATH

###################################################################
# Set  CANDLEARCH HOST USER PROD RUNFILE
###################################################################

# source dynarch.shl in a subshell so it does not modify my environment
cArch=`. $CANDLEHOME/bin/dynarch.shl $CANDLEHOME/registry/archdsc.tbl ; echo $cArch`

# temp compromise: assume all dd products runarch the same arch
#$NLS-E$ no registry directory
cd $CANDLEHOME/registry || Err_report fail "`nls_replace 'KCI0357E'`"

grep -l "runArch" ${PROD}*.ver 2>/dev/null 1>/dev/null
if [ $? -ne 0 ]
then
   #$NLS-E$ Database monitoring product "'""$PROD""'" not installed
   Err_report fail `nls_replace 'KCI0358E' \\'$PROD\\'`
   
fi

  grep -l "^runArch *= *$cArch" ${PROD}*.ver | IFS=. read pack x 
  rc1=$? 
  grep -l "^runArch *= *open" ${PROD}*.ver | IFS=. read pack x 
  rc2=$? 
  if [ $rc1 -ne 0 ] && [ $rc2 -ne 0 ]
  then
     #$NLS-E$ unsupported runtime environment: $cArch
     Err_report fail "`nls_replace 'KCI0359E' $cArch`"
  fi

#  grep -l "^runArch *= *$cArch" ${PROD:-o[ryx]}*.ver | IFS=. read pack x ||
#      Err_report fail unsupported runtime environment: $cArch

# Defect 11188
# The line below is not returning the correct architecture that the
# product team is expecting.
#  CANDLEARCH=${pack#??}
# Hence return the correct architecture as specified by the name of
# the ver file.  e.g. oysol283.ver should result in a CANDLEARCH
# of sol283, even if this is running on a sol293 machine.

if [ $rc1 -eq 0 ]
then
   verFile=$(grep -l "^runArch *= *$cArch" ${PROD}*.ver)
else
   verFile=$(grep -l "^runArch *= *open" ${PROD}*.ver)
fi

CANDLEARCH=${verFile%%.ver}
CANDLEARCH=${CANDLEARCH##$PROD}
# Defect 11188 - End

cd $OLDPWD

id | IFS="()" read x USER x

archdir=$CANDLEHOME/$CANDLEARCH
#$NLS-E$ Directory $archdir not found
[[ -d $archdir ]] || Err_report fail "`nls_replace 'KCI0360E' $archdir`"

unset cArch pack  x archdir
export CANDLEARCH HOST=$(uname -n) USER PROD RUNFILE=$HOST\_$PROD.run

###################################################################
# Checks
###################################################################

cd $CANDLECFG

  case $Action in
       (status | trace )           Lock=yes
  ;;   (sh | csh | ksh  )          Lock=any
  ;;   (p | sto* ) Action=stop     Lock=yes
  ;;   (s | st*  ) Action=start    Lock=no
	   #$NLS-E$ "unknown action $Action"	
  ;;   (*) Err_report fail "`nls_replace 'KCI0361E' $Action`"
  esac

  # Purge RUNFILE of stale locks
  RUNFILE=$HOST\_$PROD.run
  if   [[ -f $RUNFILE ]]
  #$NLS-E$ Require write access to $CANDLECFG/$RUNFILE
  then [[ -w $RUNFILE ]] || Err_report fail "`nls_replace 'KCI0362E' $CANDLECFG/$RUNFILE`"
       while IFS== read server pid
       do    kill -0 $pid 2>/dev/null && print $server=$pid ||
				#$NLS-E$ Removing stale $RUNFILE entry: $server=$pid
                Err_report info "`nls_replace 'KCI0363I' $RUNFILE $server=$pid`"
       done <$RUNFILE >.$RUNFILE
       mv -f .$RUNFILE $RUNFILE
  fi

 # Set environment variables using YUMI config files
 # Source the general product cfg files, if any, from most general to most specific


  Config_File=$CANDLECFG/$PROD.config

  [[ -f $Config_File ]] ||
		#$NLS-E$ config file $Config_File not found, run CandleConfig -A
       Err_report fail "`nls_replace 'KCI0364E' $Config_File 'CandleConfig -A'`"

   for this in dd $PROD $HOST\_dd $HOST\_$PROD
   do  config=$this.config
       [[ -r $config ]] && . ./$config
   done

   export PATH=$bindir:$PATH
   
  #$NLS-E$ "kddexec.sh not executable or missing" 
  whence kddexec.sh >/dev/null || Err_report fail "`nls_replace 'KCI0365E' kddexec.sh`"

# Expand the server list.  Doing this now so lock-checker can report individual servers
  SRVLIST=$(Delim '|' "${SRVLIST:-*}" )   # No servers = all servers (no expand now)

   servers=$(
      for server in $(eval 'ls $HOST\_$PROD\_$SRVLIST.cfg')
      do  server=${server#$HOST\_$PROD\_}
          print   ${server%.cfg}
      done)

	#$NLS-E$ '\nNo servers configured.  Perhaps you have not run CandleDBConfig'
   [[ -z $servers ]] && Err_report fail "\n `nls_replace 'KCI0366E' CandleDBConfig`"

	#$NLS-E$ "considering servers: $(print $servers)"  
   Err_report info "`nls_replace 'KCI0367I'` $(print $servers)"

   #$NLS-E$ "cannot $Action $server, running=$running"
   servers=$(
     for server in $servers
     do  grep -sl "^$server=" $RUNFILE >/dev/null && running=yes || running=no
         if   [[ $Lock.$running = @(no.no|yes.yes|any.*) ]]
         then print $server
		 else Err_report warn "`nls_replace 'KCI0368I'` $Action $server, `nls_replace 'KCI0369I'`=$running"
         fi
     done)

	#$NLS-E$ "nothing to do for $(ProdDesc $PROD) ($PROD)" 
   if [[ -z $servers ]]
   then Err_report warn "`nls_replace 'KCI0370I'` $(ProdDesc $PROD) ($PROD)"
   fi

kddexec.sh $DEBUG $Action $servers  # not exec so EXIT trap fires
