#!/usr/bin/perl

use lib qw(/usr/local/perl/lib/perl5 /usr/local/perl/lib/perl5/x86_64-linux-thread-multi);
use strict;
use warnings;
use WWW::Mechanize::Firefox;
use Capture::Tiny ':all';

sub ffquit;
sub waituntilappears;

BEGIN {
	*CORE::GLOBAL::die = sub {
		die @_ if( $^S or not defined $^S );
		foreach (@_) {
			print "ERROR: $_\n";
		}
		ffquit 2;
	};

	*CORE::GLOBAL::warn = sub {
		foreach (@_) {
			print "WARNING: $_\n";
		}
		ffquit 1;
	};
}

my ($URL, $id, $pass) = @ARGV;

unless (@ARGV == 3) {
	print "Usage: $0 <URL> <login> <password>\n";
	exit 3;
}
#print "###$URL###$id###$pass##\n";
#exit 0;
$ENV{'DISPLAY'}=':1';
$ENV{'HOME'}='/home/nagios';

`/usr/bin/killall -9 firefox >/dev/null 2>&1`;

my ($stdout, $stderr, $mech) = capture {
	#my $instance_port = '4242';
	#my $ff = Firefox::Application->new(
	#	autodie => 0,
	#	create => 1,
	#	log => [qw[error]],
	#	launch => ['/usr/bin/firefox', '-P', 'webtester', '-repl', $instance_port],
	#	repl => "localhost:$instance_port",
	#);
	my $mech = WWW::Mechanize::Firefox->new(launch => 'firefox', create => 1, log => [ qw/ error / ]);
	#my $mech = WWW::Mechanize::Firefox->new (app => $ff);
};
$mech -> autoclose_tab (0);
#print "####stdout:###$stdout###\n";
#print "####stderr:###$stderr###\n";
#print "####res:#####", @res, "###\n";

sleep 1;

$mech->get ($URL);

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

#sleep 2;

#my $retries = 10;
#while ($retries-- > 0) {
#	last if $mech->is_visible (xpath => '//*[@id="userid"]');
#	sleep 1;
#}
#$retries < 0 and do {
#        print "Failed to retrieve \"$URL\". Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
#	ffquit 2;
#};

if (waituntilappears '//*[@id="userid"]') {
        print "Failed to retrieve \"$URL\". Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	ffquit 2;
}

$mech -> submit_form (
	with_fields	=> {
		userid => $id,
	},
);

#sleep 2;

#unless ($mech -> success() && $mech->title() =~ m#Sign On#) {
#        print "Failed to submit username to PUaccess. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
#        ffquit 2;
#}

#sleep 2;
#$retries = 10;
#while ($retries-- > 0) {
#	last if $mech->is_visible (xpath => '//*[@id="Bharosa_Password_PadDataField"]');
#	sleep 1;
#}
#$retries < 0 and do {
#        print "Failed to submit username to PUaccess. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
#	ffquit 2;
#};

if (waituntilappears '//*[@id="Bharosa_Password_PadDataField"]') {
        print "Failed to submit username to PUaccess. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	ffquit 2;
}

$mech -> submit_form (
	with_fields	=> {
		Bharosa_Password_PadDataField => $pass,
	},
);

##sleep 2;

##unless ($mech -> success() && $mech->title() =~ m#Manage My Enhanced Security Profile#) {
##        print "Failed to login to PUaccess. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
##        ffquit 2;
##}

#sleep 2;
#$retries = 10;
#while ($retries-- > 0) {
#	last if $mech->is_visible (xpath => '//a[text()="Log out"]');
#	sleep 1;
#}
#$retries < 0 and do {
        #print "Failed to login to PUaccess. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	#ffquit 2;
#};

if (waituntilappears '//a[text()="Log out"]') {
        print "Failed to login to PUaccess. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	ffquit 2;
}

my @lnk = $mech->xpath ('//a[text()="Log out"]', single => 'true');
#foreach (@lnk) {
#	print $_ -> {innerHTML}, "\n";
#}
$mech -> follow_link ($lnk[0]);
#$mech->follow_link (xpath => '//a[text()="Log out"]', single => 'true');

if (waituntilappears '//input[@value="LOG OFF"]') {
	print "Failed to pre-logout out of PUaccess. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	ffquit 1;
}

@lnk = $mech->xpath ('//input[@value="LOG OFF"]', single => 'true');
#foreach (@lnk) {
#	print $_ -> {innerHTML}, "\n";
#}
$mech -> follow_link ($lnk[0]);

unless ($mech -> success() && $mech->title() =~ m#Single Sign-Off#) {
	print "Failed to logout out of PUaccess. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	ffquit 1;
}

#sleep 2;

#if (waituntilappears '//title[text()="Princeton University Logout Page"]') {
#if (waituntilappears '//title[contains(., "Princeton University Logout Page")]') {
#	print "Failed to logout of PUaccess. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
#	ffquit 2;
#}

print "Successfully logged in to PUAccess and logged out\n";

ffquit 0;

sub ffquit {
	my $err = shift;
	$mech -> application -> closeTab ($mech -> tab);
	$mech -> application -> quit if $mech -> application -> openTabs < 2 || $mech -> application -> openTabs > 2;
	#sleep 2;
	exit $err;
}

sub waituntilappears {
	my $retries = 20;
	my $fnd = shift;

	while ($retries-- > 0) {
		return 0 if $mech->is_visible (xpath => $fnd);
		sleep 1;
	}
	return 1;
}


