#!/usr/bin/perl -w

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

sub ffquit;
sub waituntilappears;

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 {
	WWW::Mechanize::Firefox->new(launch => 'firefox', create => 1, autoclose => 1, log => [ qw/ error / ]);
};
$mech -> autoclose_tab (0);
#print "####stdout:###$stdout###\n";
#print "####stderr:###$stderr###\n";
#print "####res:#####", @res, "###\n";

sleep 1;

$mech->get ($URL);

#my @tabs = $mech->application->openTabs();
#foreach (@tabs) {
    #print "title:##", $_->{title}, "##location:##", $_->{location}, "##\n";
#	$mech -> application -> closeTab ($_) if $_ -> {location} =~ m#blank#;
#}

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

$mech->click ({xpath => '//input[@value="blackboardId"]', single => 'true', synchronize => 0});

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

$mech -> form_id ('bbLoginForm');
$mech -> set_fields (
	user_id => $id,
	password => $pass,
);

$mech -> click ({selector => '.btn'});

### TEMP
if (waituntilappears '//a[@title="Logout"]') {
	print "Failed to login to Blackboard. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	ffquit 2;
}

my @logout = $mech -> xpath ('//a[@title="Logout"]');

unless ($mech -> success() && @logout > 0) {
##unless ($mech -> success()) {# && $mech->response()->decoded_content =~ m#Rover Account#) {
	print "Failed to login to Blackboard. Current URL: ". $mech->uri->as_string . ". Answer: " . $mech->status() . "; " . $mech->title() . "\n";
	ffquit 2;
}

##sleep 2;

$mech -> follow_link ($logout[0]);
##$mech -> get ("https://blackboard.princeton.edu/webapps/login?action=logout");

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

#$mech -> autoclose_tab(0);

print "Successfully logged in to Blackboard 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;
}

