#!/usr/bin/perl

# based on work of Eric Wong <eric@taedium.net>
# available at http://www.taedium.net/rrd-iptraf/ [iptraf.txt]
#
# Dobrica Pavlinusic <dpavlin@rot13.org>
# http://www.rot13.org/~dpavlin/sysadm.html
#
# Usage: parse_iptraf.pl [name of iptraf logfile]

use strict;
use warnings;

my @PORTS = qw (
	TCP/22 TCP/25 TCP/20 TCP/21 UDP/53
	TCP/80 TCP/110 TCP/113 TCP/119 UDP/137 UDP/138
	TCP/210 TCP/443 UDP/514 );

my $log = '/var/log/iptraf/tcp_udp_services-eth1.log';
#my $log = '/home/dpavlin/iptraf/tcp_udp_services-eth1.log';

$log = $ARGV[0] if ($ARGV[0] && -r $ARGV[0]);

open(LOG,$log) || die "Can't open logfile '$log': $!";

my $delta="/var/tmp/";
my $tmp_log=$log;
$tmp_log=~s/\W/_/g;
$delta.=$tmp_log.".offset";

if (-e $delta) {
	open(D,$delta) || die "can't open delta file '$delta' for log '$log': $!";
	my $offset=<D>;
	chomp $offset;
	close(D);
	my $log_size = -s $log;
	if ($offset <= $log_size) {
		seek(LOG,$offset,0);
	}
}

my %hash;

while (<LOG>) {
	chomp;
        last if ( m/^Running/ );
        next if ( m/^\s*$/ );

        ## read data for tcp packets
        if (my ($port) = $_ =~ m/^(\w+\/\d+)/) {
	        my ($packs, $bytes, $pack_in, $byte_in, $pack_out, $byte_out) =
			$_ =~ m/\s(\d+)\s/g;

	        $hash{$port} = [$byte_in, $byte_out];
	}
}

open(D,"> $delta") || die "can't open delta file '$delta' for log '$log': $!";
print D tell(LOG);
close(D);

close(LOG);

foreach my $port (@PORTS) {
	print @{$hash{$port}}[0] || "U","\n",@{$hash{$port}}[1] || "U","\n";
	delete $hash{$port};
}

my ($sum_in,$sum_out) = (0,0);

foreach my $port (keys %hash) {
	$sum_in+=@{$hash{$port}}[0];
	$sum_out+=@{$hash{$port}}[1];
}

$sum_in = "U" if ($sum_in == 0);
$sum_out = "U" if ($sum_out == 0);
print "$sum_in\n$sum_out\n";
