#!/usr/bin/perl

use strict;
use warnings;

# load LWP library:
use LWP::UserAgent;
use HTML::Parse;

sub get_param($) {
	my $get_var = shift;
	
	$get_var = "--".$get_var;
	
	my $i = 0;
	
	foreach my $var (@ARGV) {
		
		if ($get_var eq $var) {
			return $ARGV[$i+1];
		}
		
		$i++;
	}
}

#print usage
if ($#ARGV < 1) {
	print "\n";
	print "Usage: parse_web.pl --url <absolute_url> [--auth_server <auth_server> --auth_port <auth_port> --auth_user <auth_user> --auth_pass <auth_pass> --auth_realm <auth_realm>\n";
	print "\n\n";
	print "An usage example could be:\n\n";
	print './parse_web.pl --url "http://myweb.com/ --auth_server "myweb.com" --auth_port 80 --auth_user "user" --auth_pass "pass" --auth_realm "Private area"';
	print "\n\n";
	exit();
}


#Get scritp parameters
my $url = get_param("url");
my $auth_server = get_param("auth_server");
my $auth_port = get_param("auth_port");
my $auth_user = get_param("auth_user");
my $auth_pass = get_param("auth_pass");
my $auth_realm = get_param("auth_realm");
 
# create UserAgent object
my $ua = new LWP::UserAgent;
  
# timeout:
$ua->timeout(15);

# if defined set http authentication
if (defined($auth_server) && defined($auth_user) && defined($auth_pass) 
	&& defined($auth_realm) && defined($auth_port)) {

	$ua->credentials(
		"$auth_server:$auth_port",
		"$auth_realm",
		"$auth_user" => "$auth_pass"
	);
		
}

# proceed the request:
my $request = HTTP::Request->new('GET');

$request->url($url);

# Make the request 
my $response = $ua->request($request);

# Get content
my $content =  $response->content;

# Set the result to undef
my $result = undef;

#Check if the content has error string				
if ($content =~ m/(ERROR - .+)/g) {
	$result = $1;
}

#Check if the content has ok string
if ($content =~ m/OK.+/g) {
	$result = "OK";
}

# If there weren't ok or error string don't return anything
if (!defined($result)) {
	exit();
}

# return the result
print $result;
