#!/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::Simple;
use Date::Parse;
use Data::Dumper;
use POSIX qw(strftime);

my $date_format = '%Y-%m-%d %H:%M:%S'; #'%a %b %e %H:%M:%S %Y';

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

my $num_pages = 0;
my @headers = qw(Time Message Note Source Destination);
my $log;

my $document = get('http://'.$login.':'.$password.'@'.$machine.'/logfile.txt');

$log = process_logfile($document);

#print Data::Dumper->Dump(
#				[
#				$log,
#				],
#				[qw(
#				*log
#				)],
#			   );

print_log(\@headers, $log);
exit();

sub process_logfile {
	my $file = shift or return;

	my @log;

	local($/) = "\r\n";

	for my $line (split($/, $file)) {
		chomp($line);
		my @fields = ($line =~ m|^((\w+)/(\d+)/(\d+)\s(\d+):(\d+):(\d+))\n\s(.+)\s(src:(\S+))?\s(dst:(\S+))?\s(.*)$|);
		my %entry = (
			Time=>$fields[0],
			Message=>$fields[7],
			Source=>$fields[9] || '',
			Destination=>$fields[11] || '',
			Note=>$fields[12],
		);
		unshift(@log, \%entry);
	}

	return(\@log);
}

sub print_log {
	my $headers = shift or return;
	my $log = shift or return;

	my %pat = (
		time	=> '%-20s',
		date	=> '%-20s',
		message	=> '%-45s',
		note	=> '%-18s',
		source	=> '%s ',
		destination
			=> '%s ',
		);
	
	my $templ = '';

	for my $header (@{$headers}) {
		if(exists($pat{lc($header)})) {
			$templ .= $pat{lc($header)};
		}
		else {
			$templ .= '%-20s';
		}
	}

	for my $entry (@{$log}) {
		for my $field (keys(%$entry)) {
			if($field =~ m!(time|date)!i) {
				$entry->{$field} =~ tr!/! !;
				$entry->{$field} .= ' UTC';
				$entry->{$field} = str2time($entry->{$field});
				$entry->{$field} = strftime($date_format,
							localtime($entry->{$field}));
			}
		}
		print sprintf($templ, @$entry{@{$headers}}), "\n";
	}
}
