#!/usr/bin/perl
use POSIX;
use File::Temp;

$conf=shift||'/data/local/dialupadmin/conf/admin.conf';
$back_days = 80;
$backup_directory = "/logs/radiusd/accounting";

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_type = $val if ($key eq 'sql_type');
	$sql_port = $val if ($key eq 'sql_port');
	$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');
	$sqlcmd = $val if ($key eq 'sql_command');
}
close CONF;

die "sql_command directive is not set in admin.conf\n" if ($sqlcmd eq '');
die "sql command '$sqlcmd' not found or does not seem to be executable\n" if (! -x $sqlcmd);
if ($sql_type eq 'mysql'){
	$sql_password = ($sql_password eq '') ? '' : "-p$sql_password";
}
$sql_password =~ s/(\W)/\\$1/g;

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
$date = POSIX::strftime("%Y-%m-%d",$sec,$min,$hour,($mday - ($back_days - 1)),$mon,$year,$wday,$yday,$isdst);
$date2 = POSIX::strftime("%Y-%m-%d",$sec,$min,$hour,($mday - ($back_days + 1)),$mon,$year,$wday,$yday,$isdst);
$date3 = POSIX::strftime("%Y%m%d",$sec,$min,$hour,($mday - $back_days),$mon,$year,$wday,$yday,$isdst);
if (POSIX::strftime("%Y-%m-%d %T",localtime) eq $date){
	die "Could not set correct back date.\n";
}

$query = "SELECT * FROM $sql_accounting_table WHERE AcctStopTime < '$date' AND AcctStopTime > '$date2';";
print "$query\n";
my ($fh, $tmp_filename) = tempfile() or die "Could not open tmp file\n";
print $fh "ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT='YYYY-MM-DD HH24:MI:SS.FF TZH:TZM';\n" if ($sql_type eq 'oracle');
print $fh $query;
close $fh;
$comm = "$sqlcmd -B -h $sql_server -u $sql_username $sql_password $sql_database < $tmp_filename >$backup_directory/$date3" if ($sql_type eq 'mysql');
$comm = "$sqlcmd  -U $sql_username -f $tmp_filename $sql_database >$backup_directory/$date3" if ($sql_type eq 'pg');
$command = "$sqlcmd  $sql_username/$pass" . "@" . "$sql_database <$tmpfile.$server" if ($sql_type eq 'oracle');
$command = "$sqlcmd '$sql_server' '$sql_port' '' '$sql_username' '$sql_password' < $tmp_filename >$backup_directory/$date3" if ($sql_type eq 'sqlrelay');
`$comm`;
`/usr/local/bin/gzip -9 $backup_directory/$date3`;
