#!/usr/bin/perl
# Export DNSBL data
# 2009/05/26 kdeugau@deepnet.cx
# need to stub it out so it can use a module to actually write zone
# data for different NS software
# completed 2008/08/14

use strict;
use warnings;
use DBI;

use DNSBL;

my $dnsbl = new DNSBL;

$dnsbl->connect;

my %iplist;
my $ipref = \%iplist;

my $mode = $ARGV[0] || 'tiny';

#$dnsbl->export($ipref,$mode,1,'65.60/18');
#$dnsbl->export($ipref,$mode,1,'67.136.0.0/14');
#$dnsbl->export($ipref,$mode,1,'83.76/15');
#$dnsbl->export($ipref,$mode,1,'76.73.0.0/17');
#$dnsbl->export($ipref,$mode,1,'174.36.0.0/15');
$dnsbl->initexport;
$dnsbl->export($ipref,$mode);

##fixme - mode should pick actual output, not just export mode
if ($mode eq 'cidr') {
  # SOA, NS records.  Maybe dnscache needs them?
  print "\$SOA 900 company.dnsbl systems.company.com 0 1200 600 600 900\n".
	"\$NS 3600 127.0.0.1\n".
	"\$TTL 900\n";

  # more or less raw CIDR block-and-IP info.  rbldnsd format for convenience.
  foreach (sort ipcmp keys %iplist) {
    print "$_:127.0.0.$iplist{$_}:".
	($iplist{$_} & 2 ? '$ relayed a reported spam' : 'Netblock listed on one or more criteria')."\n";
  }
} else {
  foreach (sort ipcmp keys %iplist) {
    my ($o1,$o2,$o3,$o4) = (/^(\d+)\.([\d*]+)(?:\.([\d*]+)(?:\.([\d*]+))?)?$/);
    print "+".(defined($o4) ? "$o4." : '').(defined($o3) ? "$o3." : '').(defined($o2) ? "$o2." : '').
	"$o1.spamhosts.company.com:127.0.0.$iplist{$_}:900:::\n";
  }
}

exit 0;

# IP address comparison sub
sub ipcmp {
  my ($a1,$a2,$a3,$a4,$a5) = ($a =~ /^(\d+)\.([\d*]+)(?:\.([\d*]+)(?:\.([\d*]+))?)?(?:\/(\d+))?$/);
  my ($b1,$b2,$b3,$b4,$b5) = ($b =~ /^(\d+)\.([\d*]+)(?:\.([\d*]+)(?:\.([\d*]+))?)?(?:\/(\d+))?$/);
# le sigh.  knew it wasn't going to be simple...
  $b2 = -1 if $b2 && $b2 eq '*';
  $b3 = -1 if $b3 && $b3 eq '*';
  $b4 = -1 if $b4 && $b4 eq '*';
  $b5 = 128 if !defined($b5);
  $a2 = -1 if $a2 && $a2 eq '*';
  $a3 = -1 if $a3 && $a3 eq '*';
  $a4 = -1 if $a4 && $a4 eq '*';
  $a5 = 128 if !defined($a5);
  return 1 if $a1 > $b1;
  return -1 if $a1 < $b1;
  return 1 if $a2 > $b2;
  return -1 if $a2 < $b2;
  return 1 if $a3 > $b3;
  return -1 if $a3 < $b3;
  return 1 if $a4 > $b4;
  return -1 if $a4 < $b4;
  return 1 if $a5 > $b5;
  return -1 if $a5 < $b5;
  return 0;
}
