#!/usr/bin/perl
#
# Extract accounting information from squid logs
#
# Usage:
# AcctSquid hostname
#
# where hostname is a value to use as an agent host
#

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

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

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

sub compile_host
{
	my $host = shift;

	if( $host =~ /^\d+\.\d+\.\d+\.\d+$/ ){
		return "a" . inet_aton( $host );
	}else{
		my @name = split /\./, $host;
		my $reversed = $name[ $#name ];
		my $i;

		for( $i = $#name - 1; $i >= 0; $i-- ){
			$reversed .= ".";
			$reversed .= $name[ $i ];
		}
		return "d$reversed";
	}
}


my $fileprefix = "$prefix/squid";
my $out_from_file = "$fileprefix.yesterday.from.db";
my $out_to_file = "$fileprefix.yesterday.to.db";
my %from_acctdb;
my %to_acctdb;
my $from_compiled;
my $to_compiled;
my $agent_host;
my $proto;
my $status;
my $pckts;
my $bytes;

die "Bad arguments!\n" unless @ARGV;
$agent_host = $ARGV[ 0 ];

tie( %from_acctdb, 'DB_File', "$out_from_file", O_CREAT|O_RDWR, 0644, $DB_BTREE ) || die "Can\'t tie $out_from_file database: $!";
tie( %to_acctdb, 'DB_File', "$out_to_file", O_CREAT|O_RDWR, 0644, $DB_BTREE ) || die "Can\'t tie $out_to_file database: $!";

while( <STDIN> ){
	next if split != 10;
	next if $_[ 3 ] =~ /\/000$/o;	# TCP_HIT/000, TCP_MISS/000, TCP_MISS_NOFETCH/000
	next unless $_[ 3 ] =~ /^(.+)\//o;
	$status = $1;
	next unless $_[6] =~ /^((\w+):\/\/)?([^:\/]+)[:\/]/o;
	$proto = $2;
	$proto = 'http' unless $proto;
	$from_compiled = compile_host( $3 );
	$to_compiled = compile_host( $_[2] );
	( $pckts, $bytes ) = split ' ', $from_acctdb{"$from_compiled $to_compiled $agent_host $proto $status"};
	$pckts++;
	$bytes += $_[ 4 ];
	$from_acctdb{"$from_compiled $to_compiled $agent_host $proto $status"} = "$pckts $bytes";
	$to_acctdb{"$to_compiled $from_compiled $agent_host $proto $status"} = "$pckts $bytes";
}
untie %from_acctdb;
untie %to_acctdb;

