#!/usr/local/bin/perl5

# This is a version with slightly modified linefeed handling for $hostname
# 960626 fk

# Path to database made by 'tst'
$dbp1 = "/var/log/news/";
$dbp2 = "/var/log/news/db/";
$dbnam = "tstdb";
$db= $dbp2.$dbnam;
$tries = 10;
$cflush="/usr/local/news/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='news.dom.main';

# 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/sbin/sendmail';

#
# Nothing should need changes below (I hope)
#
$host =~ s/\n//;                # chop occasional linefeed

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{'*'};


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";

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);

#reset;

