#!/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.   #
#                                                               #
#################################################################

# @(#) CandleHistory - provides a table rolloff function and a
# @(#) facility for scheduling rolloff via cron.

# @03 06/21/04 LCL Fix instance processing fails for WE; 1-52424165
# @02 12/24/03 LCL Fix -A option to honor -i instances; 1-41224501
# @01 06/27/03 BRC Add -i option to process specific instances; SR1-32053701.

# General definitions.

alias printN="print -n"  # No LF at end of lines.
alias int="typeset -i"   # ksh default, but cust may have deleted.
unalias rm mv

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

Use_report() 
{
  print "\n$PROGNAME -h"  # Help. 
  print "$PROGNAME [ -h install_dir ] -C [ -L nnn[Kb|Mb] ] [ -t masks*,etc ] [ -D delim ]"
  print "    [ -H|+H ] [ -N n ] [ -i instance|-p tems_name ] prod_code"
  print "$PROGNAME -A?"  # List schedule.
  print "$PROGNAME [ -h install_dir ] -A perday|0 [ -W days ] [ -L nnn[Kb|Mb] ] [ -t masks*,etc ]"
  print "    [ -D delim ] [ -H|+H ] [ -N n ] [ -i instance|-p tems_name ] prod_code"

  print "\nDetailed help [ y/n; n is default ]? \c"
  read
  case $REPLY in
    y*|Y*) :
           ;;
    *) exit 2
       ;;
  esac

tmpname1=`print $LANG | sed 's/^\(.....\).*/\1/'` 
more < $TEXTDOMAINDIR/$tmpname1/CandleHistory_text_$tmpname1.txt
}

# Roll tablemasks ...
# Globals:   Cxhead=null if headings suppressed;  Cgroup=1 for group headings.
#            Cdelim=output delimiter;  Cgenlim=generation limit.
#            ClimKB=size limit, if any in KB.

Roll() 
{
  # Set local variables.

	typeset addr binPath cfgFile hostName lastDir table tables
  typeset -i numEle=0

  # Ensure that the rolloff program exists.

  binPath=$CANDLEHOME/$libArch/bin
  #$NLS-E$ "cannot find \"$binPath/krarloff\""
  [ -x "$binPath/krarloff" ] || Err_report fail "`nls_replace 'KCI0450E' \\"$binPath/krarloff\\"`"

  # Determine the name of the configuration file.
  
  if [ -z "$cmsName" ]  # Agent rolloff.
  then
    cfgFile=$CANDLEHOME/config/$prodCode.config  # Default.
    [ -n "$instance" ] && cfgFile=$CANDLEHOME/config/${prodCode}_${instance}.config
    
    # Instances of some agents use the same .config file.
    [ "$prodCode" = "mq" ] && cfgFile=$CANDLEHOME/config/$prodCode.config
    [ "$prodCode" = "we" ] && cfgFile=$CANDLEHOME/config/$prodCode.config
    [ "$prodCode" = "or" ] && cfgFile=$CANDLEHOME/config/$prodCode.config
    [ "$prodCode" = "oy" ] && cfgFile=$CANDLEHOME/config/$prodCode.config
      
	#$NLS-E$ "cannot read \"$cfgFile\""  
    [ -r $cfgFile ] || Err_report fail "`nls_replace 'KCI0451E' \\"$cfgFile\\"`"
  else  # CMS rolloff
    hostName=$(print $(hostname) | cut -d"." -f1)
    cfgFile=$CANDLEHOME/config/${hostName}_ms_$cmsName.config
    if [ ! -r $cfgFile ]  # The hostName and interface names are different.
    then
      # addr is the IP address.
      addr=$(grep KDCB0_HOSTNAME $CANDLEHOME/tables/$cmsName/glb_site.txt 2> /dev/null | cut -d"=" -f2 | sed s/\'//g | sed s/\"//g)
	  #$NLS-E$ "could not determine the value for KDCB0_HOSTNAME"
      [ -n "$addr" ] || Err_report fail "`nls_replace 'KCI0452E' KDCB0_HOSTNAME`"
  
      # Look for addr in a cms config file.
  
      set -A cfgNames $(grep -l $addr $CANDLEHOME/config/*_ms_$cmsName.config 2> /dev/null)
      numEle=${#cfgNames[*]}
      if [ numEle -gt 0 ]
      then
        cfgFile=${cfgNames[0]}  # Use the first one.
      else
	    #$NLS-E$ "could not find a configuration file for \"$cmsName\""
        Err_report fail "`nls_replace 'KCI0453E' \\"$cmsName\\"`"
      fi
    fi
	#$NLS-E$ "cannot read \"$cfgFile\""
    [ -r $cfgFile ] || Err_report fail "`nls_replace 'KCI0454E' \\"$cfgFile\\"`"
  fi

  # Determine the path to the attribute files.

  ATTRLIB=$(grep ATTRLIB $cfgFile | cut -d"=" -f2 2> /dev/null)
  #$NLS-E$ "could not determine ATTRLIB"
  [ -n "$ATTRLIB" ] || Err_report fail "`nls_replace 'KCI0455E' ATTRLIB`"
  ATTRLIB=${ATTRLIB#\'}  # Remove the single quotes.  Refer to the .config file.
  ATTRLIB=${ATTRLIB%\'}
  #$NLS-E$ "directory \"$ATTRLIB\" does not exist"
  [ -d "$ATTRLIB" ] || Err_report fail "`nls_replace 'KCI0456E' \\"$ATTRLIB\\"`"
  export ATTRLIB

  # Determine the path to the tables.
  
  if [ -n "$cmsName" ]  # Process date collected at the CMS.
  then
    tblPath=$CANDLEHOME/tables/$cmsName
  else  # Process data collected at the agent.
    # IZ09571 - accepted this var either at the beginning of the line or after export
    tblPath=$(grep "^CTIRA_HIST_DIR" $cfgFile | cut -d"=" -f2 2> /dev/null)
    if [ -z "$tblPath" ] 
    then
    	tblPath=$(grep "^export CTIRA_HIST_DIR" $cfgFile | cut -d"=" -f2 2> /dev/null)
    fi

	#$NLS-E$ "could not determine CTIRA_HIST_DIR"
    [ -n "$tblPath" ] || Err_report fail "`nls_replace 'KCI0457E' CTIRA_HIST_DIR`"
    tblPath=${tblPath#\'}  # Remove the single quotes.  Refer to the .config file.
    tblPath=${tblPath%\'}
    
    # For multiple instance agents that use a single config file, the CTIRA_HIST_DIR might not be
    # pointing to the instance we're interested in, so for those, we modify the directory ourselves
    # using the instance name specified in itmcmd history command.  Example agent types are mq and we.

    # Set the table path specific to an instance.  The table path at this point could be either
    # <candlehome>/<bin_arch>/mq/hist or <candlehome>/<bin_arch>/mq/hist/<prior_instance>
    
    # instance was specified
    if [ -n "$instance" ] 
    then
      # the agent uses a single config file for all instances.
      if [[ $prodCode = "mq" || $prodCode = "we" || $prodCode = "or" || $prodCode = "oy" ]]
      then
	# get the ending part of the historical directory
        lastDir=${tblPath##*/}
	# add "/<instance>" 
        [ "$lastDir" = "hist" ] && tblPath=${tblPath}/${instance} || tblPath=${tblPath%/*}/${instance}
      fi
    fi
  fi

  #$NLS-E$ "directory \"$tblPath\" does not exist"
  [ -d $tblPath ] || Err_report fail "`nls_replace 'KCI0458E' \\"$tblPath\\"`"
  #$NLS-E$ "cannot read directory \"$tblPath\""
  [ -r $tblPath ] || Err_report fail "`nls_replace 'KCI0459E' \\"$tblPath\\"`"
  #$NLS-E$ "cannot write to directory \"$tblPath\""
  [ -w $tblPath ] || Err_report fail "`nls_replace 'KCI0460E' \\"$tblPath\\"`"

  #print ... lastDir = $lastDir
  #print ... cfgFile = $cfgFile
  #print ... tblPath = $tblPath
  
  cd $tblPath > /dev/null 2>&1
  #$NLS-E$ "could not change to directory \"$tblPath\""
  [ $? -eq 0 ] || Err_report fail "`nls_replace 'KCI0461E' \\"$tblPath\\"`"

  tables=$(set +f   # next line expands wildcards.
           for table in $*
           do  [[ -f $table && -f $table.hdr ]] && print $table
           done | sort -u)

  #$NLS-E$ "tables: <none matched>"		   
  [ -n "$tables" ] || Err_report info "`nls_replace 'KCI0462I'`"

  if   [[ -n $tables && -n $ClimKB ]]
  then 
    tables=$(find $tables -size +$((ClimKB*1024))c -print | awk '{printf $1" "}')  # awk replaces printN
    Err_report info $ClimKB Kb+ ${tables:-"<none>"}
  fi

  [[ -z $tables ]] && return

  set -A heads '' -h "-h -g"   # three possible heading options
  opts="${heads[Chead]} ${Cdelim:+-d \"$Cdelim\"}"

  for table in $tables
  do  roll=$table.0.pending
   #  Grouch: must eval krarloff, else the conditional -d " " is misread
      if eval $binPath/krarloff $opts -m $table.hdr -r $table.old -o $roll $table
      then  # cycle/delete output generations
            list=$(ls $table.+([0-9]) 2>&-) &&                # only $table.n
              for tabout in $(print "$list" | sort -rnt. +1 )  # reverse num order
              do  if   (( (n=${tabout##*.}) < Cgenlim ))
                  then mv $tabout $table.$((n+1))
                  else rm $tabout
                  fi
              done
			#$NLS-E$ "history gen cycle error"  
            mv $roll $table.0 && rm $table.old ||			
            Err_report warn "`nls_replace 'KCI0463I'`"
			#$NLS-E$ "history rolloff for $table failed"
      else  Err_report warn "`nls_replace 'KCI0464I' $table`"
      fi
  done

  #$NLS-E$ "history rolloff complete"
  Err_report info "`nls_replace 'KCI0465I'`"
}

# Schedule rolloffs.
# Schedule cron jobs to Roll tablemasks...
# Globals:   Chours=hours between runs, 0=cancel, ?=list only.

Cron()
{
  typeset tables command me=$CANDLEHOME/bin/CandleHistory
  typeset hOpt chName
  set -f    # no wildcarding this function

  # Handle list-only case separately.

  if [[ $Chours = \? ]]
  then 
    #$NLS-E$ "crontab entry list"
    Err_report info "`nls_replace 'KCI0466I'`"
#    (crontab -l 2>&- || Err_report info "$LOGNAME has no crontab file") |
    crontab -l 2> /dev/null | grep "$me" > /dev/null 2>&1
	#$NLS-E$ "no relevant crontab entries"
    [ $? -eq 0 ] || { Err_report info "`nls_replace 'KCI0467I'`"; exit 0; }
    crontab -l | 
      while read entry
      do  
        set $entry
        [[ "$me" = "$6" && "$9" = "-Ct" ]] && print "  $*"
      done
    return
  fi

  tables=$*
  { crontab -l 2>&- |  # pipe to...
    while read min hour date mon day command hOpt chName Ct etc
    do 
      if [ -n "$etc" ]
      then
        set -A parms $(print $etc)
        nf=${#parms[*]}     # Number of elements in parms.
        pc=${parms[$nf-1]}  # The last arg in etc is the product code.
	inst=""
	if [[ -n "$(print $etc | grep " -i ")" ]] # See if instance was specified
	then
	  inst=${etc##*-i }   # Look for instance name
	  inst=${inst%% *}
        fi
      fi

      if [[ $me = $command && $Ct = -Ct && $pc = $prodCode && "$inst" = "$instance" ]]  # mine?
      then  # Remove from this existing crontab entry any tables in my scope
        eval set $etc      # separate quoted table list from other parms
        set -A cmdtabs $(IFS="$IFS/,:"; print $1 )
        shift
        etc=$*     # all other parms
        int i=${#cmdtabs[*]}
        until (( 0>(i-=1) ))
        do
          for table in $tables
          do [[ ${cmdtabs[i]} = $table ]] && unset cmdtabs[i] &&
             Cdate=$date Cmon=$mon Cday=$day
          done
        done
        # Write residual of existing entry, if any.  Just delete the entry.
#        (( ${#cmdtabs[*]} )) &&
#          print "$min $hour $date $mon $day $command -Ct '${cmdtabs[*]}' $etc"
      else # entry not mine, write back as is
        print "$min $hour $date $mon $day $command $hOpt $chName $Ct $cmdtabs $etc"
      fi
    done

  # Write new entries, if any
    if  ((Chours))
    then int i=0
         typeset -Z2 HH   # make hours pretty
         set -A heads -- -H '' +H    # three possible heading options
         # quote tables so wildcard not expanded by shell when job starts
croncmd="$me -h $CANDLEHOME -Ct '$tables' -N$Cgenlim ${Cdelim:+-D\'$Cdelim\' }${ClimKB:+-L$ClimKB }${heads[Chead]} $iOpt $pOpt $prodCode"
         while ((i<24))
         do    HH=$i
               print "0 $HH ${Cdate:-*} ${Cmon:-*} ${Cday:-1-6} $croncmd"
               (( i+=Chours ))
         done
    fi
  #$NLS-E$ "crontab update: $errmsg"	
  } | errmsg=$(crontab 2>&1) || Err_report fail "`nls_replace 'KCI0468E' $errmsg`"

  Chours=? Cron    # List them
}


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

typeset cmsName iOpt instance pOpt prodCode specCH thisDir
instance=""

# Non-null defaults.

int Cgenlim=9 Chead=1

while getopts :h:t:A:CD:L:HN:W:p:i: opt
do 
  case $opt in
    h) CANDLEHOME=$OPTARG
       CANDLEHOME=$(eval print $CANDLEHOME)  # Process ~ if it was entered.
       specCH=true
       ;;
    t) # convert to uppercase blank-delim (no wilcard expand yet)
       typeset -u Tabmask=$(set -f; IFS=$IFS/,:; print $OPTARG)
       ;; 
    A) [ $Action ] && Use_report
       Action=rolltab
       if [[ $OPTARG = 0 || $OPTARG = \? ]]
       then  Chours=$OPTARG
       else  
         int Chours
         let "Chours=24/OPTARG+(OPTARG>24)" 2>&- ||       #  Convert to hours
		 #$NLS-E$ "bad runs per day:  $OPTARG"
         Err_report fail "`nls_replace 'KCI0469E' $OPTARG`"
       fi 
       ;; 
    C) [ $Action ] && Use_report
       Action=rolloff
       ;; 
    D) Cdelim=$OPTARG
       ;; 
    L) int ClimKB
       # ClimKB=$OPTARG w/o trailing kb/mb.  Require valid non-neg number
       let "1 + ( ClimKB=${OPTARG%[kmKM]*} )" 2>&- ||
	     #$NLS-E$ "bad conversion limit:  $OPTARG"
         Err_report fail "`nls_replace 'KCI0470E' $OPTARG`"
       [[ $OPTARG = *[mM]* ]] && let "ClimKB *= 1024"
       ;; 
    N) let "1+(Cgenlim=OPTARG)" 2>&- ||          # Cgenlim=0 is OK.
	   #$NLS-E$ "bad generation limit:  $OPTARG"
       Err_report fail "`nls_replace 'KCI0471E' $OPTARG`"
       ;;
    H) Chead=0
       ;;
    +H) Chead=2
        ;; 
    W) Cday=$OPTARG
       ;; 
    p) cmsName=$OPTARG
       pOpt="-p $cmsName"
       ;;
    i) instance=$OPTARG
       iOpt="-i $instance"
       ;;
    *) Use_report
       exit 2
  esac
done
shift OPTIND-1
prodCode=$1

[ -n "$Action" ] || Use_report

# If it wasn't specified via -h, try to determine the name of CANDLEHOME.

if [ -z "$specCH" ]
then
  thisDir=$(basename $(pwd))
  [ "$thisDir" = "bin" ] && CANDLEHOME=$(dirname $(pwd))
fi

#$NLS-E$ "CANDLEHOME directory not set or not specified"
[ -n "$CANDLEHOME" ] || Err_report fail "`nls_replace 'KCI0472E' CANDLEHOME`"
#$NLS-E$ "\"$CANDLEHOME\" is not a directory"
[ -d "$CANDLEHOME" ] || Err_report fail "`nls_replace 'KCI0473E' \\"$CANDLEHOME\\"`"

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

cd $CANDLEHOME > /dev/null 2>&1
#$NLS-E$ "could not cd to \"$CANDLEHOME\" directory"
[ $? -eq 0 ] || Err_report fail "`nls_replace 'KCI0475E' cd \\"$CANDLEHOME\\"`"

# Ensure the proper use of -i.

#$NLS-E$ "the -i and -p options cannot be used together"
[[ -n $iOpt && -n $pOpt ]] && Err_report fail "`nls_replace 'KCI0476E' -i -p`"
#$NLS-E$ "the -i option cannot be used with prod_code \"ms\""
[[ -n $iOpt && $prodCode = "ms" ]] && Err_report fail "`nls_replace 'KCI0477E' -i prod_code \\"ms\\"`"

# List the crontab entries.

if [[ "$Action" = "rolltab" && "$Chours" = \? ]] 
then 
  Cron
  exit 0
fi

[ -n "$prodCode" ] || Use_report

if [ -n "$cmsName" ]
then
  #$NLS-E$ "directory \"$CANDLEHOME/tables/$cmsName\" does not exist"
  [ -d $CANDLEHOME/tables/$cmsName ] || Err_report fail "`nls_replace 'KCI0478E' \\"$CANDLEHOME/tables/$cmsName\\"`"
  #$NLS-E$ "the \"-p tems_name\" option requires a prod_code of \"ms\""
  #$NLS-Q$
  [ "$prodCode" = "ms" ] || Err_report fail "`nls_replace 'KCI0479E' '\\"-p tems_name\\"' prod_code \\"ms\\"`"
fi

# Ensure that required files exist.

dynShl=$CANDLEHOME/bin/dynarch.shl
#$NLS-E$ "cannot execute \"$dynShl\""
[ -x "$dynShl" ] || Err_report fail "`nls_replace 'KCI0480E' \\"$dynShl\\"`"

regPath=$CANDLEHOME/registry
archTbl=$regPath/archdsc.tbl
#$NLS-E$ "cannot read \"$archTbl\""
[ -r "$archTbl" ] || Err_report fail "`nls_replace 'KCI0481E' \\"$archTbl\\"`"

# Determine the machine's architecture.

. $dynShl $archTbl  # dynarch.shl will determine a value for cArch.
#$NLS-E$ "could not determine the machine's architecture"
[ -n "$cArch" ] || Err_report fail "`nls_replace 'KCI0482E'`"
#$NLS-E$ "computed architecture = \"$cArch\""
Err_report info "`nls_replace 'KCI0483I' \\"$cArch\\"`"

# Determine the bin directory for the krarloff executable.  The <arch> in this directory path is the 
# libArch of the ax package prereq'd by the product.  Why, because krarloff is delivered in the ax packages.

setBinLibArchs $cArch $prodCode  # setBinLibArchs is defined in dynarch.shl, and this function will set
                                 # values for binArch and libArch. 

plat=`print ${libArch##*/} | cut -c1-2`

if [ "$plat" = "hp" ]
then
 export SHLIB_PATH=$LD_LIBRARY_PATH:$CANDLEHOME/$libArch/lib
elif [ "$plat" = "ai" ]
then
 export LIBPATH=$LD_LIBRARY_PATH:$CANDLEHOME/$libArch/lib
elif [[ "$plat" = "tv" ]] || [[ "$plat" = "ta" ]]     # IZ02405
then     # IZ02405
 export _RLD_LIB_PATH=$CANDLEHOME/$libArch/lib     # IZ02405
else
 export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$CANDLEHOME/$libArch/lib
fi

if [ "$Action" = "rolloff" ]
then 
  Roll "${Tabmask:-*}"
elif [ "$Action" = "rolltab" ]
then 
  Cron "${Tabmask:-*}"
else
  #$NLS-E$ "unknown action"
  Err_report fail "`nls_replace 'KCI0484E'`"
fi

exit 0

