#!/usr/bin/perl
#
# PF Accounting (pfacc) - Accounting PF label counters
#
# Copyright (C) 2004 Alexandre Dulaunoy <adulau@foo.be>
#
# This program is  free software; you can redistribute  it and/or modify
# it under the  terms of the GNU General Public  License as published by
# the Free Software Foundation; either  version 2 of the License, or (at
# your option) any later version.
#
# This program  is distributed in the  hope that it will  be useful, but
# WITHOUT   ANY  WARRANTY;   without  even   the  implied   warranty  of
# MERCHANTABILITY  or FITNESS  FOR A  PARTICULAR PURPOSE.   See  the GNU
# General Public License for more details.
#
# You  should have received  a copy  of the  GNU General  Public License
# along  with  this  program;  if   not,  write  to  the  Free  Software
# Foundation, Inc., 59 Temple Place  - Suite 330, Boston, MA 02111-1307,
# USA.
#

use Config::General;
use DBI;
use DBD::mysqlPP;
use POSIX;

my $version = "0.0.1";

my %allconfig = ReadingConfiguration("pfacc.cfg");

if ($allconfig{general}{daemon}) { goingDaemon(); }

$| = 303; # Everybody needs a 303 !

my $dbh = DBI->connect($allconfig{general}{DBIdsn}) or die "Unable to connnect to the DB server because of : $DBI::errstr";

my $sth = $dbh->prepare("INSERT INTO counters(label,time) VALUES (?,?)");
my $token = "pfacc-start";
my $tm = `date  "+%Y-%m-%d %H:%M:%S"`;
$sth->execute($token,$tm);
$sth->finish;


while (1) 
{

 if (!($allconfig{general}{clearcounters})) {
  open (FILEX, "-|", "/sbin/pfctl -vvsl");
 } else {
  open (FILEX, "-|", " /sbin/pfctl -zvvsl");
 }

 while (<FILEX>)
 {
	my ($label,$evaluations,$packets,$bytes) = split (/ /);
	my $tm = `date  "+%Y-%m-%d %H:%M:%S"`;
	print $tm;
	AddEntry ($label, $bytes,$tm);
 }

 close (FILEX);

 sleep $allconfig{general}{wait};
 
}
sub AddEntry {
    my $label = shift;
    my $counter = shift;
    my $time = shift;

    my $sth = $dbh->prepare("INSERT INTO counters(label,bytes,time) VALUES (?,?,?)");
    $sth->execute ($label, $counter, $time);
    $sth->finish;	
}

sub ReadingConfiguration {
    my $configfile = shift;
    my $conf       = new Config::General($configfile);
    my %config     = $conf->getall;
    return %config;
}


sub goingDaemon {
    my $pid;
    $pid = fork;
    exit if $pid;
    die "goingDaemon : Couldn't fork : $!" unless defined($pid);
    POSIX::setsid() or die "goingDaemon : Can't start a new session: $!";
    $SIG{HUP}  = \&restartDaemon;
    $SIG{INT}  = \&stopDaemon;
    $SIG{TERM} = \&stopDaemon;
    print "Going daemon with PID $$";
    open( PIDFILE, ">./$0.pid" );
    print PIDFILE $$;
    close(PIDFILE);
    return $$;
}

sub restartDaemon {
    print "Restarting Daemon...";
}

sub stopDaemon {

    print "Stopping Daemon...";
    unlink "./$0.pid";
    die;
}

