#!/usr/local/bin/perl

use strict;
use warnings;

## Define things here
my $counter = 0;
my $state = 'UP';
my $email = 'av@silverwraith.com';

## Get host to ping from command line or die
my $host = shift or die "USAGE: ping.pl <host>";
## Set a wide path, so that ping can be found regardless of location
$ENV{'PATH'} = "$ENV{'PATH'}:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin";

## Find the required system binaries, if we can't, then die
foreach my $tool ('ping', 'mail') {
	`which $tool > /dev/null`;
	die "ERROR: Could not find '$tool' in the PATH: $ENV{'PATH'}" unless $? == 0;
}

## Check to see if a host is up or down
while (1) {
	if ($state eq "UP") {
		## Reset the counter if the host is up and the ping was successful.
		## This protects against minor state changes.
		if ($? == 0) {
			$counter = 0;
		} else {
			$counter++;
		}
		email();
	} elsif ($state eq "DOWN") {
		## Reset the counter if the host is down and the ping was unsuccessful.
		## This protects against minor state changes.
		if ($? != 0) {
			$counter = 0;
		} else {
			$counter++;
		}
		email();
	}
	## A sleep, to make this sane
	sleep 60;
}

sub email {
		if ($counter == 5) {
			`echo $host is $state | mail -s "$host is $state" $email`;
			## Reset the counter after sending the mail
			$counter = 0;
		}
}

