#!/usr/local/bin/perl -w
#############################
# splash - Traverse WiFi 
#          Splash Pages
# Mike Schilli, 2010
# (m@perlmeister.com)
#############################
use strict;
use SplashJumper;
use WWW::Mechanize;
use Log::Log4perl qw(:easy);

my $url =
  "http://www.google.com";

Log::Log4perl->easy_init(
 $DEBUG);

my $sj = SplashJumper->new();

my @ways = ();

for
  my $plugin ($sj->plugins())
{

 if (
  !$plugin->can("register"))
 {
  ERROR "$plugin can't do",
        " register()";
  next;
 }

 my ($algo, $order) =
   $plugin->register();

 push @ways,
   [ $algo, $plugin,
  $order ];
}

# sort by plugin priority
@ways = sort {
 $a->[2] <=> $b->[2]
} @ways;

my $mech =
  WWW::Mechanize->new();
$mech->timeout(5);

# wait until network is up
{
 INFO "Trying $url";
 eval { $mech->get($url); };
 if ($@) {
  INFO
"Connection down, retrying";
  sleep 5;
  redo;
 }
}

# try to get past splash page
for my $ways (@ways) {
 eval { $mech->get($url); };

 my $current_url =
   $mech->response->request
   ->uri;

 if ($current_url eq $url) {
  INFO "Link is up.";
  last;
 } else {
  INFO "Link still down";
 }

 my ($algo, $plugin, $order)
   = @$ways;

 eval {
  INFO "Processing splash ",
       "page $current_url ",
       "with algo $algo";
  $plugin->process($mech);
 };

 if ($@) {
  ERROR
    "Algo $algo failed ($@)";
 } else {
  INFO
    "Plugin $algo succeeded";
 }
}
