#!/usr/bin/perl
#
# LMS version 1.4.5 Persus
#
#  (C) 2001-2005 LMS Developers
#
#  Please, see the doc/AUTHORS for more information about authors!
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License Version 2 as
#  published by the Free Software Foundation.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
#  USA.
#
#  $Id: lms-squid-warnings,v 1.2.2.3 2005/01/01 19:19:08 alec Exp $

use DBI;
use Config::IniFiles;

my $configfile = '/etc/lms/lms.ini';

$|=1;

sub dotquad2u32($)
{
     my $dq = shift||'0.0.0.0';
     my @dq = split('\.',$dq,4);
     return ((($dq[0] << 8) + $dq[1] << 8) + $dq[2] << 8) + $dq[3];
}

my $ini = new Config::IniFiles -file => $configfile;

my $dbtype = $ini->val('database', 'type') || 'mysql';
my $dbhost = $ini->val('database', 'host') || 'localhost';
my $dbuser = $ini->val('database', 'user') || 'root';
my $dbpasswd = $ini->val('database', 'password') || '';
my $dbname = $ini->val('database', 'database') || 'lms';
my $redirect = $ini->val('squid-warnings', 'redirect') || 'http://lms.rulez.pl/';

while ($adres = <STDIN>) {
    if ((!defined($dbase))||($dbase->state)) 
    {
	if($dbtype eq "mysql")
	{
    	    $dbase = DBI->connect_cached("DBI:mysql:database=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
	}
	elsif($dbtype eq "postgres")
	{
    	    $dbase = DBI->connect_cached("DBI:Pg:dbname=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
	}
	elsif($dbtype eq "sqlite")
	{
    	    $dbase = DBI->connect_cached("DBI:SQLite:dbname=$dbname;host=$dbhost","$dbuser","$dbpasswd", { RaiseError => 1 });
    	    $dbase->func('inet_aton',1,'dotquad2u32','create_function');     
	}
	else
	{
    	    print STDERR "Fatal error: unsupported database type: $dbtype, exiting.\n";
    	    exit 1;
	}

	$dbq = $dbase->prepare_cached("SELECT warning FROM nodes WHERE ipaddr=INET_ATON(?)");
    }
    @lista = split(' ', $adres);
    @ip = split('/', $lista[1]);
    $dbq->execute($ip[0]);
    my $row = $dbq->fetchrow_hashref();
    if ($row->{'warning'}=='1') {
	if (!($lista[0] =~ m/$redirect/)) {
	    $lista[0] = $redirect."?oldurl=".$lista[0];
	    $adres = join(' ',@lista)."\n";
	}
    }
    print $adres;
}
$dbq->finish;
$dbase->disconnect();
