#!/usr/bin/perl

#---------------------------------------------------------------
# See ../Config/realhttp for documentation.
#
# Kevin O'Donnell
# Vancouver, BC, Canada
# kevin_odonnell@telus.net
#
#---------------------------------------------------------------

package Monitor::realhttp;

require 5.002;
require Exporter;

use strict;
use LWP::UserAgent;

@Monitor::realhttp::ISA = qw(Exporter Monitor::Monitor);

sub new
{
    my ($this, $timeout) = @_;
    my  $class = ref($this) || $this;
    my  $self = {};

	print "realhttp::new()\n" if( $BigSister::common::dl>3 );

    bless($self, $class);
	$self->{htable} = [];
    return($self);
}

sub add_url {
	my $self = shift;
	my $url = shift;
	my $item = shift;
	my $greppos = shift;
	my $grepneg = shift;
	my $user = shift;
	my $pass = shift;

	print "realhttp::add_url($url,$item,$greppos,$grepneg,$user,$pass)\n"
		if( $BigSister::common::dl>3 );

	push(@{ $self->{htable} },[$url,$item,$greppos,$grepneg,$user,$pass]);

	return(1);
}

sub check {
 	my $self = shift;

	print "realhttp::check()\n" if( $BigSister::common::dl>3 );

 	# create a new UserAgent that will handle the HTTP(S) request
 	my $ua = new LWP::UserAgent;
 	my $check;

	#
	# iterate through each URL we are supposed to check
	#
 	foreach $check (@{ $self->{htable} }) {
 		my ($url,$item,$greppos,$grepneg,$user,$pass) = @{$check};
		my $url_status;

		print "realhttp::check(url:$url, item:$item, greppos:$greppos, ".
			"grepneg:$grepneg user:$user pass:$pass)\n" if ( $BigSister::common::dl>3 );

		my $req;
		if ($user) {
			# build headers
			my $header = new HTTP::Headers;
			$header->authorization_basic($user,$pass);

			# build the request
	 		$req = new HTTP::Request( GET => $url , $header);
		} else {
			# build the request
	 		$req = new HTTP::Request( GET => $url );
		}

 		# execute the request
 		my $result;
		eval {
		    $result = $ua->request($req);
		};

 		if ($result && $result->is_success) {
			# the page was successfully retrieved from the server

			if ($result->content() !~ /$greppos/) {
				# the content of the result did not match the regular expression
				$url_status .= "FAILED: did not find $greppos ";
			}
			if (($result->content() =~ /$grepneg/) && ($grepneg)) {
				# the content of the result matched the regular expression
				$url_status .= "FAILED: found $grepneg ";
			}

		} else {
			# the page was not retrieved from the server
			$url_status .= "FAILURE: could not retrieve ";
			if ( $BigSister::common::dl>3 ) {
				print "FAILED\n";
				print $result->error_as_HTML."\n\n" if( $result );
			}
		}

		if ($url_status) {
			# an error occured in atleast one URL
			print "$url; $url_status\n" if ( $BigSister::common::dl>3 );
			$self->report( $item, $BigSister::common::status_codes{"red"}, "$url_status $url");
		} else {
			# OK
			$self->report( $item, $BigSister::common::status_codes{"green"}, "OK");
		}
 	}

 	return(1);
}

sub late_check {
	# NOOP #
	return(1);
}

1;
