#!/usr/bin/perl
# TT [N] host...
#
# Show the last 5 totals lines from a list of hosts.  If there are no
# hosts listed on the command line, we find the more recend N host in
# the hst/ directory and show the last 5 totals lines for each one.
#
# Note that, if ABCbot is running, the latest hst/ entry is  probably
# not complete, and the numbers we print are from some random time in
# the past.

$| = 1;
($P = $0) =~ s".*/"";
$V = $ENV{"V_$P"} || $ENV{"D_$P"} || 1;	# Verbose level.

$failures = 0;
if (($n = $ARGV[0]) =~ /^\d+$/) {
	shift;
	$n = int($n);
	$n = -$n if $n < 0;
} else {
	$n = 5;
}
unless (@ARGV) {
	@ARGV = `ls -tr hst | tail -$n`;
}

for	$h (@ARGV) {
	$h =~ s".*/"";
	$h =~ s"[-\r\s]+$"";
	print "$h\n";
	$hstfil = "hst/$h";
	if (open(H,$hstfil)) {
		@T = ();
		$tunes =	# Tune count for this host
		$titles =	# Title count
		$files =	# Files that contain tunes
		$scans = 0;	# Number of scans found for this host
		$tag = '';	# Append to last line
		for $l (<H>) {
			if ($l =~ /^(\d+)\s+T\s+X:(\d+)\s+T:(\d+)\s+F:(\d+)\s+(.*)$/) {
				$tunes  = int($2);
				$titles = int($3);
				$files  = int($4);
				($line = $l) =~ s/[\r\s]*$//;	# Total line stripped
				push @T, "$line\n";
				++$scans if $tunes > 0;
			} elsif ($l =~ /^(\d+)\s+T\s+L:(\d+)\s+X:(.*)$/) {
				$line = sprintf("%10d T X:$3",$1);
				push @T, "$line\n";
			} elsif ($l =~ /^(\d+)\s+(.*No ABC.*)$/) {
				$line = sprintf("%10d $2",$1);
				push @T, "$line\n";
			} elsif ($l =~ /^(\d+) Scanned (.*)[\r\s]$/) {
				push @T, sprintf("%10d Scanned $2",$1);
			} else {
			#	Ignore everything else now.
			}
			shift @T if (int(@T) > $n);
		}
		close H;
		if ($T[$#T] =~ / Scanned /) {
			print "$P: scans=$scans $tag='$tag'\n" if $V>2;
			if ($scans < 1) {$tag = ' --- No ABC found ---'}
			elsif ($scans < 3) {$tag = "	[NEW SITE $files files $tunes tunes $titles titles]"}
			$T[$#T] =~ s/\s*$/$tag\n/;
		}
		print @T;
	} else {
		print STDERR "$0: Can't read \"$hstfil\" ($!)\n";
		++$failures;
	}
}

print "$P: $failures failures.\n" if $failures > 0;

exit $failures ? 1 : 0;
