#!/usr/bin/perl

#
# JKF 3/1/2001 Analyse the sendmail logs from magpie and crow to find
#              the number of viruses rejected and pieces of spam
#              detected in a day.

$cmd = shift;

#system("echo >> /tmp/foo.log");
#system("date >> /tmp/foo.log");
#system("/usr/bin/echo cmd is $cmd >> /tmp/foo.log");

$LogDir = "/opt/mrtg/var/sendmaillogs";

chdir $LogDir or die "Cannot change to log directory $LogDir, $!";

# Find all the compressed files in the log directory
do {
  opendir(LOGDIR, '.') || die "Cannot access log dir $LogDir, $!";
  while ($file=readdir LOGDIR) {
    next if $file =~ /^\./;
    push @logfiles, $file if -f $file;
  }
  sleep 300 unless @logfiles;
} until @logfiles;

# Reset counters
$TotalMails   = 0;
$TotalViruses = 0;
$TotalSpam    = 0;

#system("/usr/bin/echo logfiles are " . join(',', @logfiles) . " >> /tmp/foo.log");

# Work through each file building stats
foreach $file (@logfiles) {
  if ($file =~ /\.Z$/) {
    open(LOG, "zcat $file|")
      or (warn("Cannot access log file $file, skipping, $!"), next);
  } else {
    open(LOG, $file)
      or (warn("Cannot access log file $file, skipping, $!"), next);
  }
  while(<LOG>) {
    chomp;
    if (/sendmail/) {
      $TotalMails += $1 if /nrcpts=(\d+),/;
      next;
    }
    if (/mailscanner/) {
      $TotalViruses += $1 if /found (\d+) viruses in/i;
      $TotalSpam++        if /message [^\s]+ is spam/i;
    }
  }
  close LOG;
}

print "$TotalMails\n" if $cmd =~ /mail/i;
print "$TotalViruses\n" if $cmd =~ /virus/i;
print "$TotalSpam\n" if $cmd =~ /spam/i;
print "0\n";
print "Not Applicable\n";
print "ECS Mail Servers\n";