#!/usr/bin/perl 
#Author:
#        Otavio Honorio (otavio.honorio@opservices.com.br)
use strict;
use Getopt::Long;
use POSIX;
use File::Basename;
use Switch;
use DBI;
# Setting environment
$ENV{"USER"}="opuser";
$ENV{"HOME"}="/home/opuser";
# Global variables
our $name = basename($0, ".pl");
our $path = "/usr/local/opmon/libexec";
our ($oHelp, $oVerbose, $oWarn, $oCrit, $oDatabase, $oHost, $oUser, $oPass, $oMode);
#--------------------------------------------------------------------------------------
sub main {

     getoption();
	quit("Invalid option, use host or service.",3) if ($oMode !~ /^host$|^service$/);

	my $unavail = mysql("SELECT count(*) as value FROM $oMode\_status WHERE current_state <> 0");
	my $avail = mysql("SELECT count(*) as value FROM $oMode\_status WHERE current_state = 0");
	my $total = $unavail + $avail;
	quit("Unable to check",2) if ((!defined($total)) or (!defined($unavail)) or (!defined($avail)));

	my $PercUnavail = sprintf('%0.2f',(($unavail * 100)/$total));
	my $PercAvail = sprintf('%0.2f',(($avail * 100)/$total));

	my $vWarn = sprintf('%0.0f',(($oWarn / 100)*$total));
	my $vCrit = sprintf('%0.0f',(($oCrit / 100)*$total));

	my $code = imetric($PercAvail);
	my $perf = "available=$PercAvail%;$oWarn;$oCrit;0;100 unavailable=$PercUnavail%;".(100 - $oWarn).";".(100 - $oCrit).";0;100 value_available=$avail;$vWarn;$vCrit;0;$total value_unavailable=$unavail;".($total - $vWarn).";".($total - $vCrit).";0;$total";
	quit("Available: $PercAvail% / $avail - Unavailable: $PercUnavail% / $unavail | $perf",$code);
}
#--------------------------------------------------------------------------------------
sub mysql {
	my $query = shift;
	my ($dbh, $sth, $date);

	$dbh = DBI->connect("DBI:mysql:database=$oDatabase;host=$oHost","$oUser", "$oPass",{'RaiseError' => 1});
	$sth = $dbh->prepare($query);
	$sth->execute() or quit("Error executing query!",3);
        $date = $sth->fetchrow_array;
        $sth->finish();

	return $date;
}
#--------------------------------------------------------------------------------------
sub imetric {
        my $value = shift;
        if ($value <= $oCrit) { return 2
        }elsif ($value <= $oWarn) { return 1
        }elsif ($value > $oCrit) { return 0
        }else{ quit("Unable to check",3); }
}
#--------------------------------------------------------------------------------------
sub metric {
        my $value = shift;
        if ($value >= $oCrit) { return 2
        }elsif ($value >= $oWarn) { return 1
        }elsif ($value < $oWarn) { return 0
        }else{ quit("Unable to check",3); }
}
#--------------------------------------------------------------------------------------
sub quit {
	my $mgs = shift;
	my $code = shift;
	print $mgs,"\n";
	exit($code);
}
#--------------------------------------------------------------------------------------
sub getoption  {
	Getopt::Long::Configure('bundling');
	GetOptions(
            'c|critical=f' => \$oCrit,
            'h|help' => \$oHelp,
            'D|database=s' => \$oDatabase,
            'u|username=s' => \$oUser,
            'p|password=s' => \$oPass,
            'H|host=s' => \$oHost,
            'm|mode=s' => \$oMode,
            'v|verbose=i' => \$oVerbose,
            'w|warning=f' => \$oWarn,
        );
	if($oHelp){
		printUsage();
		exit(3);
	}
	# Variables defined
	$oHost = "127.0.0.1" if (!defined($oHost));
	$oDatabase = "opmon4" if (!defined($oDatabase));
	$oUser = "root" if (!defined($oUser));
	$oPass = "" if (!defined($oPass));
	
	if ((!$oWarn) or (!$oCrit)){
		printUsage();
		exit(3);
	}
}
#--------------------------------------------------------------------------------------
sub logger {
        my $msg = shift (@_);
        my $log = "$path/$name.log";
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
        $wday++;
        $yday++;
        $mon++;
        $year+=1900;
        $isdst++;
        open(LOG, ">>$log");
        printf LOG ("%02i/%02i/%i - %02i:%02i:%02i => %s\n",$mday,$mon,$year,$hour,$min,$sec,$msg);
        close(LOG);
}
#--------------------------------------------------------------------------------------
sub printUsage {
       print <<EOB
Usage: $name.pl [OPTION]...

-h, --help
-H, --host 		* Default: 127.0.0.1
-D, --database 		* Default: opmon4
-u, --username 		* Default: root
-p, --password 		* Default: not defined
-m, --mode 		* Need inform: host or service
-c, --critical 		* Need inform
-w, --warning 		* Need Inform

EOB
}
#--------------------------------------------------------------------------------------
&main;
