#!/usr/bin/perl

$ip          = 'A.B.C.D';
$logfile     = "/var/log/XXX";
$logfile2    = "/var/log/YYY";
$link_up     = "/usr/sbin/birdc enable XXX";
$link_down   = "/usr/sbin/birdc disable XXX";
$cmd         = 'fping -c 40 -p 50 ' . $ip . ' 2>&1 >/dev/null';


$state = 0;
$start = 1;
$counter = 50;
$tc = 0;

open(LOGFILE, '>>', $logfile);
print LOGFILE localtime () . ': watchdog (' . $ip . ") started\n";
close(LOGFILE);

while (1)
{
    $unreach = `$cmd`;
    $unreach =~ s/.*\/([[:digit:]]+)%.*/\1/s;

    open(LOGFILE2, '>>', $logfile2);

    if ($tc == 0)
    {
	print LOGFILE2 localtime () . ":";
    }

    print LOGFILE2 " " . (0+$unreach) . "%";
    $tc ++;

    if ($tc > 10)
    {
	print LOGFILE2 "\n";
	$tc = 0;
    }

    close(LOGFILE2);


    
    if ($unreach == 0)
    {
	$counter -= 100;
    }
    elsif ($unreach < 3)
    {
    	$counter -= 50;
    }
    elsif ($unreach < 6)
    {
    	$counter -= 10;
    }
    else
    {
	$counter += $unreach;
    }

    if ($counter > 300)
    {
	$counter = 300;
    }
    
    if ($counter < 0)
    {
	$counter = 0;
    }
    
    if ((($start) && ($unreach < 6)) ||
        (($state == 0) && ($counter < 30)))
    {
        system ($link_up);

	$state = 1;
	$start = 0;

	open(LOGFILE, '>>', $logfile);
	print LOGFILE localtime () . ': Link (' . $ip . ") online\n";
	close(LOGFILE);
    }
    if ((($start) && ($unreach >= 6)) ||
        (($state == 1) && ($counter > 95)))
    {
	system ($link_down);

    	$state = 0;
	$start = 0;

	open(LOGFILE, '>>', $logfile);
	print LOGFILE localtime () . ': Link (' . $ip . ") offline\n";
	close(LOGFILE);
    }
    
    sleep 2;
}

