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

use DBI;
use Switch;
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, ">> /srv/www/htdocs/pannello_vbc/proxy/squid_acl/squid_pool.log";
#LOG->autoflush(1);

alarm $timeout;
while($limit) {
	my $query = "";
	my $input = <>;
	chop $input;

#	my ($acl, $ip) = split / /, $input;
	my @param = split / /, $input;

	switch ($param[0]) {
		case "permessi"	{ 
					$query = "SELECT id FROM proxy_src WHERE ip = '".$param[1]."' AND attivo = 1"; 
					@reply = ("OK\n", "ERR\n");
					my $time = localtime; # scalar context
					#print LOG "$$ - $time - $limit - $input -\n";
					$limit--;
					alarm $timeout;
				}
		case "utenti"	{ 	
					$query = "SELECT id FROM proxy_utenti WHERE user = '".$param[1]."' AND pass = PASSWORD('".$param[2]."') AND attivo = 1"; 
					@reply = ("OK\n", "ERR\n");
					my $time = localtime; # scalar context
					#print LOG "$$ - $time - $limit - $input -\n";
					$limit--;
					alarm $timeout;
				}
		else		{
					$limit = 0;
				}
	}

	next if ($query eq "");

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

	if ($ref = $sts->fetchrow_hashref ) {
		print $reply[0];
	} else {
		print $reply[1];
	}
}
exit;
