#!/usr/bin/perl -w

# Looping test on whether an Internet connection is up. Pings an
# address continuously, prints out every failure and every Nth
# success. Written to catch the PacBell line crew on Geary.
# By <nelson@monkey.org> 2001-11-15. I won't support this script.

use Net::Ping;

autoflush STDOUT 1;
if ($#ARGV < 2) {
    print ("Usage: $0 hostname pingInterval printInterval\n");
    exit;
}
$host=$ARGV[0];                  # host to ping
$pingInterval=$ARGV[1];          # seconds between pings
$printInterval=$ARGV[2];         # number of pings between prints of success

$proto='icmp';                   # ping protocol (see Net::Ping(3m))
$timeout=5;                      # ping timeout

$ping = Net::Ping->new($proto, $timeout);
$i = 0;
$outage = 0;
$lastSuccess = time;
$lastSuccessString = localtime;

while (1) {
    $i++;
    $now = time;
    if ($ping->ping($host)) {
        if (($i-1) % $printInterval == 0) {
            $date = localtime;
            print "Ping $i succeeded $date\n";
        }
        # If the last pings were failures, report how long
        if ($outage == 1) {
            print "Outage for ", (time - $lastSuccess), " seconds started ", $lastSuccessString, "\n";
        }
        $outage = 0;
        $lastSuccess = time;
        $lastSuccessString = localtime;
    } else {
        $date = localtime;
        print "Ping $i failed $date\n";
        $outage = 1;
    }
    $sleepTime = $pingInterval - (time - $now);
    sleep $sleepTime;
}
