#!/usr/bin/perl
# File:       mf-analyze
# Version:    1.11
# Purpose:    Analyzes rejected messages saved by rays-filter
#             (Run once every 24 hours)
# Requires:   mail-filter.conf, string-list.conf
# Written by: R. Butler <butlerra@sbu.ac.uk>
# Date:       23-Jun-2000
# Revised:    31-Jul-2000
# 
# Copyright (C) 2000 South Bank University, London.
# (Please see the full copyright notice in 'copyright.txt')

# Note: Assumes that the previous day's rejected messages have been 
#       moved to the directory specified by '$message_files'.  This
#       is done by the 'archive-rejects' script.

$conf_file = "/usr/local/etc/mail-filter/mail-filter.conf";
$string_list = "/usr/local/etc/mail-filter/string-list.conf";
$work_dir = &get_work_dir($conf_file);
$message_files = $work_dir . "/rejects/Arc-yesterday/*";
$out_file = $work_dir . "/analysis/analysis." . `date +"%d-%b-%Y"`;
$count = 0;
$total = 0;
$args = @ARGV;

open(OUT_FILE, ">$out_file")
   || die "$0: Cannot open file $out_file for output\n";
print OUT_FILE "\n\n\n";
print OUT_FILE `date +"%d-%b-%Y %T"`;
print OUT_FILE "Analysis of yesterday\'s rejected messages on ";
print OUT_FILE `hostname`;
print OUT_FILE 
   "\nNOTE: Patterns such as name=\\\".*\\.vbs\\\", representing attached\n";
print OUT_FILE 
   "      files, will usually occur twice for each attachment.\n\n";
print OUT_FILE "Pattern                   Count\n\n";
&scan_message_files($string_list);
print OUT_FILE "-------------------------------\n";
printf OUT_FILE "%-25s %5d\n", "TOTAL", $total;
print OUT_FILE "===============================\n\n";
close(OUT_FILE);


sub scan_message_files {
   local($string_list) = @_;
   open(STRING_LIST, "$string_list");
   while (<STRING_LIST>) {
      if ((/#.*/ == 0) && (/^\W$/ == 0)) {
         while (/\s$/) {
            chop;
         }
         while (/^\s/) {
            s/^\s//;
         }
         $pattern = $_;
         s/\./\\\./g;
         s/\"/\\\"/g;
         s/\*/\\\*/g;
         s/\^/\\\^/g;
         s/\$/\\\$/g;
         $command = "grep -i \'^:_ $_\' $message_files | wc -l";
         # print "$command\n";
         $count = `$command`;
         $total += $count;
         printf OUT_FILE "%-25s %5d\n", $pattern, $count;
      }
   }
   close(STRING_LIST);
}


sub get_work_dir {
   local($conf_file) = @_;
   open(CONF_FILE, "$conf_file");
   while (<CONF_FILE>) {
      if (/^\s*WORK_DIR\s*=\s*\"{0,1}([^\s\"]+)/) {
         $work_dir = $1;
         last;
      }
   }
   close(CONF_FILE);
   $work_dir;
}

