#!/usr/bin/perl
use POSIX;

# Log in the mtotacct table aggregated accounting information for
# each user spaning in one month period.
# If the current month has not ended it will log information up to
# the current month day

$conf=shift||'/usr/local/dialupadmin/conf/admin.conf';
$mysql='/usr/local/mysql/bin/mysql';

open CONF, "<$conf"
	or die "Could not open configuration file\n";
while(<CONF>){
	chomp;
	($key,$val)=(split /:\s*/,$_);
	$sql_server = $val if ($key eq 'sql_server');
	$sql_username = $val if ($key eq 'sql_username');
	$sql_password = $val if ($key eq 'sql_password');
	$sql_database = $val if ($key eq 'sql_database');
	$sql_accounting_table = $val if ($key eq 'sql_accounting_table');
}
close CONF;

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
if ($mday == 1){
	$mon--;
}
$date_start = POSIX::strftime("%Y-%m-%d",0,0,0,1,$mon,$year,$wday,$yday,$isdst);
$date_end = POSIX::strftime("%Y-%m-%d",0,0,0,$mday,$mon,$year,$wday,$yday,$isdst);

$query1 = "DELETE FROM mtotacct WHERE AcctDate = '$date_start';";
$query2 = "INSERT INTO mtotacct (UserName,AcctDate,ConnNum,ConnTotDuration,
	ConnMaxDuration,ConnMinDuration,InputOctets,OutputOctets,NASIPAddress)
	SELECT UserName,'$date_start',SUM(ConnNum),SUM(ConnTotDuration),
	MAX(ConnMaxDuration),MIN(ConnMinDuration),SUM(InputOctets),
	SUM(OutputOctets),NASIPAddress FROM totacct
	WHERE AcctDate >= '$date_start' AND
	AcctDate <= '$date_end' GROUP BY UserName;";
print "$query1\n";
print "$query2\n";
open TMP, ">/tmp/tot_stats.query"
	or die "Could not open tmp file\n";
print TMP $query1;
print TMP $query2;
close TMP;
`$mysql -h $sql_server -u $sql_username -p$sql_password $sql_database </tmp/tot_stats.query`;
