#!/usr/bin/perl -w
use strict;

###########################################################################
# (c) 2005 Brett T. Warden
# http://www.wgz.org/bwarden/
#
# License:
# Perl Artistic License
# http://www.perl.com/language/misc/Artistic.html
#
# Other licensing arrangements available upon request.
#
# Note specifically: 
#  THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED 
#  WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF 
#  MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#
###########################################################################

use Net::Netrc;
use LWP::UserAgent;
use HTML::TreeBuilder;
use Template::Extract;

my $ua = LWP::UserAgent->new;
my $extract = Template::Extract->new;

my $machine = shift(@ARGV) || 'vapor.gue.st.wgz.org'; 
my $auth = Net::Netrc->lookup($machine, 'admin');
my $login = $auth->login();
my $password = $auth->password();

my $req = HTTP::Request->new(POST => 'http://'.$login.':'.$password.'@'.$machine.'/mac.cgi') or die "Couldn't create User Agent\n";

my $template = << '.';
<div align=center><font[% ... %]>[% /\s*/ %]
[% message %]<br[% ... %]>[% /\s*/ %]</font>[% /\s*/ %]</div>
.

for my $arg (@ARGV) {
	my @octets;
	if(my @mac = split(/[:\-]/, $arg)) {
		for my $octet (@mac) {
			if($octet =~ m|^([0-9a-f]{1,2})$|i) {
				push(@octets, sprintf('%02X', hex($1)));
			}
		}
	}
	if(@octets == 6) {

		my $editRow = -1;
		my $delrow  =  0;
		my $filters =  1;

		$req->content_type('application/x-www-form-urlencoded');
		
		my $content = sprintf('editRow=%d&delrow=%d&filters=%d&name=%s&mac1=%s&mac2=%s&mac3=%s&mac4=%s&mac5=%s&mac6=%s',
			$editRow,
			$delrow,
			$filters,
			'Automated+entry',
			@octets,
			);

		$req->content($content);
		my $res = $ua->request($req);
		if ($res->is_success) {
			my $tree = HTML::TreeBuilder->new_from_content($res->content);
			my @message;
			for my $div ($tree->look_down('_tag', 'div',
						'align', 'center')) {
				my $font = $div->look_down('_tag', 'font',
							'color', '#000000');
				if($font) {
					push(@message, $font->as_trimmed_text);
				}
			}
			
			print "Address: ", join(':', @octets), "\n", join("\n", @message), "\n";
		}
		else {
			warn "Failed to POST $arg\n";
		}
	}
	else {
		warn "Skipping invalid address $arg\n";
	}
}
exit();

