#!/usr/bin/perl -w
#
# Test sp2010
#
# By Igor Gubenko (igubenko@Princeton.EDU), 09/25/2013
#

use strict;
use lib qw(/usr/local/perl/lib/perl5/x86_64-linux-thread-multi /usr/local/perl/lib/perl5);
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;
$ENV{HTTPS_CA_DIR}='/etc/pki/tls/certs';

sub usage;

my $progname = $0;

usage unless @ARGV >= 3;

my $mech = WWW::Mechanize->new (agent => 'Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0', stack_depth => '1', noproxy => '1', quiet => '1', onerror => undef, onwarn => undef, timeout => '20') or die ("Unable to instantiate WWW::Mechanize!\n");
#$mech->proxy (['http', 'https'], 'http://malka.princeton.edu:8888');
$mech -> add_handler("request_send",  sub { shift->dump; return });
$mech -> add_handler("response_done", sub { shift->dump; return });

my ($host, $user, $pass, $str) = @ARGV;
$str = '.*' unless defined $str;
my $url_ini = "https://${host}.princeton.edu/oit/csg/sharepoint/default.aspx";

$mech->get ($url_ini);

unless ($mech -> success() && $mech->title() =~ m#Sign In#) {
	print "Failed to fetch \"$url_ini\". Current URL: " . $mech->uri->as_string . ". Answer: " . $mech->status() . ";\n";
	exit 2;
}

# Login
$mech->submit_form (
	'form_id' => 'loginForm',
	with_fields      => {
		'userNameInput'	=> $user,
		'passwordInput'	=> $pass,
	},
);

unless ($mech -> success() && $mech->title() =~ m#Working#) {
	print "Failed to login at Federation Services. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	exit 2;
}

$mech->submit();

unless ($mech -> success() && $mech->title() =~ m#Home - SharePoint# && $mech->response()->decoded_content =~ m#$str#) {
	print "Failed to follow with authentication to SharePoint. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	exit 2;
}
#print "\n#########################\n\n\n", $mech -> response() -> decoded_content, "\n";

$url_ini = 'https://sp2010prod.princeton.edu/oit/csg/sharepoint/_layouts/SignOut.aspx';
$mech->get ($url_ini);

unless ($mech -> success() && $mech->title() =~ m#Sign Out: Close Browser To Complete Sign Out#) {
	print "Failed to sign out of SharePoint. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	exit 1;
}

#print "\n#########################\n\n\n", $mech -> response() -> decoded_content, "\n";

print "Successfully accessed SharePoint, logged in and logged out\n";

exit 0;

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