#!/usr/bin/perl -w
#
# Check to login to http://www.princeton.edu/rms, and perform policy accessibility checks - ticket #1717662
#
# By Igor Gubenko (igubenko@Princeton.EDU), 12/15/2011
#

use lib qw(/usr/local/monitoring/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;
#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 == 2;

my $mech = WWW::Mechanize->new (agent => 'Mozilla/5.0', stack_depth => '1', noproxy => '1', quiet => '1', onerror => undef, onwarn => undef, timeout => '20') or die ("Unable to instantiate WWW::Mechanize!\n");
my $url_ini = "http://www.princeton.edu/rms";

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

# Retrieve initial URL - this is just a very silly bunch of redirects
$mech->get ($url_ini);

unless ($mech -> success() && defined $mech->title() && $mech->title() =~ m#LC SSO Request#) {
	print "Failed to fetch \"$url_ini\". Answer: " . $mech->status() . "\n";
	exit 2;
}
$url_ini = "https://rms.princeton.edu/edc/Login.do";

# Retrieve the actual website
$mech->get ($url_ini);

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

# Login
$mech->submit_form (
	fields      => {
		j_username    => $user,
		j_password    => $pass,
	}
);

unless ($mech -> success() && $mech->response()->decoded_content =~ m#Manage policies, policy sets#) {
	print $mech->response()->decoded_content =~ m#Login failed# ? "Unable to login to Adobe Rights Management. Login failed\n" : 'Error after trying to login. Web server returned ' . $mech->status() . "\n";
	exit 2;
}

# Click on Policies
$mech->follow_link (text => 'Policies');

unless ($mech -> success() && $mech->response()->decoded_content =~ m#Policy sets you have access to appear below#) {
	print "Error clicking on \"Policies\". Web server returned " . $mech->status() . "\n";
	exit 2;
}

# Click on Test Policy Set
$mech->follow_link (text => 'Test Policy Set');

unless ($mech -> success() && $mech->response()->decoded_content =~ m#Edit Policy Set: Test Policy Set#) {
	print "Error navigating to \"Test Policy Set\". Web server returned " . $mech->status() . "\n";
	exit 2;
}

print "Successfully logged in to \"$url_ini\", navigated to \"Policies\", and then \"Test Policy Set\".\n";
exit 0;

sub usage {
	print "Usage: $progname <login_for_www.princeton.edu/rms> <password>\n";
	exit 2;
}
