#!/usr/local/bin/perl

##################################################
#
# n_status_watch
#
#      Version 1.0
#      Last revision on July 24, 1997.
#
# Author:
#
#      Patrick Ryan <pgryan@geocities.com>
#
# Usage:
#
#      n_status_watch host name count
#
# Synopsis:
#
#      n_status_watch will parse syslog entries on
#      the standard input.  It looks for NodeWatch
#      1.4 status messages from the process name on
#      host and counts the number of times a status
#      message appears.  If count doesn't match the
#      number of status messages encountered, then
#      a command is executed.
#
# Author:
#
#      Patrick Ryan <pgryan@geocities.com>
#
##################################################


##################################################
# Configurable Section

# The command to execute if the status message count
# is not the same as the count specified on the command
# line.
$cmd = "/usr/local/bin/qpage -f \"\" duty \"$ARGV[1] on $ARGV[0] may be down.\"";

#
##################################################


##################################################
# The Program

if (@ARGV != 3 || $ARGV[0] eq "" || $ARGV[1] eq "" || $ARGV[2] eq "" ||
    $ARGV[2] =~ /\D/) {
   die "Usage: $0 host name count\n";
}

$host = $ARGV[0];
$name = $ARGV[1];
$targetCount = $ARGV[2];
$count = 0;

while (<STDIN>) {

   chop();

   # A syslog line looks like
   # Mmm md hh:mm:ss host process[pid]: Message
   # or
   # Mmm md hh:mm:ss host process: Message

   if (/^\w{3} \d{2} \d\d:\d\d:\d\d $host $name\[\d+\]: (.+)/) {
      $count++ if statusMessage($1);
   } elsif (/^\w{3} \d{2} \d\d:\d\d:\d\d $host $name: (.+)/) {
      $count++ if statusMessage($1);
   }
}

if ($count != $targetCount) {
   exec($cmd) if (fork() == 0);
}

#
##################################################


##################################################
# Functions

sub statusMessage {
# If the message is a NodeWatch status message,
# then return 1, else return 0.
#
# Input:
#
#    message
#
# Output:
#
#    1 if it is a NodeWatch status message and 0 if not.
#
# Side Effects:
#
#    None.
#

   my($msg) = $_[0];

   # If it is a NodeWatch status message, return 1, else return 0.
   if ($msg =~ /^It is \d+ and all is well\.$/ ||
       $msg =~ /^It is \d+ and hosts are down\.$/ ||
       $msg =~ /^It is \d+, node actions are disabled, and all is well\.$/ ||
       $msg =~ /^It is \d+, node actions are disabled, and hosts are down\.$/) {
      return 1;
   } else {
      return 0;
   }
}

#
##################################################

