#!/usr/bin/perl -w

use strict;
use Net::Ping::External qw(ping);

my $tries = 10;
my $max_fail = 5;

my $ppp_rc;
if (-x "/etc/rc.d/ppp-user")
{
	# FreeBSD 6.x and before
	$ppp_rc = "/etc/rc.d/ppp-user";
}
elsif (-x "/etc/rc.d/ppp")
{
	# FreeBSD 7.x and after
	$ppp_rc = "/etc/rc.d/ppp";
}
else
{
	die "Cant find rc.d script for ppp!\n";
};

open (ROUTES, "/usr/bin/netstat -rn |grep default |")
	or die "Cant open route table for reading: $!\n";
my $defaultrouter;
while (<ROUTES>)
{
	chomp;
	my @str = split(/\s+/);
	if ($str[0] eq 'default')
	{
		$defaultrouter = $str[1];
		last;
	};
};
unless ($defaultrouter)
{
#	system("/sbin/ifconfig");
#	system("/usr/bin/netstat -rn");
	warn scalar(localtime(time))." Cant read defaultrouter address! Restarting ppp....\n";
	system("$ppp_rc restart");
	exit 0;
};

my $fails = 0;
while ($tries)
{
	$fails += 1 unless ping(hostname => $defaultrouter, count => 1, size => 128, timeout => 3);
	$tries--;
};

if ($fails > $max_fail)
{
	warn scalar(localtime(time)).
		" Ping loss $fails of $tries packets (max loss is $max_fail). Restarting ppp....\n";
	system("$ppp_rc restart");
};
