#!/usr/bin/perl
#
# Joins the data from source databases to the data contained in destination
# databases.
#
# Usage:
# AcctJoin [-v] <src-db-prefix> <dst-db-prefix>
# -v		produces progress information to STDERR
# src-db-prefix	filename prefix (without .(to|from).db) of the database
#		containing source data
# dst-db-prefix	filename prefix (without .(to|from).db) of the database to
#		which join the source data

use strict;
use DB_File;

my $opt_v;
my $pckts1;
my $bytes1;
my $pckts2;
my $bytes2;
my $lines;
my %src_from;
my %dst_from;
my %dst_to;
my $src_from_file;
my $dst_from_file;
my $dst_to_file;
my $key_from;
my $key_to;
my $value;

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

$src_from_file = "$ARGV[ 0 ].from.db";
$dst_from_file = "$ARGV[ 1 ].from.db";
$dst_to_file = "$ARGV[ 1 ].to.db";

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

tie( %src_from, 'DB_File', $src_from_file, O_RDONLY, 0644, $DB_BTREE ) || die "Can\'t tie $src_from_file database: $!";
tie( %dst_from, 'DB_File', $dst_from_file, O_RDWR|O_CREAT, 0644, $DB_BTREE ) || die "Can\'t tie $dst_from_file database: $!";
tie( %dst_to, 'DB_File', $dst_to_file, O_RDWR|O_CREAT, 0644, $DB_BTREE ) || die "Can\'t tie $dst_to_file database: $!";

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

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

	( $pckts1, $bytes1 ) = split( ' ', $src_from{$key_from} );
	( $pckts2, $bytes2 ) = split( ' ', $dst_from{$key_from} );
	$pckts2 += $pckts1;
	$bytes2 += $bytes1;
	$dst_from{$key_from} = "$pckts2 $bytes2";
	$dst_to{$key_to} = "$pckts2 $bytes2";

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

untie %src_from;
untie %dst_from;
untie %dst_to;
