#!/usr/bin/perl
#
#Description:
#	Check the tables from deleted hosts
#
#	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_deleted_hosts.pl
#
#Author:
#       Fernando Rocha (fernando.rocha@opservices.com.br)
#       Luis Ferreira  (luis.ferreira@opservices.com.br) Update to versions 1.2 and 1.3
#
#Version:
#       1.1:    Added the CentOs compatibility
#               Change the password parameter to optional
#       1.2:    Added the absolut link at the critical message
#       1.3:    Added the check the truth of html_dir

use strict;
use Getopt::Long;
use POSIX;
use File::Basename;
use DBI;
use Sys::Hostname;
use File::Path;

# 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 ($login, $pass, $uid, $gid);
our ($opt_version, $opt_help, $opt_debug , $opt_host, $opt_user, $opt_pass);

our $perfparse_dir = "/var/local/mysql/var/perfparse";

our $hostname = hostname;
our $html_link_file = "$name.html";
our $html_dir = "/usr/local/opmon/share/custom";
our $html_file = "$html_dir/$html_link_file";
our $html_removed;
our $removed = 0;

sub main {
        # Get options
        getOptions();

        logger("----- INICIO DO SCRIPT -----");

	# CentOs compatibility
        if (!-d $perfparse_dir){
                $perfparse_dir = "/var/lib/mysql/perfparse";
        }
        
        # Check html_dir
	if (!-d $html_dir){
		mkdir($html_dir,0755);
		($login,$pass,$uid,$gid) = getpwnam("apache");
		chown $uid,$gid, $html_dir;
	}

	# 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=perfparse;host=$opt_host", $opt_user, $opt_pass) 
	 or do{
		print "Cannot connect to database: $DBI::errstr\n";
		exit (2);
		};

	my $host_db;
	my $host_name;
	my $class;

	foreach my $db_file (@perfparse_db_files){
	
		#perfdata_service_bin_www_clion_net.ibd
		if ($db_file =~ /(perfdata_service_bin_.+)\.ibd/){
			$host_db = $1;
		
			# get the hostname
			my $sql_hostname="select host_name from $host_db limit 1";

			my $sth = $dbh->prepare("$sql_hostname")
	 		or do{
			 	print "Cannot prepare statement: $DBI::errstr\n";
				exit (2);
				};
		
			$sth->execute
                        or do {
                                print "Cannot execute the query $sth->errstr\n";
                                exit(2);
                                };
			my $host_name = $sth->fetchrow();
			$sth->finish;

			logger (":: $host_name");

			# Get the host status
			my $sql_status="select DATEDIFF(CURDATE(),timestamp) from opmon.host_alert where hostname='$host_name' order by timestamp desc limit 1";

			my $sth = $dbh->prepare("$sql_status")
	 		or do{
			 	print "Cannot prepare statement: $DBI::errstr\n";
				exit (2);
				};

			$sth->execute
                        or do {
                                print "Cannot execute the query $sth->errstr\n";
                                exit(2);
                                };

			my ($host_date_diff) = $sth->fetchrow();
			$sth->finish;

			logger ("\tDateDiff: $host_date_diff");

			# Removed hosts
			if ($host_date_diff){
                                if ($removed%2){
                                        $class = 'statusEven';
                                }else{
                                        $class = 'statusOdd';
                                }

                                $html_removed .= "<tr>\n";
                                $html_removed .= "<td CLASS='$class'>$host_name</td>\n";
                                $html_removed .= "<td CLASS='$class'>$host_db</td>\n";
                                $html_removed .= "<td CLASS='$class'>$host_date_diff</td>\n";
                                $html_removed .= "</tr>\n";

				$removed++;
			}

		}
	
	}

	$dbh->disconnect;

	logger ("-------FIM DO SCRIPT--------");

	if ($removed){
		writeHtml();
		print "Critical: Host Deleted: $removed <a target='_blank' href='https://$hostname/opmon/custom/$html_link_file'><img alt='OpMon Removed Hosts' src='/opmon/images/logos/website.png' border='0' width='20'></a>|host_deleted=$removed;;;0;\n";
		exit (2);
	}

	        print "Ok: Host Deleted: $removed |host_deleted=$removed;;;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 perfparse tables from deleted hosts

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);
        }

}
#-------------------------------------------------------------------------
sub writeHtml {

	open(FILE,">$html_file");
	print FILE "<html>\n";

        print FILE "<head>\n";
        print FILE "<LINK REL='stylesheet' TYPE='text/css' HREF='/opmon/stylesheets/status.css'>\n";
        print FILE "<LINK REL='stylesheet' TYPE='text/css' HREF='/opmon/stylesheets/common.css'>\n";
        print FILE "<LINK REL='stylesheet' TYPE='text/css' HREF='/opmon/stylesheets/opservices.css'>\n"; 
        print FILE "<LINK REL='stylesheet' TYPE='text/css' HREF='/opmon/stylesheets/avail.css'>\n";
        print FILE "<LINK REL='stylesheet' type='text/css' media='screen' href='/opmon/seagull/www/themes/opmon/css/style.php?navStylesheet=SglDefault_TwoLevel&amp;moduleName=slaforslm'/>\n";
        print FILE "</head>\n";
        print FILE "<BODY CLASS='avail'>\n";
        print FILE "<center>\n";

        if ($removed){
                print FILE "<hr>\n";
                print FILE "<font face='Verdana' size='5'><b>Deleted Hosts</b></font>\n";
                print FILE "<hr>\n";
                print FILE "<table border='1' class='infoOpSla'>\n";

                print FILE "<tr>\n";
                        print FILE "<th>Hostname</th>\n";
                        print FILE "<th>Table</th>\n";
                        print FILE "<th>Days Ago</th>\n";
                print FILE "</tr>\n";

                print FILE $html_removed;

		print FILE "\n</table><p>";

        }

	print FILE "<hr>\n<div align='right'>\n<b>OpMon by OpServices</b>\n";
	print FILE "</center>\n";
	print FILE "</body>\n</html>";
	close(FILE);

}

&main;
