#!/usr/athena/bin/perl -s

# $Header: /afs/sipb.mit.edu/project/dec-charon/mail-server/RCS/nightly-report.plin,v 1.3 1993/09/22 20:45:50 jik Exp $

push(@INC, "/rtfm/mserv");

require 'mservlib.pl';

$lockfile = &lib'make_file_name("stat-lock");
&lib'get_lock($lockfile);

if (! $lib'stat_file) {
    &lib'clear_lock($lockfile);
    die "No log file!";
}

if (! open(LOGFILE, $lib'stat_file)) {
    &lib'clear_lock($lockfile);
    die "Opening $lib'stat_file: $!.\n";
}

while (<LOGFILE>) {
    chop;
    $start = $1 if (! $start && /^(... .. ..:..:..)/);
    if (m,: sent .* // (.*),) {
	$files++;
	$files{$1}++;
    }
    elsif (m,: fail .* // (.*),) {
	$failed{$1}++;
	$failed++;
    }
    elsif (/\]: (.*): request from invalid address (.*)/) {
	$badfile = $1;
	$badaddr = $2;
	if ($invalid{$badaddr} !~ /$badfile/) {
	    $invalid{$badaddr} .= "\t$badfile\n";
	    $invalid++;
	}
	if (-f "$queuedir/$badfile") {
	    push(@bad_files, $badfile);
	    $still_invalid++;
	}
    }
    $end = $1 if (/^(... .. ..:..:..)/);
}

close(LOGFILE);

$start = "<unknown>" if (! $start);
$end = "<unknown>" if (! $end);

if ($mail) { # Set with -mail because of -s on perl command line
    if (! open(STDOUT, "|/usr/ucb/Mail -s '$lib'archiver report' $lib'admin_address")) {
	&lib'clear_lock($lockfile);
	die "Opening /usr/ucb/Mail: $!\n";
    }
}

print <<EOF;
Mail server report, covering the period from $start
                                          to $end.
EOF

if ($files) {
    print <<EOF;

A total of $files files were retrieved:

Times sent  File name
----------  ---------
EOF

    for (sort { $files{$b} <=> $files{$a}; } keys %files) {
	printf "%-10d  %s\n", $files{$_}, $_;
    }
}

if ($failed) {
    print <<EOF;

A total of $failed invalid requests were received:

Times sent  File requested
----------  --------------
EOF

    for (sort { $failed{$b} <=> $failed{$a}; } keys %failed) {
	printf "%-10d  %s\n", $failed{$_}, $_;
    }
}

if ($invalid) {
    print <<EOF;

A total of $invalid requests were sent from invalid addresses:

Address
	Request files(s)

EOF

    for (keys %invalid) {
	print "$_\n$invalid{$_}";
    }
}

if ($still_invalid) {
    print <<EOF;

Of those, $still_invalid are still in the queue:

EOF

    for (sort @bad_files) {
	print "\t$_\n";
    }
}

if ($full) { # set with -full because of perl -s
    if (! open(LOGFILE, $lib'stat_file)) {
	&lib'clear_lock($lockfile);
	die "Opening $lib'stat_file: $!.\n";
    }
    print "\nComplete log output:\n";
    while (<LOGFILE>) {
	print;
    }
    close(LOGFILE);
}

if (! close(STDOUT)) {
    &lib'clear_lock($lockfile);
    die "Closing STDOUT: $!.\n";
}

# $clear is set with "-clear" (note running perl with -s)

if ($clear) {
    if (! open(LOGFILE, ">$lib'stat_file")) {
	&lib'clear_lock($lockfile);
	die "Opening $lib'stat_file for write: $!.\n";
    }
    close(LOGFILE);
}

&lib'clear_lock($lockfile);

exit 0;
