#!/usr/bin/perl
#notify_by_comunika
#Description:
#       OpMon Notifycation via comunika
#       
#Author:
#       Fernando Rocha (fernando.rocha@opservices.com.br)
#
#Update:
#	Estevan Ramalho (estevan.ramalho@opservices.com.br)
#
#Version:
#       1.0 14-12-2010: Initial release
#	1.1 27-05-2012: Include serviceoutput
#	1.2 19-08-2013: Generic Adjusts.

BEGIN { push @INC,"/usr/local/opmon/libexec";}

# Perl Modules
use strict;
use Getopt::Long;
use POSIX;
#use opservices;
use LWP::UserAgent;
use HTTP::Request;
use HTTP::Cookies;

# Setting environment
$ENV{"USER"}="opuser";
$ENV{"HOME"}="/home/opuser";
# Username: opservices
# Password: jcxxoo

# globlal variables
our $version = "1.2";
#our $name = $NAME;
#our $path = $PATH;
our $name = "notify_by_comunika";
our $path = "/usr/local/opmon/libexec/opservices/";
our ($opt_version, $opt_help, $opt_debug, $opt_user, $opt_pass, $opt_from, $opt_to, $opt_detail, $opt_env);
our ($opt_date, $opt_Ntype);
our ($opt_Hname, $opt_Haddr, $opt_Hstate);
our ($opt_Sname, $opt_Sstate);

our $usage ='
Usage: '. $0 .' [OPTION]...
Send a SMS notification via comunika, for hosts and services.

General Options:
        -e, --env		Get data from environmental variables (service|host|test)
        -U, --username		Comunika username
        -P, --password		Comunica password
        -f, --from		Sender number		
        -t, --to		Recipient number with the DDD and DDI		

Extra Options:

        -h, --help              Display this help and exit
        -v, --version           Output version information and exit

        -d, --debug     	1 = Debug
                        	2 = Generate log file

';

sub main {
        # Get options
        getOptions();

	logger($opt_debug, "----- Starting -----");
	# Get the OpMon Environmental Variables
	get_env();

	logger($opt_debug, "----- Environmental Variables -----");
	logger($opt_debug, $opt_Ntype); 
        logger($opt_debug, $opt_date);
        logger($opt_debug, $opt_Hname);

        logger($opt_debug, "----- Access Info -----");
        logger($opt_debug, "User: $opt_user");
        logger($opt_debug, "Pass: $opt_pass");
	
	# Get the Ticket Description
	my $msg = get_msg();
	logger($opt_debug, "Message:\n$msg");

	# Make the HTTP connection
	my $ua  = LWP::UserAgent->new;
	my $cookie_jar = HTTP::Cookies->new;
	my $agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9) Gecko/2008052912 Firefox/3.0";
	$ua->agent("$agent");

	# Send Message
	logger($opt_debug, "----- Send Message -----");
	my $return = send_msg($ua,$cookie_jar,$msg);

	if (!$return){
		print "OK - The message has been sent\n";
		exit (0);
	}else{
		print "Critital - The message could not be sent\n";
		exit (2);
	}

}
#---------------------------------------------------------------------------
sub send_msg{
	# HTTP connection parameters
	my $ua = shift;
	my $cookie_jar = shift;
	my $msg = shift;

	my $id = time();
	my $sch;
	my $user = $opt_user;
	my $pass = $opt_pass;
	my $cmsg = "$opt_from\t$opt_to\t$sch\t$msg\t$id";

	$user =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
	$pass =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
	$cmsg =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;

	logger($opt_debug, "CodedMsg: $cmsg");

	my $param;
	$param .= "?testmode=0";
	$param .= "&linesep=0";
	$param .= "&user=$user";
	$param .= "&pass=$pass";
	$param .= "&messages=$cmsg";
	
	my $path = "/3.0/user_message_send.php";
	my $url = "https://cgi2sms.com.br$path$param";
	logger($opt_debug, "Url: $url");

	# Login URL
	my $request = new HTTP::Request GET => "$url";
	$cookie_jar->add_cookie_header($request);
	my $response = $ua->request($request);
	$cookie_jar->extract_cookies($response);
	my $return = $response->content;

	logger($opt_debug, "Response:".$response->as_string());

	check_response ($response->as_string());

	if ($response->as_string() =~ /00 $opt_to/){
		return(0);
		
	} else {
		return(1);
	}

} 
#---------------------------------------------------------------------------
sub check_response{
	my $response = shift;

	#verify existance of string in response
	if ($response =~ /HTTP\/1.(0|1) (1|2|3)/i) {  
#		print "Passed HTTP Response Code Verification (not in error range)\n";
		return (1);
	}else{
		#this is true if an HTTP response returned 
		$response =~ /(HTTP\/1.)(.*)/i;
		if ($1) {
			print "Critical - Failed HTTP Response Code Verification ($1$2)\n";
			exit(2);

		#no HTTP response returned.. could be error in connection, bad hostname/address, or can not connect to web server
	        }else {
			print "Critical - Failed - No Response \n";
			exit(2);
		}
	}

	return (1);
}
#--------------------------------------------------------------------------
sub getOptions {  #command line options

        Getopt::Long::Configure('bundling');
        GetOptions(
                'v|version'             => \$opt_version,
                'h|help'                => \$opt_help,
                'd|debug=i'             => \$opt_debug,
                'e|env=s'               => \$opt_env,
                'f|from=s'              => \$opt_from,
                't|to=s'          	=> \$opt_to,
                'U|user=s'              => \$opt_user,
                'P|password=s'          => \$opt_pass,
        )or do {
                usage($usage);
                exit();
        };

        if ($opt_version) {
               print usage("$name version: $version\n"); 
        }

        if ($opt_help){
                usage($usage);
	}

	if ((!$opt_to) || (!$opt_from) || (!$opt_user) || (!$opt_pass) || ($opt_env !~ /host|service|test/)){
		usage($usage);
	} 

        if (($opt_debug) and ($opt_debug !~/1|2/)){
                usage("Option Missing:\t-d|--debug\t(1|2)\n");
        }

}
#--------------------------------------------------------------------------
sub get_env(){

        logger($opt_debug,"Loading Environmental Variables");

	if ($opt_env =~ /test/){

	        $opt_Ntype  = 'NAGIOS_NOTIFICATIONTYPE';
	        $opt_date   = 'NAGIOS_SHORTDATETIME';
	        $opt_Hname  = 'NAGIOS_HOSTNAME';

	        $opt_Haddr  = 'NAGIOS_HOSTADDRESS';
                $opt_Hstate = 'NAGIOS_HOSTSTATE';

                $opt_Sname  = 'NAGIOS_SERVICEDESC';
                $opt_Sstate = 'NAGIOS_SERVICESTATE';
		$opt_detail = 'NAGIOS_SERVICEOUTPUT';

	} else {

        	$opt_Ntype = $ENV{'NAGIOS_NOTIFICATIONTYPE'};
        	$opt_date  = $ENV{'NAGIOS_SHORTDATETIME'};
        	$opt_Hname = $ENV{'NAGIOS_HOSTNAME'};

        	if ($opt_env =~ /host/){
        		$opt_Haddr  = $ENV{'NAGIOS_HOSTADDRESS'};
        	        $opt_Hstate = $ENV{'NAGIOS_HOSTSTATE'};
        	}else{
        	        $opt_Sname  = $ENV{'NAGIOS_SERVICEDESC'};
        	        $opt_Sstate = $ENV{'NAGIOS_SERVICESTATE'};
			$opt_detail = $ENV{'NAGIOS_SERVICEOUTPUT'};
        	}
	}

        return;
}
#--------------------------------------------------------------------------
sub get_msg {
	my $msg;
	
	if ($opt_env =~ /host/){
		$msg = $opt_Ntype."\rHost: ".$opt_Hname."\rState: ".$opt_Hstate."\rAddress: ".$opt_Haddr."\rDate/Time: ".$opt_date;
	}elsif ($opt_env =~ /service/){
		$msg = $opt_Ntype."\rHost: ".$opt_Hname."\rService: ".$opt_Sname."\rState: ".$opt_Sstate."\rDetail: ".$opt_detail."\rDate/Time: ".$opt_date;
	}else {
		$msg = $opt_Ntype."\rHost: ".$opt_Hname."\rService: ".$opt_Sname."\rState: ".$opt_Sstate."\rDetail: ".$opt_detail."\rDate/Time: ".$opt_date;
	}

	return ($msg);
}
#--------------------------------------------------------------------------
sub logger {
        my $opt = shift;
        my $msg = shift;
        my $log = "$path/$name.log";
        my $date = strftime("%d/%m/%Y - %H:%M:%S",localtime);
        if ($opt == 1){
                        print "$msg\n";
        }elsif ($opt == 2) {
                        open(LOG, ">>$log");
                        print LOG "$date => $msg\n";
                        close(LOG);
        }
}

#--------------------------------------------------------------------------
sub usage {
        print @_;
        print "Send email to suporte\@opservices.com.br if you have questions\nregarding use of this software. To submit patches or suggest improvements,\nsend email to suporte\@opservices.com.br.\nPlease include version information with all correspondence (when possible,\nuse output from the --version option of the plugin itself).\n";
        exit (3);
}
#--------------------------------------------------------------------------
&main;
