: # *-*-perl-*-*
    eval 'exec perl -S $0 "$@"'
    if $running_under_some_shell;

#
# Checks on Harvest gatherers and brokers.  
#
#	* Makes TCP connections to gatherer and broker ports.
#	  Gives 'perror' if connect fails.
# 
#	* Counts files in objects directories.  Stops counting after
#	  $MAXFILECOUNT, and reports directories containing less than
#	  $MAXFILECOUNT files.
#
#	* -v option reports successful connections and total count of
#	  files in objects directories.
#
# Duane Wessels 12/28/94

$MAXFILECOUNT=100;  	# the filecount procedure stops when it counts this
			# many files

require "$ENV{'HARVEST_HOME'}/lib/socket.ph";

$verbose = 1
	if ($ARGV[0] eq "-v");

$|=1;

while (<DATA>) {
	chop;
	next if (/^#/);
	($what, $name, $host, $port, $dir) = split;

	if ($host ne "" && $port != 0) {
		$cmd = "QUIT\n" if ($what eq 'gatherer');
		print "$what $name $host $port: $!\n"
			unless ($c = &connect_tcp ($host,$port, $cmd));
		if ($verbose && $c) {
			printf ("%-10s %-10s %-35s : UP\n",
				$what, $name, $host.":".$port);
		}
	}

	if ($dir ne '') {
		$dir = "$ENV{'HARVEST_HOME'}/" . $dir
			unless ($dir =~ /^\//);
		$n = &filecount ($dir);
		printf ("%7d objects in: $dir\n", $n)
			if ($verbose || $n < $MAXFILECOUNT);
	}
}

exit 0;

sub connect_tcp {
        local ($host, $port, $cmd) = @_;
        local ($sockaddr) = 'S n a4 x8';
        local ($name, $aliases, $proto) = getprotobyname('tcp');
        local ($connected) = 0;
 
        # Lookup addresses for remote hostname
        #
        local($w,$x,$y,$z,@thataddrs) = gethostbyname($host);
        die("Unknown Host: $host\n")
		unless (@thataddrs);
 
        # bind local socket to INADDR_ANY
        #
        local ($thissock) = pack($sockaddr, &AF_INET, 0, "\0\0\0\0");
        die("socket: $!\n")
		unless socket (SOCK, &AF_INET, &SOCK_STREAM, $proto);
        die("bind: $!\n")
		unless bind (SOCK, $thissock);
 
        # Try all addresses
        #
        foreach $thataddr (@thataddrs) {
                local ($that) = pack($sockaddr, &AF_INET, $port, $thataddr);
                if (connect (SOCK, $that)) {
                        $connected = 1;
                        last;
                }
        }

        return 0 unless ($connected);
	return 0 unless ($cmd eq '' || print SOCK $cmd);
	return 0 unless close SOCK;
	return 1;
}

sub filecount {
	local ($dir) = shift;
	local ($n) = 0;
	push (@dirs, $dir);

	while ($dir = shift @dirs) {
		unless (opendir (D, $dir)) {
			print STDERR "$dir: $!\n";
			return 0;
		}
		foreach $f (readdir D) {
			next if ($f eq '.');
			next if ($f eq '..');
			print STDERR "$dir/$f: $!\n"
				unless (stat ("$dir/$f"));
			push (@dirs, "$dir/$f")	if (-d _);
			$n++			if (-f _);
		}
		closedir D;
		return ($n) if ($verbose == 0 && $n > $MAXFILECOUNT);
	}
	$n;
}

__END__

#what    name		host			port  [objdir]
broker   default	localhost		8501  brokers/default/objects
gatherer default	localhost		8500
