#!/bin/perl

require "getopts.pl";

# Path to database made by 'tst'
$dbp1 = "/usr/local/news/log/";
$dbp2 = "/usr/local/news/log/db/";
$dbnam = "tstdb";
$db = $dbp2.$dbnam;
$resultfile =  $dbp2 . "tstdata";
$tries = 10;
$cflush="/usr/local/news/inn/bin/ctlinnd flush";

# The name of your host -- if hostname gives FQDN, then use this
# else  use the second line with correct 
#$host=`hostname`;
$host='swidir.switch.ch';

# Give a cutoff -- little links don't count and this will reduce 
# the size of the result files

$cutoff = 7*30;    # 7 Days a 30 articles each

# Path to sendmail program
$sendmail='/usr/lib/sendmail';

#
# Nothing should need changes below (I hope)
#

$usage = "tst_out    (c) Heiko Rupp <hwr@pilhuhn.de> with additions by Felix Kugler <felix@switch.ch>
Cycle db with Path:-data collected by 'tst', preprocess and send data to Heiko.
Usage: tst_out [-fhr]
        -f: write to file $resultfile instead of piping into sendmail
        -h: this help
        -n: do not cycle db, use old copy to process & send
        -r: resend existing result file $resultfile, do not cycle db\n";

&Getopts('hfnr');
if ($opt_h) { print "$usage"; exit 0; }

$host =~ s/\n//;		# chop occasional linefeed


if ($opt_r) {			# resend an existing result file
    open(RF,$resultfile) || die "cannot open $resultfile: $!\n";
    &init_mail;
    while (<RF>) {
	print OUT;
    }
    close(OUT);
    exit 0;
}

# flush db and save data
unless ($opt_n) {
    chdir($dbp2) || die "$dbp2 does not exist - please create directory";
    chdir($dbp1);

    system("mv $dbnam* $dbp2");

    system($cflush." TST");

    sleep 2;
}

while ($tries > 0) {
    last if dbmopen(%db,$db,0644);
    sleep 5;
    $tries --;
}
die "No DB $db " if $tries == 0;

$tot=$db{'*'};

if ($opt_f) { open(OUT,">$resultfile") || die "cannot open $resultfile: $!\n"; }
else { &init_mail; }

print OUT "Site: ",$host,"\n";
print OUT "Total: ",$tot,"\n";

foreach $x (sort keys %db) {
	($to,$from) = split('_',$x);
	if ($to ne "*" && $from ne "*" && $db{$x} > $cutoff) {
		print OUT $to,"!",$from,"!",$db{$x},"\n";
	}
}

dbmclose(%db);
close(OUT);

sub init_mail {
    open(OUT,"|$sendmail -t -v")  || die "Sendmail not found ";
    print OUT "From: news\@$host\n";
    print OUT "Subject: Data from $host\n";
    print OUT "To: collect-stats\@snert.pilhuhn.de\n";
    print OUT "\n";
} 
