# ftp-monitor.pl
# Monitor a remote FTP server by doing a test download

sub get_ftp_status
{
local $up=0;
local $st = time();
local $error;
local $temp = &transname();
eval {
	local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
	alarm($_[0]->{'alarm'} ? $_[0]->{'alarm'} : 10);

	&ftp_download($_[0]->{'host'}, $_[0]->{'file'}, $temp, \$error,
		      undef, $_[0]->{'user'}, $_[0]->{'pass'}, $_[0]->{'port'});
	alarm(0);
	$up = $error ? 0 : 1;
	};

if ($@) {
	die unless $@ eq "alarm\n";   # propagate unexpected errors
	return { 'up' => 0 };
	}
else { 
	return { 'up' => $up, 'time' => time() - $st,
		 'desc' => $up ? undef : $error };
	}
}

sub show_ftp_dialog
{
print "<tr> <td><b>$text{'ftp_host'}</b></td>\n";
print "<td>",&ui_textbox("host", $_[0]->{'host'}, 30),"</td>\n";

print "<td><b>$text{'ftp_port'}</b></td>\n";
print "<td>",&ui_textbox("port", $_[0]->{'port'} || 21, 5),"</td>\n";

print "<tr> <td><b>$text{'ftp_user'}</b></td>\n";
print "<td>",&ui_opt_textbox("ftpuser", $_[0]->{'user'}, 15,
			     $text{'ftp_anon'}),"</td>\n";

print "<td><b>$text{'ftp_pass'}</b></td>\n";
print "<td>",&ui_password("ftppass", $_[0]->{'pass'}, 15),"</td>\n";

print "<tr> <td><b>$text{'ftp_file'}</b></td>\n";
print "<td colspan=3>",&ui_opt_textbox("file", $_[0]->{'file'}, 50,
				   	$text{'ftp_none'}),"</td> </tr>\n";

print "<tr> <td><b>$text{'http_alarm'}</b></td>\n";
printf "<td><input type=radio name=alarm_def value=1 %s> %s\n",
	$_[0]->{'alarm'} ? '' : 'checked', $text{'default'};
printf "<input type=radio name=alarm_def value=0 %s>\n",
	$_[0]->{'alarm'} ? 'checked' : '';
print "<input name=alarm size=5 value='$_[0]->{'alarm'}'></td> </tr>\n";
}

sub parse_ftp_dialog
{
$in{'host'} =~ /^[a-z0-9\.\-\_]+$/i || &error($text{'ftp_ehost'});
$_[0]->{'host'} = $in{'host'};

$in{'port'} =~ /^\d+$/i || &error($text{'ftp_eport'});
$_[0]->{'port'} = $in{'port'};

$in{'ftpuser_def'} || $in{'ftpuser'} =~ /^\S+$/ || &error($text{'ftp_euser'});
$_[0]->{'user'} = $in{'ftpuser_def'} ? undef : $in{'ftpuser'};
$_[0]->{'pass'} = $in{'ftppass'};

$in{'file_def'} || $in{'file'} =~ /^\S+$/ || &error($text{'ftp_efile'});
$_[0]->{'file'} = $in{'file_def'} ? undef : $in{'file'};

if ($in{'alarm_def'}) {
	delete($_[0]->{'alarm'});
	}
else {
	$in{'alarm'} =~ /^\d+$/ || &error($text{'http_ealarm'});
	$_[0]->{'alarm'} = $in{'alarm'};
	}
}

