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

use DBI;
use Switch;
use FindBin qw($Bin);

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

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);

my $time = localtime; # scalar context
print LOG "$$ - $time - Start\n";

while (<>) {
	print LOG "$$ - $time - $_\n";
	my ($name, $ip, $host) = &shellwords;
	
	if (cerca($ip,$host, -1)) {
		print LOG "$ip, $host, -1 - ERR\n";
		print "ERR\n";
	} else {
		if (cerca($ip,$host, 1)) {
			print LOG "$ip, $host, -1 - OK\n";
			print "OK\n";
		} else {
			print LOG "$ip, $host, -1 - ERR\n";
			print "ERR\n";
		}
	}
}
exit;

sub cerca {
	my $ip = shift;
	my $url = shift;
	my $stato = shift;

	if ($stato == 1) {
		$tutto = "";
	} else {
		$tutto = "";
	}

	$query = "	SELECT
				1
			FROM
				proxy_pool
			JOIN
				proxy_acl_ip
				ON
					proxy_pool.id = proxy_acl_ip.idpool
					AND
					proxy_acl_ip.stato = $stato
			JOIN
				proxy_acl_list
				ON
					proxy_acl_ip.idacllist = proxy_acl_list.id
					AND
					proxy_acl_list.attivo = 1
			JOIN
				proxy_acl
				ON
					proxy_acl.idacllist = proxy_acl_list.id
					AND
					proxy_acl.attivo = 1
					AND
					LOCATE(proxy_acl.rif, '$url') > 0
			WHERE
				proxy_pool.ip = '$ip'
			UNION DISTINCT SELECT
					1
				FROM
					proxy_pool
				JOIN
					proxy_acl_ip
					ON
						proxy_pool.id = proxy_acl_ip.idpool
						AND
						proxy_acl_ip.stato = $stato
				JOIN
					proxy_acl_list
					ON
					proxy_acl_ip.idacllist = proxy_acl_list.id
					AND
					proxy_acl_list.nome = 'ALL'
				WHERE
					proxy_pool.ip = '$ip'
			UNION DISTINCT SELECT
					1
				FROM
					proxy_acl
				JOIN
					proxy_acl_list
					ON
					proxy_acl_list.id = proxy_acl.idacllist
				WHERE
					LOCATE(proxy_acl.rif, '$url') > 0
					AND
					proxy_acl_list.dflt = $stato
					AND
					proxy_acl_list.id NOT IN (
						SELECT
							proxy_acl_ip.idacllist
						FROM
							proxy_acl_ip
						JOIN
							proxy_pool
						ON
							proxy_pool.id = proxy_acl_ip.idpool
					WHERE
						proxy_pool.ip = '$ip'
					)

	";

#	print LOG "$query\n";
	$sts = $dbmysql->prepare($query);
	$sts->execute ();

	if ($ref = $sts->fetchrow_hashref ) {
		return 1;
	} else {
		return 0;
	}
}
