#!/usr/bin/perl -w
#NAME
#  DelNulls - Remove hst/ files that contain no useful data
#
#SYNOPSIS
#  [hosts]...
#REQUIRES
#
#DESCRIPTION
# 
#
#OPTIONS
# 
# -V[n]
# +V[n]
#   Set a verbose level.  The default is 1, which gives only important
#   information like reasons for failure.
#
#EXAMPLES
#
#FILES
#
#BUGS
#
#SEE ALSO
#
#AUTHOR
#  2018 John Chambers <jc@trillian.mit.edu>
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #

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

$bad   = 'bad';	# Directory for "bad" sites
$del   = 10;	# Whether to delete bad hst files
$hosts = 0;		# Hosts examined so far
$limit = 0;		# If > 0, quit after this many hosts examined
@list  = ();	# Hosts to examine

for $arg (@ARGV) {
	print STDERR "$P: arg=\"$arg\"\n" if $V>2;
	if (($flg,$opt) = ($arg =~ /^([-+])(.*)$/)) {
		print STDERR "$P: flg='$flg' opt=\"$opt\"\n" if $V>2;
		if (uc($opt) =~ /^L(\d+)/) {		# Limit to number of hosts
			$limit = int($1);
			print STDERR "$P: limit='$limit'\n" if $V>0;
		} elsif (uc($opt) =~ /^V(\d+)/) {	# Verbose level
			$V = int($1);
			print STDERR "$P: V='$1'\n" if $V>0;
		} else {
			print STDERR "$P: Arg \"$arg\" ignored.\n" if $V>0;
		}
	} else {
		print STDERR "$P: arg=\"$arg\" listed.\n" if $V>1;
		$arg =~ s"^.*/"";	# Strip off directory names
		push @list, $arg;	# List it as a host to examine
	}
}

unless (@list) {	# Look at all of the hst directory
	opendir(HST, 'hst') || die "$P: Can't read hst directory.\n";
	for $hst (readdir(HST)) {
		if ($hst =~ /^\./) 	{
			print STDERR "$P: hst=\"$hst\" ignored [.]\n" if $V>1;
		} else {
			print STDERR "$P: hst=\"$hst\" found.\n" if $V>1;
			push @list, $hst;
		}
	}
}

print STDERR "$P: Examine listed hosts ...\n" if $V>1;
host:
for $hst (@list) {
	++$hosts;
	exit $exitstat if ($limit > 0 && $hosts > $limit);
	sleep 1 if $V>1;
	$path = "hst/$hst";
	next if -d $path;
	$last = `tail -1  $path`;
	$last =~ s/[\r\s]+$//;		# Trim away white stuff
	print STDERR "Test: \"$last\" ...\n" if $V>1;
	if ($last =~ ' NEW SITE 0 files 0 tunes 0 titles') {
		print "$P: NULL hst/$hst\n" if $V>0;
		link($path,"$bad/$hst");	# This host didn't have any tune files
		unlink($path) if $del;
		next host;
	}
	print STDERR "$P: Not a new site.\n" if $V>1;
	print STDERR "test: \"$last\" ...\n" if $V>1;
	if ($last =~ /\d* \+ start /) {
		print "$P: LOST hst/$hst\n" if $V>1;
		link($path,"$bad/$hst");	# Lost without getting anything worth reporting
#		unlink($path) if $del;
#		next host;
	} elsif ($last =~ ' T X:0 T:0 F:0 ') {
		print "$P: ZERO hst/$hst $last" if $V>1;
		link($path,"$bad/$hst");	# Lost after getting reportable stuff, but no tunes.
#		unlink($path) if $del;
#		next host;
	} else {
		print "$P: GOOD hst/$hst\n" if $V>1;
	}
}

exit $exitstat;
