#!/usr/bin/perl
$|=1;

use DBI;
use FindBin qw($Bin);

require "$Bin/../script/conntrack.conf";

local $SIG{ALRM} = sub {
	my $time = localtime; # scalar context
#	print LOG "$$ - $time - Exit\n";
	exit 1;
};

srand($$);
$timeout = 60 * (int(rand(5))+61);
$limit = 50;

my $dbmysql = DBI->connect("DBI:mysql:;host=$DBhost", $DBuser, $DBpass) or die ($DBI::errstr);
$sts = $dbmysql->prepare("use $DBname");
$sts->execute ();

open LOG, ">> /usr/local/mybin/proxy/squid_acl/squid_pool.log";
LOG->autoflush(1);
#					pass = PASSWORD('".$param[1]."') 

alarm $timeout;
while($limit) {
	my $query = "";
	my $input = <>;
	print LOG "AUTH -- $input\n";
	chop $input;

	my @param = split / /, $input;

	if ($param[0] ne "") {
		$query = "	SELECT 
					id, 
					primo, 
					(tempo*3600)-time_to_sec(timediff(ultimo, primo)) AS rimasto, 
					tempo 
				FROM 
					proxy_utenti 
				WHERE 
					user = '".$param[0]."' 
					AND 
					pass = ENCRYPT('".$param[1]."',LEFT(pass, 2)) 
					AND 
					attivo = 1";
		$limit--;
		alarm $timeout;
	} else {
		$limit = 0;
	}

	next if ($query eq "");

	$sts = $dbmysql->prepare($query);
	$sts->execute ();

	if ($ref = $sts->fetchrow_hashref ) {
		my $id = $$ref{'id'};
		my $primo = $$ref{'primo'};
		my $rimasto = $$ref{'rimasto'};
		my $tempo = $$ref{'tempo'};

		my $agg = "";
		my $query = "";
		if (($tempo > 0) && ($rimasto < 0)){
			$agg = "attivo = 0,";
		}

		if (!$primo) {
			$query = "UPDATE proxy_utenti SET $agg primo =  NOW(), ultimo = NOW() WHERE id = $id";
		} else {
			$query = "UPDATE proxy_utenti SET $agg ultimo = NOW() WHERE id = $id";
		}
#		print LOG "$rimasto -- $query\n";
		$sts = $dbmysql->prepare($query);
		$sts->execute ();
		print "OK\n";
	} else {
		print "ERR\n";
	}
}
exit;
