#!/usr/bin/perl -w
#
# Test accessibility of Departmental Charges webpage, and login
#
# By Igor Gubenko (igubenko@Princeton.EDU), 05/21/2012
#

use lib qw(/usr/local/perl/lib/perl5);
#use lib qw(/usr/local/perl/modules/lib/perl5/site_perl/5.8.8 /usr/local/perl/modules/lib/perl5/5.8.8 /usr/local/perl/modules/lib64/perl5/site_perl/5.8.8 /usr/local/perl/modules/lib64/perl5/5.8.8 /var/local/groundwork/perl/lib/site_perl/5.8.8/);

use strict;
use WWW::Mechanize;

sub usage;

my $progname = $0;

usage unless @ARGV == 3;

my $mech = WWW::Mechanize->new (agent => 'Mozilla/5.0', stack_depth => '1', noproxy => '1', quiet => '1', timeout => '20') or die ("Unable to instantiate WWW::Mechanize!\n");
my $url_ini = "https://puwebp.princeton.edu:7900/dc_web/priv/index.html";

my ($user, $pass, $group) = @ARGV;

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

unless ($mech -> success() && $mech->title() =~ m#Departmental Charges \[DC Home\]#) {
	print "Failed to fetch \"$url_ini\". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	exit 2;
}

$url_ini = "https://puwebp.princeton.edu:7900/dc_web/priv/Signin.jsp";

# Retrieve the login page
$mech->get ($url_ini);

unless ($mech -> success() && $mech->title() =~ m#Princeton University - Departmental Charges \[Sign In\]#) {
	print "Failed to fetch \"$url_ini\". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	exit 2;
}

# Login
$mech->submit_form (
	fields      => {
		txtUserId    => $user,
		txtPassword  => $pass,
		selDept      => $group,
	}
);

unless ($mech -> success() && $mech->response()->decoded_content =~ m#Do you wish to Sign Out from the Departmental Charges Application#) {
	print "Failed: " . ($mech->status() !~ /^200$/ ? "Error submitting login information\n" : "Error logging in\n");
	exit 2;
}

$url_ini = "https://puwebp.princeton.edu:7900/dc_web/priv/Signout.jsp";

# Logout
$mech->get ($url_ini);

unless ($mech -> success() && $mech->response()->decoded_content =~ m#Signed Out of the DC system#) {
	print 'Failed to log out. Web server returned ' . $mech->status() . "\n";
	exit 2;
}

print "Successfully accessed the Departmental Charges webpage, logged in and logged out.\n";

exit 0;

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