#!/usr/bin/perl

use strict;
use warnings;
use CGI::Carp qw (fatalsToBrowser);
use CGI::Simple;
use HTML::Template;
use DNSBL;

# Set up the CGI object...
my $q = new CGI::Simple;
# ... and get query-string params as well as POST params if necessary
$q->parse_query_string;

my %webvar;
# This is probably excessive fiddling, but it puts the parameters somewhere my fingers know about...
foreach ($q->param()) {
  $webvar{$_} = $q->param($_);
}

my $dnsbl = new DNSBL;

$dnsbl->connect;

print "Content-type: text/html\n\n";

my $page;
my $templatedir = "templates";

# decide which page to spit out...
if (!$webvar{page}) {
  $page = HTML::Template->new(filename => "$templatedir/index.tmpl");
} else {
  $page = HTML::Template->new(filename => "$templatedir/$webvar{page}.tmpl");
}

if ($webvar{page} eq 'report') {
  $page->param(ip => $webvar{ip});
  for (my $i=0; $i<3; $i++) {
    my ($block,$org) = $dnsbl->getcontainer($webvar{ip},$i);
    if ($block) {
      $page->param("block$i" => $block);
      $page->param("org$i" => $org);
    }
  }
} elsif ($webvar{page} eq 'dbreport') {
  my $count = $dnsbl->report($webvar{ip});
  my $org0id = $dnsbl->orgexists($webvar{org0});
  if (!$org0id) {
    $org0id = $dnsbl->addorg($webvar{org0});
    $page->param(org0 => $webvar{org0});
  }
  if (!$dnsbl->blockexists($webvar{block0})) {
    $dnsbl->addblock($webvar{block0}, $org0id, 0);
    $page->param(block0 => $webvar{block0});
  }
# yes, this is grotty.  PTHBTT!
  if ($webvar{block1}) {
    my $org1id = $dnsbl->orgexists($webvar{org1});
    if (!$org1id) {
      $org1id = $dnsbl->addorg($webvar{org1});
      $page->param(org1 => $webvar{org1});
    }
    if (!$dnsbl->blockexists($webvar{block1})) {
      $dnsbl->addblock($webvar{block1}, $org1id, 1);
      $page->param(block1 => $webvar{block1});
    }
    if ($webvar{block2}) {
      my $org2id = $dnsbl->orgexists($webvar{org2});
      if (!$org2id) {
        $org2id = $dnsbl->addorg($webvar{org2});
        $page->param(org2 => $webvar{org2});
      }
      if (!$dnsbl->blockexists($webvar{block2})) {
        $dnsbl->addblock($webvar{block2}, $org2id, 2);
        $page->param(block2 => $webvar{block2});
      }
    }
  }

  $page->param(ip => $webvar{ip});
}
print $page->output;
