#!/opt/bcs/bin/perl -w
#
# Robert Moss, coding@mossko.com
#
# Requires:
# Crypt::SSLeay
# LWP::UserAgent

#
# http://nagiosplug.sourceforge.net/developer-guidelines.html#PLUGOUTPUT
#

use strict;
use LWP::UserAgent;
use Getopt::Long;
use Time::HiRes qw ( time );

use lib "/usr/local/nagios/libexec";
use utils qw($TIMEOUT %ERRORS &print_revision &support);
our $TIMEOUT;

# debug
my $debug           =   0;

# HTTP status
my $status          =   0;
my $status_line     =   "";
my $contentlength   =   0;
my $response        =   '';

# For timings
my $time_start      =   0;
my $time_finish     =   0;
my $time_taken      =   0;

my $proto           =   '';



my $http_req = LWP::UserAgent->new (
    agent   => 'Nagios/HTTPCheck/1',
    timeout => 30,
    );


my ($opt_V,  $opt_h,  $opt_p,  $opt_u,  $opt_v,  $opt_t);
    $opt_V = $opt_h = $opt_p = $opt_u = $opt_v = $opt_t = '';

Getopt::Long::Configure('bundling');
GetOptions(
        "V"   => \$opt_V,   "version"   => \$opt_V,
        "h"   => \$opt_h,   "help"      => \$opt_h,
        "p=i" => \$opt_p,   "port=i"    => \$opt_p,
        "u=s" => \$opt_u,   "url=s"     => \$opt_u,
        "v+"  => \$debug,   "verbose+"  => \$debug,
        "t=s" => \$opt_t,   "type=s"    => \$opt_t,
);


my $url         =   $opt_u;

### Warning and Critical times can be entered


# Version
if ($opt_V) {
    print_version();
    exit 0;
}
# Help
elsif ($opt_h) {
    print_help();
    exit 0;
}

#if (not defined $opt_t or $opt_t eq "") {
#   print "No timeout specified!";
#   print STDERR "No timeout specified!";
#   exit $ERRORS{'UNKNOWN'};
#}
if (not defined $url or $url eq "") {
    print "Missing URL!\n";
    print STDERR "Missing URL!\n";
    exit $ERRORS{'UNKNOWN'};
}

if ($url =~ /http\:\/\//)       { $proto = 'HTTP';  }
elsif ($url =~ /https\:\/\//)   { $proto = 'HTTPS'; }
else                            { $proto = '???';   }

debug(1,"Timeout set at $TIMEOUT, setting alarm\n");

# Set timeout so it doesn't hang nagios
$SIG{'ALRM'} = \&bail;
alarm($TIMEOUT);


# here is where we get down to the business
$time_start = time();                           # time start
if ($opt_t eq 'get') {
    $response = $http_req->get($url);           # the request, should be get or head
    debug(1,"Setting request type to GET");
} else {
    $response = $http_req->head($url);          # the request, should be get or head
    debug(1,"Setting request type to HEAD");
}
$time_finish = time();                          # time end
$time_taken = sprintf('%02f', ( $time_finish - $time_start ) );


$response->status_line =~ /(\d\d\d).*/g;
$status = $1 or 0;
$status_line = $response->status_line;
$contentlength = length($response->content);



debug(1,"Response: $status");
debug(1,"Time taken: $time_taken for $contentlength bytes");


if ( $status == 200 ) {
    print "$proto OK - $opt_t $url Status $status_line: loaded $contentlength bytes in $time_taken seconds\n";
    exit $ERRORS{'OK'};
}
elsif ( $status >= 500 ) {
    print "$proto NOTOK - $opt_t $url Status $status_line: loaded $contentlength bytes in $time_taken seconds\n";
    exit $ERRORS{'CRITICAL'};
}
elsif ( $status >= 400 ) {
    print "$proto NOTOK - $opt_t $url Status $status_line: loaded $contentlength bytes in $time_taken seconds\n";
    exit $ERRORS{'CRITICAL'};
}
elsif ( $status == 302 ) {
    print "$proto OK - $opt_t $url Status $status_line: loaded $contentlength bytes in $time_taken seconds\n";
    exit $ERRORS{'WARNING'};
}
elsif ( $status >= 300 ) {
    print "$proto OK - $opt_t $url Status $status_line: loaded $contentlength bytes in $time_taken seconds\n";
    exit $ERRORS{'WARNING'};
}
else {
    print "$proto NOTOK - $opt_t $url Status $status_line: loaded $contentlength bytes in $time_taken seconds\n";
    exit $ERRORS{'CRITICAL'};
}




###############################################################################
sub debug {
    my ($lvl,$msg) = @_;
    if ( defined $debug and $lvl <= $debug ) {
        chomp($msg);
        print localtime(time) .": $msg\n";
    }
    return 1;
}

###############################################################################
sub print_version {
    print "Version 1.. now go away\n";
    exit 0;
}

###############################################################################
sub print_help {
    print <<END;

    -V or --version
        Shows version

    -h or --help
        Shows help (this screen)

    -p NN or --port=NN
        Sets the TCP port

    -u <url> or --url=<url>
        Sets the URL

    -v or --verbose
        Sets verbosity/debugging

    -t <get/head> or --type=<get/head>
        Sets the HTTP request type, HEAD or GET

END



    exit 0;
}

###############################################################################
# Just in case of problems, let's not hang Nagios
sub bail {
        print ("ERROR: No response from web server\n");
        exit $ERRORS{"UNKNOWN"};
}

