#!/usr/bin/perl

($hostname)=@ARGV;

$VERSION="2.0";

use DBI;
use POSIX;

$DBSERVER="localhost";
$DBNAME="stats";
$DBUSER="root";
$DBPASS="";
# Connect to mysql
$dbh = DBI->connect ( "dbi:mysql:dbname=$DBNAME;host=$DBSERVER", "$DBUSER", "$DBPASS");
if ( !defined $dbh ) {
	die "Cannot connect to database!\n";
}

$TIME_LAST_COLLECT=86400;
$time_for_select=time-$TIME_LAST_COLLECT;

# Gets all interfaces beeing monitored
$#IF_ID=-1;
$#HOSTNAME=-1;
$#IFNAME=-1;
$sth=$dbh->prepare("SELECT distinct hostname FROM stats_ifs");
$sth->execute;
while (($hostname) = $sth->fetchrow()) {
	push(@HOSTNAME, $hostname);
}
$sth->finish();

$nr_ifs_not_collecting=0;
$temp="";
foreach $host (@HOSTNAME) {
	#print "++$host\n";
	$new_hostname=gen_hostname($host);
	$table_to_select="stats_".$new_hostname;
	$table_to_select =~ s/\./_/g;
	$sth=$dbh->prepare("SELECT * FROM $table_to_select where stamp>$time_for_select limit 1");
	#print "SELECT * FROM $table_to_select where stamp>$time_for_select limit 1\n";
	$sth->execute;

	@nr = $sth->fetchrow();
	if ($#nr<1) {
		$temp=$temp."$host ";
		$nr_ifs_not_collecting+=1;
	}
	$sth->finish();
	$nr_count=$nr_count+1;
}

$time_in_hours=$TIME_LAST_COLLECT/60/60;
if ($nr_ifs_not_collecting>0) {
	print "CRITICAL - $nr_ifs_not_collecting hosts nas ultimas $time_in_hours horas sem coleta de utilizacao de rede - $temp\n";
	exit(2);
}
print "OK - Utilizacao de rede nas ultimas $time_in_hours horas OK\n";
exit(0);

sub gen_hostname {
	($hostname)=@_;
	
	@letters=split(//,$hostname);
	$new_hostname="";
	foreach $letter (@letters) {
		if ($letter eq "-") {
			$new_hostname=$new_hostname."_";
		}
		else {
			$new_hostname=$new_hostname.$letter;
		}
	}
	return($new_hostname);
}
