package Yaala::Parser;
# FIXME

use strict;
use warnings;
use vars qw(%names %datafields);

use Exporter;
use Config qw#get_config read_config#;

die;

@Yaala::Parser::EXPORT_OK = qw#parse extra %datafields#;

@Yaala::Parser::ISA = ('Exporter');

print STDERR "\nparser/netacct: Using NET-ACCT format" if $::DEBUG;
# FIXME: pass month, date and hour in seconds to properly format and sort.

read_config ('netacct.config');
for (get_config ('alias'))
{
	s/\s//g;
	my ($name, $ips) = split (m/:/, $_);
	my @ips = split (m/,/, $ips);

	for (grep { m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ } @ips)
	{
		$names{$_} = $name;
	}
}

%datafields= (	
    protocol	    => 'key',
    source	    => 'key:host',
    sourceport	    => 'key',
    destination	    => 'key:host',
    destinationport => 'key',
    interface	    => 'key',
    user	    => 'key',
    month	    => 'key',
    date	    => 'key',
    hour	    => 'key',
    packetcount     => 'amount:number',
    bytes	    => 'amount:bytes',
    connections	    => 'amount:number'
    );

# This needs to be done at runtime, since Data uses Setup which relies on
# %datafields to be defined  -octo
require Yaala::Data;
import Yaala::Data qw#store#;

return (1);

sub parse
{
	my $line = shift or return undef;

	my @data = split (/[\t\s]+/, $line, 10);

# Initialize the variables that we can get out of
# each line first..
		my ($epoch, $protocol, $source_ip, $source_port, $dest_ip,
			$dest_port, $packet_count, $data_size, $interface,
			$user) = @data;

		my ($hour, $day, $month, $year) = (localtime ($epoch))[2,3,4,5];
		++$month; $year += 1900;
		my $date = sprintf ("%04u-%02u-%02u", $year, $month, $day);
		$hour = sprintf ("%02u", $hour);
		$month = sprintf ("%02u", $month);

# And now initialize all the variables we will use
# to get more information out of each field..

		if ($protocol == 1) { $protocol = 'ICMP'; }
		elsif ($protocol == 6) { $protocol = 'TCP'; }
		elsif ($protocol == 17) { $protocol = 'UDP'; }

		if (defined $names{$source_ip}) { $source_ip = $names{$source_ip}; }
		elsif ($source_ip eq '127.0.0.1') { $source_ip = 'localhost'; }
		elsif ($source_ip =~ /^192\.168\./) { $source_ip = 'lan'; }
		else { $source_ip = 'extern'; }
		
		if (defined $names{$dest_ip}) { $dest_ip = $names{$dest_ip}; }
		elsif ($dest_ip eq '127.0.0.1') { $dest_ip = 'localhost'; }
		elsif ($dest_ip =~ /^192\.168\./) { $dest_ip = 'lan'; }
		else { $dest_ip = 'extern'; }

		my %combined = (
					'protocol'	=>	$protocol,
					'source'	=>	$source_ip,
					'sourceport'	=>	$source_port,
					'destination'	=>	$dest_ip,
					'destinationport'=>	$dest_port,
					'packetcount'	=>	$packet_count,
					'interface'	=>	$interface,
					'user'		=>	$user,
					'bytes'		=>	$data_size,
					'hour'		=>	$hour,
					'date'		=>	$date,
					'month'		=>	$month,
					'connections'	=>	1
										);
		store (\%combined);
}

sub extra
{
	# foo
}

1;
