#!/usr/bin/perl
#
#Description:
#	Check the host's perfparse tables
#
#       This plugin must be executed using the command sudo.
#       Before run, insert the follow line at /etc/sudoers:
#       
#	opuser  ALL=(ALL)       NOPASSWD: /usr/local/opmon/libexec/check_opmon_perfparse.pl
#
#Author:
#       Fernando Rocha (fernando.rocha@opservices.com.br)
#
#Version:
#       1.1:    Added the CentOs compatibility
#		Change the password parameter to optional

use strict;
use Getopt::Long;
use POSIX;
use File::Basename;
use DBI;

# Setting environment
$ENV{"USER"}="opuser";
$ENV{"HOME"}="/home/opuser";

# globlal variables
our $name = basename($0, ".pl");
our $version = "1.1";
our $path = "/usr/local/opmon/libexec";
our $temp_log = "$path/$name.log";
our ($opt_version, $opt_help, $opt_debug , $opt_host, $opt_user, $opt_pass);

our $perfparse_dir = "/var/lib/mysql/opperf";

our $problem = 0;
our $msg;

sub main {
        # Get options
        getOptions();

        logger("----- INICIO DO SCRIPT -----");

        # CentOs compatibility
        if (!-d $perfparse_dir){
                $perfparse_dir = "/var/lib/mysql/opperf";
        }

	# Read the perfparse dir
	opendir(DIR,$perfparse_dir)
	or do {
		print "$perfparse_dir: $!\n";
		exit (2);
	};
	my @perfparse_db_files = readdir(DIR);
	closedir(DIR); 

	# Connect to the Data Base
	my $dbh = DBI->connect ( "dbi:mysql:dbname=opperf;host=$opt_host", $opt_user, $opt_pass) 
	 or do{
		print "Cannot connect to database: $DBI::errstr\n";
		exit (2);
		};

	my $host_db;
	my $row;

	foreach my $db_file (@perfparse_db_files){
	
		#perfdata_service_bin_www_clion_net.ibd
		if ($db_file =~ /(service_perf_.+)\.ibd/){
			$host_db = $1;
		
			logger(":: $host_db");
			# Insert
#			my $sql_insert="INSERT INTO $host_db (host_name,service_description,metric,ctime,value,warn,critical,state) VALUES ('check_opmon_perfparse','check_opmon_perfparse','check_opmon_perfparse','1970-01-01 00:00:00',0,0,0,0)";
			my $sql_insert="INSERT INTO $host_db (service_id,metric_id,entry_time,perf_value,warning,critical) VALUES ('0','0','1970-01-01 00:00:00',0,0,0)";

			my $sth = $dbh->prepare("$sql_insert")
	 		or do{
			 	print "Cannot prepare statement: $DBI::errstr\n";
				exit (2);
				};
		
			$row = $sth->execute
			or do {
				$msg = "<br>$host_db";
				$problem++;
				$sth->finish;
				next;
				#print "Cannot execute the query $sth->errstr\n";
				#exit(2);
				};
			logger("\tInsert: $row");
			$sth->finish;

			# Delete 
			my $sql_delete="DELETE FROM $host_db WHERE service_id='0'";

			my $sth = $dbh->prepare("$sql_delete")
	 		or do{
			 	print "Cannot prepare statement: $DBI::errstr\n";
				exit (2);
				};

			$row = $sth->execute
			or do {
				$msg = "<br>$host_db";
				$problem++;
				#print "Cannot execute the query $sth->errstr\n";
				#exit(2);
				};

			logger("\tDelete: $row");
			$sth->finish;


		}
	
	}

	$dbh->disconnect;

	logger ("-------FIM DO SCRIPT--------");

	if ($problem){
		print "Critical: $problem failed test $msg |failed_test=$problem;;;0;\n";
		exit (2);
	}

	        print "Ok: $problem failed test|failed_test=$problem;;;0;\n";
                exit (0);
}
#--------------------------------------------------------------------------

sub getOptions {  #command line options

        Getopt::Long::Configure('bundling');
        GetOptions(
                'v|version'             => \$opt_version,
                'h|help'                => \$opt_help,
                'd|debug=i'             => \$opt_debug,
                'H|host=s'              => \$opt_host,
                'u|username=s'          => \$opt_user,
                'p|password=s'          => \$opt_pass,

        )or do {
                printUsage();
                exit();
        };

        if ($opt_version) {
                print "$name.pl: $version\n";
                exit();
        }

        if ($opt_help){
                printUsage();
                exit();
        }

        if ((!$opt_host) or (!$opt_user)){
                printUsage();
                exit();
        }


        if (($opt_debug) and (($opt_debug < 1) or ($opt_debug > 2))){
                printUsage();
                exit();
        }

}
#--------------------------------------------------------------------------
sub printUsage {

       print <<EOB

Usage: $0 [OPTION]...
Verify the host's perfparse tables.

General Options:
        -H, --host		OpMon address
        -u, --username		DB username
        -p, --password		User password

Extra Options:

        -h, --help              Display this help and exit
        -v, --version           Output version information and exit

        -d, --debug     1 = Debug
                        2 = Generate log file

EOB

}
#-------------------------------------------------------------------------
sub logger {

        return (0) if (not defined $opt_debug);

        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++;

        if ($opt_debug == 1){
            print "$msg\n";
        }else {
           open(LOG, ">>$log");
           printf LOG ("%02i/%02i/%i - %02i:%02i:%02i => %s\n",$mday,$mon,$year,$hour,$min,$sec,$msg);
           close(LOG);
        }

}
#-------------------------------------------------------------------------

&main;
