#!/usr/bin/perl -T

use strict;
use warnings;

use Fcntl ':flock';

delete($ENV{'PATH'});

my $IptablesCmd = '/sbin/iptables --numeric --verbose --exact --zero ' .
 '--table filter --list ';
my $OutputBaseDir = '/var/lib/hostsharing/iptcnt';

my $Now = time();

my @LocalTime = localtime(${Now});
my $Month = ${LocalTime[4]} + 1;
my $Year = ${LocalTime[5]} + 1900;

my $OutputDir = sprintf(${OutputBaseDir} . '/%04u-%02u', $Year, $Month);

if(! -e ${OutputDir}){
	mkdir(${OutputDir}) || -d ${OutputDir} ||
	 die "$0: Cannot mkdir ${OutputDir}: $!\n";
}

my $OutputPath = ${OutputDir} . '/%s-%s-%s';

SaveChain(${IptablesCmd} . 'AccountingIn',  'IN');
SaveChain(${IptablesCmd} . 'AccountingOut', 'OUT');

exit(0);

sub SaveChain{
	my ($Command, $Prefix) = @_;

	open(INPUT, '-|', ${Command}) ||
	 die "$0: Cannot execute \"${Command}\": $!\n";

	my $EndReached = 0;

	while(<INPUT>){
		chomp;
	
		if($. == 1 || $. == 2){
			next;
		}

		if(${EndReached}){
			die "$0: Unexpected input line #$. from " .
			 "\"${Command}\" (expected EOF): \"$_\"\n";
		}

		if(/^Zeroing chain `Accounting(In|Out)'$/){
			$EndReached = 1;
			next;
		}

		my $IpAddrRE = '([0-9]{1,3}\.){3}[0-9]{1,3}(/[0-9]{1,2})?';
		my $LineRE   = '^ *[0-9]+ +([0-9]+) +0 +-- +\* +\* +' .
		               '(' . ${IpAddrRE} . ') +(' . ${IpAddrRE} . ') *$';

		if(/${LineRE}/){
			my ($Bytes, $Source, $Destination) = ($1, $2, $5);

			$Source      .= "/32" if($Source      !~ m#/[0-9]{1,2}$#);
			$Destination .= "/32" if($Destination !~ m#/[0-9]{1,2}$#);

			$Source      =~ s#/#!#;
			$Destination =~ s#/#!#;

			my $OutputFile = sprintf(${OutputPath}, ${Prefix},
			 ${Source}, ${Destination});

			open(OUTPUT, '>>', ${OutputFile}) ||
			 die "$0: Cannot open ${OutputFile}: $!\n";

			flock(OUTPUT, LOCK_EX) ||
			 die "$0: Cannot exclusively lock ${OutputFile}: $!\n";

			seek(OUTPUT, 0, 2) ||
			 die "$0: Cannot move to the end of ${OutputFile}: $!\n";
			
			print OUTPUT "${Now} ${Bytes}\n" ||
			 die "$0: Cannot write to ${OutputFile}: $!\n";
			
			close(OUTPUT) ||
			 die "$0: Cannot close ${OutputFile}: $!\n";
		}
		else{
			die "$0: Invalid input line #$. from " .
			 "\"${Command}\": \"$_\"\n";
		}
	}

	if(! ${EndReached}){
		die "$0: Unexpected EOF while reading input from " .
		 "\"${Command}\".\n";
	}

	close(INPUT) ||
	 die "$0: Cannot close \"${Command}\": $!\n";
}
