#!/usr/bin/perl 
#check_metric.pl
#
#17-07-2012 : Created 
#

use strict;
use Getopt::Long;
use POSIX;
use File::Basename;
use DBI;
use English;

#--------------------------------------------------
# Setting environment
#-------------------------------------------------- 
$ENV{"USER"}="opuser";
$ENV{"HOME"}="/home/opuser";

#--------------------------------------------------
# Global variables
#--------------------------------------------------
our $name = basename($0, ".pl");
our $version = "1.0";
our $path = "/usr/local/opmon/libexec";
our $temp_log = "$path/$name.log";
our $conf_file = "/usr/local/opmon/etc/db.php";
our ($opt_help, $opt_verbose, $opt_version, $opt_warn, $opt_crit);


our ($dbname1,$dbname2,$sth,$out,$query1,$query2,$queryIds,@ServiceId,@ServiceName,$state,@HostName,$opt_filter,$opt_service,$dbuser,$dbpass,$dbhost);
$dbname1 = "opmon4";
$dbname2 = "opcfg";


open( FILE, "$conf_file" );
while(<FILE>) {
   $dbuser = $1 if (m/DBUSER\s*=\s*[\'\"]*([^\'\"]*)[\'\"]*;/);
   $dbpass = $1 if (m/DBPASS\s*=\s*[\'\"]*([^\'\"]*)[\'\"]*;/);
   $dbhost = $1 if (m/DBHOST\s*=\s*[\'\"]*([^\'\"]*)[\'\"]*;/);
}
   close(FILE);


my @metrics = ("", "", ""); # Generate performance data.
my @return = (); # Return to complete performance data.
$opt_warn="1";
$opt_crit="1";
$FORMAT_LINES_PER_PAGE = 25;
$FORMAT_FORMFEED = '';

sub main {

     getoption();
     #LIst Querys
#     $queryIds = "select service_id,service_description from nagios_services";
     if ($opt_filter =~ /ALL/i){
	 $opt_filter = "";
     }
     $queryIds = "select s.service_id,s.service_description,h.host_name from nagios_services s,nagios_hosts h where h.host_id=s.host_id  and host_name like \'\%$opt_filter\%\'";
     $sth = DBConnect($dbname2,$queryIds);
     while (my ($id,$name,$host) = $sth->fetchrow()){

	 push (@ServiceId,$id);
	 push (@ServiceName,$name);
	 push (@HostName,$host);
     }
     my $count = 0;
     my $cnProb = 0;

	if (!$opt_service){

	    print "  ID	 	SERVICE_NAME         	  	        HOSTNAME		METRIC.COLETADAS     REGISTRO BASE\n";
	    print "  --		------------		        	--------		----------------     -------------\n";
	    foreach (@ServiceId){
		$query1 = "select perf_data,current_state from service_status where service_id=$_";
		$query2 = "select count(*) from service_metric where service_id = $_";
		
	       	$sth = DBConnect($dbname1,$query1);
		($out,$state) = $sth->fetchrow();
       		my @perf_data = split (/;/,$out);
		#print "\n\n$perf_data[0]\n";
       		my @metrics;
       		my @parsePerfData;
       		if ($state !=0){
       		    $count++;
       		    next;
       		}
       		foreach (@perf_data){
		    $_ =~ s/ /_/g;
		    $_ =~ s/\//_/g;

       		    my $lines = $& if ($_ =~ m/\S+=/);
       		    push(@parsePerfData,$&) if ($lines =~ m/\w+/);
       		}
       		my $countServiceStatus = scalar (@parsePerfData);
       		$sth = DBConnect($dbname2,$query2);
       		my $countServiceMetrics = $sth->fetchrow();
       		if ($countServiceStatus != $countServiceMetrics){
		    $cnProb++;
       		    write();
       		    format STDOUT = 
     @<<<<<<<       @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<     @<<<<<<<<<<<<<<<<<<<<<<<<<<<    @<<<<        @<<<<
   		$ServiceId[$count], $ServiceName[$count] , $HostName[$count], $countServiceStatus, $countServiceMetrics
.
#   		print "ID $ServiceId[$count]  SERVICE_NAME $ServiceName[$count] HOSTNAME $HostName[$count]\n SERVICE_STATUS - $countServiceStatus SEVICE_METRIC $countServiceMetrics\n";

    	 	}
#   		print "ID $ServiceId[$count]  SERVICE_NAME $ServiceName[$count] HOSTNAME $HostName[$count]\n SERVICE_STATUS - $countServiceStatus SEVICE_METRIC $countServiceMetrics\n";

	 	$count++;
	    }
	    print "TOTAL DE REGISTROS: $cnProb\n";
	}else{
	print "METRIC_ID	        HOST_ID              SERVICE_ID	       	METRIC     \n";
	print "---------        	------------          --------	  	------     \n";
	    my $query1 = "select metric_id,host_id,service_id,metric,unit from service_metric where service_id = $opt_service";
	    $sth = DBConnect($dbname2,$query1);
	    while (my ($metric_id,$host_id,$service_id,$metric,$unit) = $sth->fetchrow()){
		print "$metric_id\t\t$host_id\t\t\t$service_id\t\t$metric\t\t\n";
	    }
	    print "\n===========          HELP:             ===========\n";
	    print "\nPara remocao acesse a base do OpCfg:\n\t #  mysql> use opcfg\n\nExecute o comando para deletar a metrica:\n\t# mysql> delete from service_metric where metric_id=METRIC_ID\n";
	    print "\nATENCAO!!! Use apenas se tiver certeza que quer deletar a metricai!!!\n\n";

	}

     




}
#--------------------------------------------------------------------------------------
sub DBConnect {
	my $dbname = shift;
	my $query = shift;
	my $sth;
	my $dbh = DBI->connect ("dbi:mysql:dbname=$dbname;host=$dbhost", "$dbuser", "$dbpass")
    	    or print_error ("Nao foi possivel efetuar a conexao na base.");
#my $sql ="select perf_data from service_status where host_id = 6651 and service_id=174211";
   	my $sql = $query;
   	$sth = $dbh->prepare("$sql")
   	    or die "Cannot prepare statement: $DBI::errstr\n" if (not defined $sth);
   	$sth->execute;
	return ($sth);



}


#--------------------------------------------------------------------------------------
sub getoption  {
     Getopt::Long::Configure('bundling');
     GetOptions(
            'V|version'               => \$opt_version,
            'H|host=s'               => \$opt_filter,
            'S|service=s'               => \$opt_service,
            'c|critical=f'              => \$opt_crit,
            'h|help'                  => \$opt_help,
            'v|verbose=i'               => \$opt_verbose,
            'w|warning=f'               => \$opt_warn,
        );

     if($opt_help){
             printHelp();
              exit(1);
     }

     if($opt_version){
             print "$name.pl - '$version'\n";
             exit(1);
      }

     if(!$opt_verbose){
             $opt_verbose = 0;
     }

     if ((!$opt_filter)){
             printUsage();
              exit(1);
     }

}

#--------------------------------------------------------------------------------------
sub logger {

        return (0) if (not defined $opt_verbose);

        my $msg = shift (@_);
        my $perf = "";
        my $log = "$path/$name.log";
        my $counter = 0;

        foreach(@metrics){
		$perf .= "$_=$return[$counter];$opt_warn;$opt_crit;; ";
	   	$counter++;
        }
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
        $wday++;
        $yday++;
        $mon++;
        $year+=1900;
        $isdst++;
        if ($opt_verbose == 0){
		if (@metrics){
    			 print "$msg | $perf\n";
		}
	   	else{
		       	 print "$msg\n";
	    	}
	    }
	    elsif ($opt_verbose == 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 printUsage {
       print <<EOB
Usage: $name.pl [OPTION]...

         -h, --help         Show help
         -H, --host	   Insira o nome do host para consulta de um expecifico ou ALL para todos
			   ex:  ./check_metric.pl -H oprobot-win2

	 -S, --service	   Insira o ID do servico para visualizar todas as metricas
			   ex: ./check_metric.pl -H oprobot-win2 -S 184881

EOB
}
#--------------------------------------------------------------------------------------

sub printHelp {
		my $help = <<'HELP';

Script destinado a limpeza de metricas no OpMon.
Este problema ocorre quando eh alterado algum nome de metrica nos dados de performance
e nao eh removido da base.
O script compara a quantidade de metricas que o servico esta enviando ao OpMon com 
a quantidade total que existe na base.

Sintaxe:
         -H, --host        Insira o nome do host para consulta de um expecifico ou ALL para todos
                           ex:  ./check_metric.pl -H oprobot-win2

         -S, --service     Insira o ID do servico para visualizar todas as metricas
                           ex: ./check_metric.pl -H oprobot-win2 -S 184881

HELP
		print $help;
}
#--------------------------------------------------------------------------------------

sub print_error {
		my $msg = shift;
		print "Critical - $msg\n";
		exit (2);
}
#--------------------------------------------------------------------------------------

&main


