#!/usr/bin/perl # -*- perl -*-
#
#  Log connection downtime
#  run a function on drop and return
#
#  
## set up logging
use IO::Handle;

sub init_log {
    close(LOG); 
    open(LOG, ">>connlog");
    LOG->autoflush(1);
    print LOG "Connectivity check:\n".&date." on $addr from ".`hostname`;
    print LOG "ping interval: $interval seconds, trigger $loss lost/$timeout second timeout\n";
    $timecomp = $loss*$interval;
    print LOG "timeout reports compensated by $timecomp\n";
}

$interactive = 0;
$SIG{HUP} = "init_log";

## set up ping
$addr = (scalar(@ARGV)>0)?(shift ARGV):"209.21.177.10";
$interval = 3; $loss = 2;
$timeout = $loss*$interval + 1;	# notice 2 lost pings
$debug = 0;
&init_log;
open(PING,"ping -i $interval $addr|") or die;
$rin = $win = $ein = '';
vec($rin,fileno(PING),1) = 1;
$ein = $rin | $win;


$| = 1;
$tflag = 0;
while(1) {
    ($nfound,$timeleft) =
	select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
    if ($nfound) {
	if (vec($rin,fileno(PING),1)) {
	    $slen = sysread(PING, $sval, 1024);
	    chomp $sval;
	    $tflag && print LOG "\ntimeout ended...".&date." [".(time-$tlast+$timecomp)."s]\n";
	    $interactive && $tflag && print "\ntimeout ended...".&date." [".(time-$tlast+$timecomp)."s]\n";
	    $tflag = 0;
	    $interactive && $debug && print "got ping <$sval>\n";
	} else {
	    $interactive && print "HUH? nfound $nfound but not PING\n";
	    print LOG "HUH? nfound $nfound but not PING\n";
	}
    } else {
	$interactive && $tflag || print "timeout...      ".&date;
	$tflag || ($tlast = time);
	$interactive && $tflag && print ".";
	$tflag = 1;
    }
}

sub date {
    my $x = `date`;
    chomp $x;
    $x;
}
