#!/usr/bin/perl
#
# Use try to connect to a FTP server using Net::FTP, login as
# anonymous and issue PWD.
#
# Since anonymous ftp servers can be quite busy I suggest that you
# enter more than one anonymous ftp server and use option -o. That will
# return success if ANY OF SERVERS are available -- that way you can
# test if you can connect to ANY ftp server outside.
#
# For use with "mon".
#
# Arguments are "[-p port] [-t timeout] [-o] host [host...]"
#
# 2002-09-02 Dobrica Pavlinusic <dpavlin@rot13.org>
# 

use Getopt::Std;
use Net::FTP;

getopts ("p:t:o");
$PORT = $opt_p || 21;
$TIMEOUT = $opt_t || 30;

my %bad;

foreach my $host (@ARGV) {

	my $result = check_anon_ftp($host);
	if ($result) {
		$bad{$host} = $result;
	} else {
		$good{$host} = "ok";
	}
}

if (keys %bad == 0) {
    exit 0;
}

print join (" ", sort keys %bad), "\n";

foreach my $h (keys %bad) {
    print "HOST $h: " . $bad{$h}, "\n";
}

if ($opt_o && keys %good > 0) {
	# one host is o.k., don't report warning
	exit 0;
}

exit 1;

sub check_anon_ftp {
	my ($host) = @_;
	$ftp = Net::FTP->new($host, Debug => 0, Timeout => $TIMEOUT, Port => $PORT) || return "can't connect to $host:$PORT for $TIMEOUT seconds.";
	$ftp->login("anonymous",'mon@kernel.org') || return "$host: can't login as anonymous";
	my $dir = $ftp->pwd || return "$host: can't do PWD";
	$ftp->quit;
	return 0;
}

