#!/usr/bin/perl

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

die "usage: $0 <database> <Y-M-D h:m:s>" unless @ARGV;

my $database = shift @ARGV;
my ($user, $passw) = ("root", "");
my ($dbh, $sth);

my $date;
if ($ARGV[0]) {
	$date = $ARGV[0];
} else {
	my ($sec,$min,$hour,$day,$mon,$year) = localtime();
	$year += 1900;
	$mon++;
	$date = "$year-$mon-$day $hour:$min:$sec";
}

$dbh = DBI->connect("DBI:mysql:host=localhost;database=$database",
	$user, $passw, {PrintError => 0, RaiseError => 1});

$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;

while (<STDIN>) {
	chomp();
	my ($srcIp,$srcPort,$dstIp,$dstPort,$prtName,$bytes,$psize) = split();

	$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",
		"$srcIp","$dstIp","$srcPort","$dstPort",
		"$prtName","$bytes","$psize") or die($dbh->errstr);
}

$dbh->disconnect();
exit 0;

sub ip2long {
	return unpack("L*", pack("N*", unpack("L*", inet_aton(shift))));
}
