#!/usr/bin/perl -wT

#################################################
#       Simple Demon bwusage file analyser      #
# (c) 2001-2002 Mike Newman <mikegtn@gnome.org> #
#                                               #
#           Released under the GNU GPL          #
#               http://www.gnu.org              #
#################################################

use strict;
use Net::FTP;

# location of the downloaded logfile
# FTP username and passwd

my $logfile = "bwusage.txt";
my $username = "yourhostname";
my $password = "secret";

# other global variables

my $dir = shift;
my $req = 0;
my $dlds = 0;
my $date = 0;

# get the bwusage file either over the network.
# if we can't, we'll still check there's no local file

print "Fetching bandwidth log file...\n";
my $ftp = Net::FTP->new("homepages.demon.co.uk", Debug => 0);
if ($ftp) {
		$ftp->login($username, $password);
		$ftp->get($logfile);
		$ftp->quit;
};

# if no server-side path specified, print a simple help message and exit
# for complete figures, use /

if (! $dir) {
	print "Usage: bw <path> -  lists bandwidth usage in <path> on server\n";
	unlink ($logfile);
	exit(0);
}

# open the logfile, and get the date of the first entry

open (FILE,$logfile) or die("File not found, check your network connection.\n");
read(FILE, $date, 80);
$date =~ /(.*?),.*/;
$date = $1;

# iterate over the file, checking for instances of the chose path
# and accumulating request and bandwidth figures

while (<FILE>) {
	if (/$dir/) {
		$_ =~ m/$dir\/* (.*) Requests, totalling (.*) MB/;
		$req += $1; $dlds += $2;
	}
}
close FILE;

# if the path was mentioned at least once, print some results
# otherwise explain that it wasn't found

if ($req > 0) {
	my $avg = ($dlds/$req)*1024;
	print "Checking $dir since $date:\n";
	print "$req requests, $dlds MB downloaded,";
	print " Average download " . int($avg) . "K\n";
} else {
	print "$dir not found in usage log.\n";
}

# remove the logfile and
# return the bandwidth used for other programs to use

unlink ($logfile);
exit ($dlds);
