#!/usr/bin/perl

=head1 Wait Up - Scans at intervals until a server is up

Copyright (c) Paul Battley / po-ru.com / July 2002

This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute and modify
it under the terms of the GNU General Public License
(see http://www.fsf.org/licenses/gpl.html for more information).

=cut

use Getopt::Long;
use IO::Socket::INET;
use Time::HiRes qw[sleep];
use Pod::Text;

# defaults
$def_port = 80;
$timeout = 5;
$pause = 10;

GetOptions ('timeout=i'    => \$timeout,
            'help'         => \$help,
            'pause=i'      => \$pause
           );

do_help() if (defined ($help));

($host, $port) = split (/:/, $ARGV[0]);
# undocumented bonus feature: if the user tried to type waitup host port
# (no colon) we'll let it work anyway.
$port ||= $ARGV[1];
$port ||= $def_port;

do_help() unless (defined ($host));
print ("Attempting connect to $host on port $port...");

do
{
  print ('.');
  if ($socket = IO::Socket::INET->new
    (PeerAddr => $host, PeerPort => $port, Proto => "tcp",
     Type => SOCK_STREAM, Timeout  => $timeout))
  {
    $up = 1;
    close ($socket);
  }
  else
  {
    $up = 0;
    close ($socket);
    sleep ($pause);
  }
} until ($up);
print ("\nServer is up!\n");
exit();

# Prints the help from the POD documentation in this file
sub do_help
{
  my $parser = Pod::Text->new (width => 78);
  $parser->parse_from_file ($0);
  exit();
}

=head1 About

This program simply repeatedly attempts to connect to a given server on a given port
until it either succeeds or is killed.

=head1 Usage

waitup [options] host[:port]

Port is optional; default value is 80 (HTTP).

=head1 Options

=head2 --pause N

Number of seconds to wait after each failed attempt before the next.

=head2 --timeout N

Timeout in seconds for connection attempts.

=head2 --help

View the documentation (this is it!).

=cut
