#!/usr/bin/perl -Tw
#
#  LMS version 1.10.2 Roham
#
#  Copyright (C) 2001-2007 LMS Developers
#
#  Please, see the doc/AUTHORS for more information about authors!
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License Version 2 as
#  published by the Free Software Foundation.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
#  USA.
#
#  $Id: lms-traffic,v 1.20.2.1 2007/08/17 13:14:49 alec Exp $

use strict;
use DBI;
use Config::IniFiles;
use Getopt::Long;
use vars qw($logfile $configfile $quiet $help $version);
use POSIX qw(strftime);

my $_version = '1.10.2 Roham';

my %options = (
	"--traffic-log-file|f=s"=>	\$logfile,
	"--config-file|C=s"	=>	\$configfile,
	"--quiet|q"		=>	\$quiet,
	"--help|h"		=>	\$help,
	"--version|v"		=>	\$version,
);

Getopt::Long::config("no_ignore_case");
GetOptions(%options);

if($help)
{
	print STDERR <<EOF;
lms-traffic, version $_version
(C) 2001-2007 LMS Developers

-f, --traffic-log-file=/var/log/traffic.log	traffic log file (default: /var/log/traffic.log);
-C, --config-file=/etc/lms/lms.ini	alternate config file (default: /etc/lms/lms.ini);
-h, --help			print this help and exit;
-v, --version			print version info and exit;
-q, --quiet			suppress any output, except errors;

EOF
	exit 0;
}

if($version)
{
	print STDERR <<EOF;
lms-traffic, version $_version
(C) 2001-2007 LMS Developers

EOF
	exit 0;
}

if(!$configfile)
{
	$configfile = "/etc/lms/lms.ini";
}

if(!$quiet)
{
	print STDOUT "lms-traffic, version $_version\n";
	print STDOUT "(C) Copyright 2001-2007 LMS Developers\n";
	print STDOUT "Using file $configfile as config.\n";
}

if(! -r $configfile)
{
	print STDERR "Fatal error: Unable to read configuration file $configfile, exiting.\n";
	exit 1;
}

if(!$logfile)
{
	$logfile = "/var/log/traffic.log";
}

if(! -r $logfile)
{
	print STDERR "Fatal error: Unable to read log file $logfile, exiting.\n";
	exit 1;
}

my $ini = new Config::IniFiles -file => $configfile;
print @Config::IniFiles::errors;

my $dbtype = $ini->val('database', 'type') || 'mysql';
my $dbhost = $ini->val('database', 'host') || 'localhost';
my $dbuser = $ini->val('database', 'user') || 'root';
my $dbpasswd = $ini->val('database', 'password') || '';
my $dbname = $ini->val('database', 'database') || 'lms';

my $dbase;
my $utsfmt;

if($dbtype =~ /mysql/)
{
	$dbase = DBI->connect("DBI:mysql:database=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
	$utsfmt = "UNIX_TIMESTAMP()";
}
elsif($dbtype eq "postgres")
{
	$dbase = DBI->connect("DBI:Pg:dbname=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
	$utsfmt = "EXTRACT(EPOCH FROM CURRENT_TIMESTAMP(0))";
}
else
{
	print STDERR "Fatal error: unsupported database type: $dbtype, exiting.\n";
	exit 1;
}


# get nodes IDs table
my $dbq = $dbase->prepare("SELECT id, inet_ntoa(ipaddr) AS ipaddr FROM nodes");
$dbq->execute();
my %table;      
while (my $row = $dbq->fetchrow_hashref())
{    
    $table{$row->{'ipaddr'}} = $row->{'id'};
}

# read log file
open(LOGFILE, $logfile); 	
my(@lines) = <LOGFILE>;   
close(LOGFILE);

my %data;

# insert data to lms database 
foreach my $line (@lines)           
{
	my ($ip,$upload,$download) = split('[\t\s]+',$line);                 
	if( $table{$ip} )   # if IP is in our database then we can insert
	{
		if( $upload || $download ) # don't need zeroes 
		{
			$data{$ip}{'download'} += $download;
			$data{$ip}{'upload'} += $upload;
			
			if(!$quiet)
    			{
				print "IP: $ip\tSend: $upload\t Recv: $download\n";
			}
		} else
		{
			print "IP: $ip\tSkipped - null data\n";
		}
	} 
	else 
	{
		if(!$quiet)
		{
			print "IP: $ip\tSkipped - not in database\n";
		}
	}
}

while (my ($ip,$record) = each %data)
{
	$dbq = $dbase->prepare("INSERT INTO stats (nodeid, dt, download, upload) VALUES ( $table{$ip} , $utsfmt, $record->{'download'}, $record->{'upload'})");
	$dbq->execute();
}

# finally 
$dbq->finish();
$dbase->disconnect();
