#!/usr/bin/perl
#check_comunika
#Description:
#       Check credits comunika
#       
#Author:
#       Fernando Rocha (fernando.rocha@opservices.com.br)
#
#Version:
#       1.0 28-12-2010: Initial release

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.0";
our $name = $NAME;
our $path = $PATH;
our ($opt_version, $opt_help, $opt_debug, $opt_user, $opt_pass, $opt_warn, $opt_crit);

our $usage ='
Usage: '. $0 .' [OPTION]...
Check comunika credits.

General Options:
        -U, --username		Comunika username
        -P, --password		Comunica password
	-w, --warning		
	-c, --critical		

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

        logger($opt_debug, "----- Access Info -----");
        logger($opt_debug, "User: $opt_user");
        logger($opt_debug, "Pass: $opt_pass");
	
	# 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");

	# Get credit
	logger($opt_debug, "----- Get credit -----");
	my $return = get_cred($ua,$cookie_jar);

	if ($return < $opt_crit){
		print "Credits: $return |credit=$return;$opt_warn;$opt_crit;\n";
		exit(2);
	}

	if ($return < $opt_warn){
		print "Credits: $return |credit=$return;$opt_warn;$opt_crit;\n";
		exit(1);
	}

	print "Credits: $return |credit=$return;$opt_warn;$opt_crit;\n";
	exit(0);

}
#---------------------------------------------------------------------------
sub get_cred{
	my $ua = shift;
	my $cookie_jar = shift;

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

	my $param;
	$param .= "?linesep=0";
	$param .= "&user=$user";
	$param .= "&pass=$pass";

	my $path = "/3.0/user_credit.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());

	my @content = split (/\n/,$response->as_string());
	my $cred = 0;

	foreach (@content){
		#print "->$_";
		if ($_ =~ /^([0-9]+\.[0-9])/){
			#print "X - $1\n";
			$cred = $1;
		}	
	}
	return($cred);
		
}
#---------------------------------------------------------------------------
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,
                'U|user=s'              => \$opt_user,
                'P|password=s'          => \$opt_pass,
                'c|critical=i'         	=> \$opt_crit,
                'w|warning=i'          	=> \$opt_warn,
        )or do {
                usage($usage);
                exit();
        };

        if ($opt_version) {
                print_version($version);
        }

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

	if ((!$opt_user) || (!$opt_pass) || (!$opt_warn) || (!$opt_crit)){
		usage($usage);
	} 

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