#!/usr/bin/perl

use warnings;
use strict;
use Socket;
use DBI;

die "usage: $0 trafd.eth" unless @ARGV;
my $traf = shift @ARGV;

my $database = "traffic";
my ($user, $passw) = ("root", "");
my ($sec,$min,$hour,$day,$mon,$year) = localtime();

# получим дату получения записи
my %date;
my %month = (
	"Jan" => 1, "Feb" => 2, "Mar" => 3,
	"Apr" => 4, "May" => 5, "Jun" => 6,
	"Jul" => 7, "Aug" => 8, "Sep" => 9,
	"Oct" => 10, "Nov" => 11, "Dec" => 12
);

open(TRAFFIC, "traflog -l -i $traf 2>/dev/null |")
	or die "Failed execute 'traflog'";
my $str =  <TRAFFIC>;
while (<TRAFFIC>) {
	my ($nm,$mon1,$day1,$time1,$mon2,$day2,$time2) = split();
#	$date{$nm} = $year + 1900 . "-$month{$mon2}-$day2 $time2";
	$date{$nm} = "2009" . "-$month{$mon2}-$day2 $time2";
}
close(TRAFFIC);

my ($dbh, $sth);
$dbh = DBI->connect("DBI:mysql:host=localhost;database=$database",
	$user, $passw) or die $DBI::errstr;
$sth = $dbh->prepare("INSERT INTO traffic
	(date,srcIp,dstIp,srcPort,dstPort,protoID,bytes,psize)
	VALUES(?,?,?,?,?,(SELECT protoID FROM proto WHERE name = ?),?,?)")
	or die $dbh->errstr;

foreach my $nm (sort keys %date) {
	open(TRAFFIC, "traflog -na -b$nm -e$nm -o default -i $traf 2>/dev/null |")
		or die "Failed execute 'traflog'";

	while (<TRAFFIC>) {
		# удалим последний символ перевода строки '\n'
		chomp();
		# разобъем строку
		my ($srcIp,$srcPort,$dstIp,$dstPort,$prtName,$bytes,$psize) = split();
		# преобразуем IP адреса в цифровые значения
		$srcIp = ip2long($srcIp);
		$dstIp = ip2long($dstIp);
		# преобразуем текстовые значения портов в числовые
		if ($srcPort eq "none") {
			$srcPort = -1;
		} elsif ($srcPort eq "client") {
			$srcPort = 0;
		}
		if ($dstPort eq "none") {
			$dstPort = -1;
		} elsif ($dstPort eq "client") {
			$dstPort = 0;
		}
		# добавим значение в базу
		$sth->execute("$date{$nm}",
			"$srcIp","$dstIp","$srcPort","$dstPort",
			"$prtName","$bytes","$psize") or die($dbh->errstr);
	}
	close(TRAFFIC);
}

$dbh->disconnect();
exit 0;

# преобразует строковое представление IP адреса в цифровое
sub ip2long {
	return unpack("L*", pack("N*", unpack("L*", inet_aton(shift))));
}
