#! /usr/bin/perl
#
# Leaves only maximum traffic value among all routers for each
# from/to pair. Both the to- and from-sorted databases are rewritten.
#
# Usage:
# AcctMax [-v] <db-prefix>
# -v		produces progress information to STDERR
# <db-prefix>	filename prefix (without .(from|to).db) of the database to
#		process
#

use strict;
use DB_File;
use vars qw( $prefix );

require '/usr/local/etc/tas/tas.conf';

# Providing default values for config parameters:
$prefix = '/var/account' unless defined $prefix;

my $opt_v;
my( $orig_from_file, $orig_to_file );
my $tmp_from_file = "$prefix/$$.db";
my %orig_from;
my %orig_to;
my %tmp_from;
my $lines;
my $key_from;
my $key_to;
my $value;
my $from;
my $to;
my $agent_host;
my $rest;
my $pckts_tmp;
my $bytes_tmp;
my $agent_host_tmp;
my $pckts;
my $bytes;


if( $ARGV[ 0 ] eq '-v' ){
	$opt_v = 1;
	shift @ARGV;
}
die "Bad arguments!" unless @ARGV == 1;

$orig_from_file = "$ARGV[ 0 ].from.db";
$orig_to_file = "$ARGV[ 0 ].to.db";

print STDERR "Stage 1 of 2: Number of records processed:\n" if $opt_v;

tie( %orig_from, 'DB_File', $orig_from_file, O_RDONLY, 0644, $DB_BTREE ) || die "Can\'t tie $orig_from_file database: $!";
tie( %tmp_from, 'DB_File', $tmp_from_file, O_RDWR|O_CREAT, 0644, $DB_BTREE ) || die "Can\'t tie $tmp_from_file database: $!";

$lines = 0;
while ( ( $key_from, $value ) = each %orig_from ) {

	next unless $key_from =~ /^(a.{4}|d\S+)\s(a.{4}|d\S+)\s(\S+)\s(.+)$/so;
	$from = $1;
	$to = $2;
	$agent_host = $3;
	$rest = $4;

	( $pckts, $bytes ) = split( ' ', $value );
	( $pckts_tmp, $bytes_tmp, $agent_host_tmp ) = split( ' ', $tmp_from{"$from $to $rest"} );

	$tmp_from{"$from $to $rest"} = "$pckts $bytes $agent_host" if( $bytes_tmp < $bytes );

	if ($opt_v) {
		$lines ++;
		print STDERR "$lines\r" if $lines%100 == 0;
	}
}

untie %orig_from;
unlink $orig_from_file, $orig_to_file;

tie( %orig_from, 'DB_File', $orig_from_file, O_RDWR|O_CREAT, 0644, $DB_BTREE ) || die "Can\'t tie $orig_from_file database: $!";
tie( %orig_to, 'DB_File', $orig_to_file, O_RDWR|O_CREAT, 0644, $DB_BTREE ) || die "Can\'t tie $orig_to_file database: $!";

print STDERR "Stage 2 of 2: Number of records processed:\n" if $opt_v;

$lines = 0;
while ( ( $key_from, $value ) = each %tmp_from ) {

	next unless $key_from =~ /^(a.{4}|d\S+)\s(a.{4}|d\S+)\s(.+)$/so;
	$from = $1;
	$to = $2;
	$rest = $3;

	( $pckts, $bytes, $agent_host ) = split( ' ', $value );

	$orig_from{"$from $to $agent_host $rest"} = "$pckts $bytes";
	$orig_to{"$to $from $agent_host $rest"} = "$pckts $bytes";

	if ($opt_v) {
		$lines ++;
		print STDERR "records: $lines\r" if $lines%100 == 0;
	}
}
print STDERR "\nComplete.\n" if $opt_v;
untie %orig_from;
untie %orig_to;
untie %tmp_from;
unlink $tmp_from_file;
