#
#****************************************
#Bandmin (c)1998-1999 J. Nick Koston (BlueDraco)
# - A simple Bandwidth Monitor
#****************************************
#
#To use this package you must have a OS that has ipacct
#

package IP::UserAcct;

require 5.002;
require Exporter;
use strict;
use Carp;

use vars qw(@ISA $VERSION);

$VERSION = 0.10;
@ISA = qw(Exporter);



sub new 
{
	my ($backend);
	my  $self = {};

	bless($self);

	if (-e "/sbin/ipacct" && -e "/proc/net/ip_acct_user") {
		$self->{"backend"} = "ipacct";
	} else {
		return 0;
	}

	return($self);

}

sub clearcounter {
	my ($self) = @_;

	if ($self->{"backend"} eq "ipacct") {
		system("/sbin/ipacct","-C");
	}
}

sub getuserbytes {
        my ($self) = @_;

	my($user,$ipdata,@IPMASS,$bytes,%userbytemap,$uid);
	my($address,$sent,$recv,$user);

        if ($self->{"backend"} eq "ipacct") {
		open(IPACCTUSER,"/proc/net/ip_acct_user");
		@IPMASS=<IPACCTUSER>;
		close(IPACCTUSER);
	} else {
		die "getuserbytes called without a backend"; 
	}

	foreach $ipdata (@IPMASS) {
        	$ipdata =~ s/\t/ /g;
        	$ipdata =~ s/\s(\s*|.)\s/ /g;
        	$ipdata =~ s/^ //g;
		$bytes = 0;
	        if ($self->{"backend"} eq "ipacct") {
			($uid,$address,$sent,$recv,undef) =
				split(/\s/, $ipdata);
			$bytes = ($sent + $recv);
	        }
        	if ($uid > -1 && $address eq "*") {
			$user = (getpwuid($uid))[0];
                	$uid =~ s/\n//g;
                	$bytes =~ s/\n//g;
			$userbytemap{$user} = ($userbytemap{$user} + $bytes);
		}
	}
	
	return(%userbytemap);

}

