#!/usr/bin/perl
#
# $Id: iptables,v 1.1 2002/02/07 18:31:12 syatskevich Exp $
#
#  ,   
#
#    iptables -L " " -n -v -x -Z
#
#      account_log.
#
#      :
#     1)  (   ) 
#     2) 
#     3)  
#     4)  
#     5)  
#     6)  
#     7)  
#     8)   
#     9)   
#

use DBI;

$user   = $ENV{"USER"};
$dbase  = $ENV{"DBASE"};
$passwd = $ENV{"PASSWD"};

#  
if (($user eq "") || ($dbase eq "") || ($passwd eq ""))
{
	die "  \n";
}

($day, $month, $year) = (localtime) [3, 4, 5];

$month++;
$year += 1900;

sub parseLogLine
{
	if (($pkts, $bytes, $prot, $opt, $in, $out, $source, $destination) =
	    (/^\s+(\d+)\s+(\d+)\s+([\w\d]+)\s+([-\w\d]+)\s+([\*\w\d]+)\s+([\*\w\d]+)\s+([!\d\.:\/-]+)\s+([!\d\.:\/-]+)/i))
	{
		$opt = "" if ($opt eq "--");
		$in  = "" if ($in  eq "*");
		$out = "" if ($out eq "*");

		return ("INSERT", $pkts, $bytes, $prot, $opt, $in, $out, $source, $destination);
	}

	return ("SKIP", 0, 0, "", "", "", "", "", "");
}

$dbh = DBI->connect ("dbi:Pg:dbname=$dbase", $user, $passwd, {AutoCommit => 0});

$sth = $dbh->prepare ("INSERT INTO account_log VALUES ('$year/$month/$day', ?, ?, ?, ?, ?, ? ,?, ?)");

while (<STDIN>)
{
	($state, $pkts, $bytes, $prot, $opt, $in, $out, $source, $destination) = parseLogLine ($_);

	if (($state eq "INSERT") && ($pkts > 0) && ($bytes > 0))
	{
		$sth->execute ($prot, $opt, $in, $out, $source, $destination, $pkts, $bytes);
		if ($sth->state)
		{
			$dbh->rollback;
			$dbh->disconnect;

			die "  ,    \n";
		}
	}
}

$dbh->commit;
$dbh->disconnect;
