#!/usr/local/bin/perl -w
###########################################
# tomato-bandwith - JavaScript-enabled
#   screen scraper
# Mike Schilli, 2011 (m@perlmeister.com)
###########################################
use strict;
use Sysadm::Install qw(:all);
use WWW::Scripter;
use HTML::TableExtract;
use YAML qw(Dump);

my $w = new WWW::Scripter;
$w->use_plugin('Ajax');

my $pw = slurp "pw.txt";
chomp $pw;

$w->credentials( "root", $pw );
$w->get(
    'http://192.168.0.1/bwm-realtime.asp');

rounds( $w, 5, sub { } );
rounds( $w, 1, \&extract_bandwidth );

###########################################
sub rounds {
###########################################
    my( $w, $rounds, $callback ) = @_;

    for( 1 .. $rounds ) {
        $w->check_timers();
        sleep( 1 );
    }

    $callback->( $w->content );
}

###########################################
sub extract_bandwidth {
###########################################
    my( $html ) = @_;

    my $te = HTML::TableExtract->new( );
    $te->parse( $html );

    my $ts = $te->first_table_found();

    my %bw = ();

    foreach my $row ($ts->rows) {
        my @cols = map { /(\S+)/ } @$row;

        $bw{ $cols[0] } = 
             { avg  => $cols[3],
               peak => $cols[5],
             };
    }

    print Dump( \%bw );
}
