#!/usr/bin/perl -w
#
# $Id: scheduler,v 1.6 2002/06/22 18:33:31 cvs Exp $
#
# scheduler: A basic alarm scheduler for PICA

BEGIN { push @INC, "/usr/local/lib/site_perl"; };

#perl
# First of all check if we have defined the MANDATORY variables
if (!$notifymail || !$notifypager) {
   print <<__EOF__;
***************************************************************************
ERROR: Mandatory PIFIA variables 'notifymail' and 'notifypager' not defined
***************************************************************************
__EOF__
   "";
}
#lrep

use strict;
use pifia;

#------------------------------------------------[ Configuration Section ]----

my $picabasedir = '<#$picaalarms#>';
my $notifymail = '<#$notifymail#>';
my $mailcmd = "<#$mailcmd#>";
my $notifypager = '<#$notifypager#>';
my $pagercmd = "<#$pagercmd#>";

#-----------------------------------------------------------------------------

my $priority = shift ;
die "I need a priority!\n" unless defined $priority;
my @output;
my $host=`uname -n`;
chomp $host;

# Get timestamp
my $tstamp=tstamp('time');

# Get hostname
my $hostname=`uname -n`;
chomp $hostname;

my $header = 1;
# Process all alarms in the given priority
while (<$picabasedir/$priority/*-picacaller>) {
   next unless -x ;
   my $alarm = $_;
   chomp $alarm;
   $alarm =~ s|^.*/||;
   open F, "$_ |" or do {
      push @output, "WARNING: Couldn't execute $_\n";
      next ;
   };
   my $alarmheader = 1;
   while (<F>) {
      if ($header) {
         push @output, "$priority \n";
         $header = 0;
      }
      if ($alarmheader) {
         my $alarmactualname = $alarm;
         $alarmactualname =~ s/-picacaller$//;
         push @output, "\t$alarmactualname \n";
         $alarmheader = 0;
      }
      push @output, "\t\t$_";
   }
   close F;
}

# If we got output, send alarm
if (@output) {
   my $date = `date`;
   if ($mailcmd) {
      open(MAIL,"|$mailcmd") or die("Can't open mail program: $!\n");
      print MAIL <<__EOB__;
From: pica\@$host
To: $notifymail
Subject: PICA Alert ($priority) on $host   


                       PICA Alert on $host
                       $date
__EOB__
      print MAIL @output;
      close(MAIL);
  }
  if ($pagercmd) {
      open(PAGER,"|$pagercmd") or die("Can't open pager program: $!\n");
      map { s/\s+/ /g } @output;
      print PAGER "$hostname $tstamp \n";
      print PAGER @output;
      close(PAGER);
  }
}
