#!/bin/sh
#
# - script for automatic actions on alerts defined in contrib/actions
# - remote execution is needed for actions on other then receiving site
# - think on needed permissions for commands etc/actions, sudo package
#   could be used to get the
#
# contributed by Wulf Dietrich w_dietrich@hotmail.com 14.04.2000
#
# usage: 
# agent:alert:0-24:1:0:enabled:RUN=$BCNUHOME/contrib/bcnuaction:

#. /usr/local/bcnu/etc/bcnuenv
. $BCNUHOME/agent/agent_head

ACTIONS=$BCNUHOME/contrib/actions
ACTIONPATTERNS=$BCNUHOME/data/files/action_patterns
BCNUACTION=$BCNUHOME/data/files/bcnuaction

if [ -s $ACTIONS ] ; then
  cat - | \
  grep " [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9].[0-9][0-9].[0-9][0-9] " | \
  while read HOST AGENT DATE TIME MSG ; do

    # get the attached file
    DATALOG=`date +%Y%m%d`.log

    ATT_FILE=`$AWK -v HOST=$HOST -v AGENT=$AGENT -v DATETIME="$DATE $TIME"  'BEGIN {FS=":"} {
  if ( $3 == HOST && $5 == AGENT && $6 == DATETIME && $11 != "" ) {
    print $11;
  }
}' $BCNUHOME/data/$DATALOG`

    if [ -n "$ATT_FILE" -a -s "$ATT_FILE" -a -r "$ATT_FILE" ] ; then

      # process the action file
      grep "^\[$AGENT - .*\]" $ACTIONS | sed -e "s/\[$AGENT - //g" -e "s/\]//g" >$ACTIONPATTERNS

      if [ -s $ACTIONPATTERNS ] ; then
        # found configured actions for this agent
        while read PATTERN ; do
          if grep "$PATTERN" $ATT_FILE >/dev/null ; then
            # found pattern for this agent in attachment
            sed -ne "\+^\[$AGENT - $PATTERN]+,\+^\[+p" $ACTIONS | sed -ne "/^[^\[#]/p" >$BCNUACTION
            SENDING_HOST=$HOST
            RECEIVING_HOST=$BCNUHOST
            . $BCNUACTION
            if [ $? -ne 0 ] ; then
              STAT=error
            else
              STAT=ok
            fi
            # some logging 
            echo "$STAT - action on alert at `date`: ($HOST:$AGENT:$DATE $TIME:$MSG:$ATT_FILE), pattern is: \"$PATTERN\", command is:"
            echo "--"
            sed -e "s/\$SENDING_HOST/$SENDING_HOST/g" \
                -e "s/\$RECEIVING_HOST/$RECEIVING_HOST/g" \
                -e "s/\$OTHER_HOST/$OTHER_HOST/g" $BCNUACTION
            echo "--"
          fi
        done < $ACTIONPATTERNS
      fi
    fi
  done
fi  
