#!/usr/bin/perl
#Description:
#	Check the host's perfparse table size
#
#       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_table_size.pl
#
#Author:
#	Fernando Rocha (fernando.rocha@opservices.com.br)
#       Luis Ferreira (luis.ferreira@opservices.com.br)
#Version:
#	1.1:	Added the CentOs compatibility
#		Change the password parameter to optional
#       1.2:	Added check the truth of html_dir;
use Getopt::Long;
use POSIX;
use File::Basename;
use DBI;
use Sys::Hostname;

# 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 $log_dir = "$path/opmon_table_size";
our $perfparse_dir = "/var/lib/mysql/opperf";

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_problem;
our $problem = 0;

sub main {
        # Get options
        getOptions();

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

	# Check log_dir
	if (! -e $log_dir){
		mkdir($log_dir)
		or do {
			print "$log_dir: $!\n";
			exit (2);
		};
	}

        # CentOs compatibility
        if (!-d $perfparse_dir){
                $perfparse_dir = "/var/lib/mysql/opperf";
        }
        
   	 # 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); 

	my $host_db;
	my $class;

	foreach my $db_file (@perfparse_db_files){
	
		#perfdata_service_bin_www_clion_net.ibd
		if ($db_file =~ /(service_perf_.+)\.ibd/){
			$host_db = $1;

			logger (":: $db_file");

			# get the DB size
			my @db_stat = stat ("$perfparse_dir/$db_file");
			my $db_size = $db_stat[7];

			logger ("\tFile: $db_file");
			logger ("\tSize: $db_size");

			# Compare the last size
			open (LOG,"$log_dir/$host_db.log");
			my $last_db_size = <LOG>;
			close (LOG);

		
			logger ("\tOld Size: $last_db_size");

			if ($last_db_size > $db_size){

				$last_db_size = $last_db_size/1024/1024;
				$db_size = $db_size/1024/1024;				
				if ($problem%2){
					$class = 'statusEven';
				}else{
					$class = 'statusOdd';
				}

				$html_problem .= "<tr>\n";
                                $html_problem .= "<td CLASS='$class'>$db_file</td>\n";
                                $html_problem .= "<td CLASS='$class'>$last_db_size</td>\n";
                                $html_problem .= "<td CLASS='$class'>$db_size</td>\n";
				$html_problem .= "</tr>\n";

				$problem++;
				next;
			}

			open(LOG,">$log_dir/$host_db.log")
		        or do {
        		        print "$log_dir/$host_db.log: $!\n";
                		exit (2);
        		};
			print LOG $db_size;
			close(LOG);

		}
	
	}

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

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

	        print "Ok: Table Size Problem: $problem|table_problem=$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 table size.

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 ($problem){
                print FILE "<hr>\n";
	        print FILE "<font face='Verdana' size='5'><b>Table Size Problem</b></font>\n";
	        print FILE "<hr>\n";
	        print FILE "<table border='1' class='infoOpSla'>\n";

		print FILE "<tr>\n";
			print FILE "<th>Table File</th>\n";
			print FILE "<th>Old Size MB</th>\n";
			print FILE "<th>New Size MB</th>\n";
		print FILE "</tr>\n";

		print FILE $html_problem;

		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;
