#!/usr/bin/perl
#
# Action module for Ant monitoring system
#
# Sends mail with report to admin.
# Aggregates several reports in one mail, if more than one message
# is sent at 5 seconds
#
# Agrument is e-mail(s) where to send mails to.
#

use Fcntl;

#die "Undefined email or subject\n" if !defined $ENV{email} or !defined $ENV{subject};
#die "Bad email or subject\n" if $ENV{email} eq '' or $ENV{subject} eq '';

$ENV{PATH}="/usr/sbin";


$|=1;

$,=' ';

my $line;
my %tosend;
my $counter=0;
my $p2;

chomp @ARGV;
my $to=join(',',map {"<$_>"} @ARGV);

fcntl(STDIN,F_SETFL,fcntl(STDIN,F_GETFL,0)|O_NONBLOCK);

sub action();
sub sendit();

for(;;){
  $line='';
INNER_LOOP:
  for(;;){
    while(read(STDIN,$p,1)>0){
      $line.=$p;
      last INNER_LOOP if $p eq "\n" and $p2 eq "\n";
      $p2=$p;
    }
    if($counter>0){
      if(--$counter==0){
        sendit();
      }
    }
    select(undef,undef,undef,0.3);
  }
  action();
}

sub action( ){
  $line =~ /^([^\n]*)\n(.*)/s;

  $tosend{$1}.=$2;
  print "push it ($1)...\n";
  $counter=50 if($counter==0);
}


sub sendit(){
  my $i;
  foreach $i (keys(%tosend)){
    print "Send it ($i)!!!\n$tosend{$i}\n";
    open MAIL,"|sendmail '$to'" or die "Cannot run sendmail!";
    print MAIL <<MAIL_BODY;
To: $to
Subject: $i

$tosend{$i}
MAIL_BODY

    close MAIL;
  }
  %tosend=();
}
