#!/usr/bin/perl -w
#
# Test AIS ShoppingCart app for book purchases
#
# By Igor Gubenko (igubenko@Princeton.EDU), 10/15/2012
#

use lib qw(/usr/local/monitoring/perl/lib/perl5);

use strict;
use WWW::Mechanize;

#use Net::SSL; # From Crypt-SSLeay
#use LWP::Protocol::https;
#BEGIN {
#       $Net::HTTPS::SSL_SOCKET_CLASS = "Net::SSL"; # Force use of Net::SSL
#       $ENV{PERL_NET_HTTPS_SSL_SOCKET_CLASS}="IO::Socket::SSL";
#}
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
#$ENV{HTTPS_VERSION} = 3;

sub usage;

my $progname = $0;

usage unless @ARGV == 1;

my $mech = WWW::Mechanize->new (agent => 'Mozilla/5.0', stack_depth => '1', noproxy => '0', quiet => '1', onerror => undef, onwarn => undef, timeout => '20') or die ("Unable to instantiate WWW::Mechanize!\n");
#$mech -> add_handler("request_send",  sub { shift->dump; return });
#$mech -> add_handler("response_done", sub { shift->dump; return });
my $url_ini = "https://$ARGV[0].Princeton.EDU/bookordersws/Shoppingcart.asmx";

# Retrieve initial URL
$mech->get ($url_ini);

unless ($mech -> success() && $mech->title() =~ m#ShoppingCart Web Service#) {
	print "Failed to fetch \"$url_ini\". Answer: " . $mech->status() . ";\n";
	exit 2;
}

# Go to login link
$mech->follow_link (text => 'InvokingWebServiceForTesting');

unless ($mech -> success() && $mech->response() -> decoded_content =~ m#To test the operation using the HTTP POST protocol, click the 'Invoke' button.#) {
	print "Error clicking on the InvokingWebServiceForTesting link;" . $mech->status() . "\n";
	exit 2;
}

# Login
$mech->submit_form ();

unless ($mech -> success() && $mech->response() -> decoded_content =~ m#<Invoking>Success</Invoking>#) {
	print "Error clicking on \"Invoke\" or receiving the XML file;" . $mech->status() . "\n";
	exit 2;
}

print "Successfully tested the ShoppingCart app\n";

exit 0;

sub usage {
	print "Usage: $progname <host>\n";
	exit 2;
}
