#!/usr/bin/perl

use DBI;
use strict;

our $host = $ARGV[0];
our $service = $ARGV[1];

sub _main {
	my $dbh = DBI->connect ("dbi:mysql:dbname=opdoc;host=127.0.0.1","root","oppass");
	die "Cannot connect to database!\n" if (not defined $dbh);

	my $sth = $dbh->prepare("select descricao, DATE_FORMAT(dataproxrevisao, \"\%d/\%m/\%Y\"), DATEDIFF(dataproxrevisao,CURDATE()) as diff, OID_PROCESSOSCRITICOS, texto from PROCESSOSCRITICOS where hostname='$host' and servicedescription='$service' order by dataproxrevisao");
	die "Cannot prepare statement: $DBI::errstr\n" if (not defined $sth);

	$sth->execute;
        my $zrfound = 0;
	my $counter = 0;
	my $critical = 0;
	my $msg = "";
	while (my ($descr,$data,$diff,$oid, $texto) = $sth->fetchrow()) {
		$counter++;
		my $time = 15;
		$msg .= "$descr $data ";
		if ($diff <= $time) {
			$zrfound = 1;
			$critical = 1 if ($diff <= 0);
		} else {
			next;
		}
	}

	if ($counter == 0) {
		&_usage();
	}

	if ($critical == 1) {
		print "CRITICAL - Documentacao encontrada( $msg).\n";
		exit(2);
	}

        if( $zrfound == 1 ){
                print "WARNING - Documentacao encontrada( $msg).\n";
                exit(1);

        } else {
                print "OK - Nenhuma Documentacao encontrada.\n";
                exit(0);
        }

}

sub _usage {

	print "Documentacao nao encontrada!\n";
	print "Usage: $0 <host> <servico>\n";
	exit(2);
}


&_main;
