#!/usr/bin/perl
# Delist an IP
# 2010/09/07 kdeugau@deepnet.cx

use strict;
use warnings;
use DBI;

use DNSBL;

my $dnsbl = new DNSBL;

# default DB info - all other settings should be loaded from the DB.
my $dbhost = "localhost";
my $dbname = "dnsbl";
my $dbuser = "dnsbl";
my $dbpass = "spambgone";

die "Usage: delist-ip <list> <IP>\n".
	"  <list> should be the DNSBL you want to remove the IP from\n"
	if !$ARGV[1];
my $cfgname = shift @ARGV;

# Load a config ref containing DB host, name, user, and pass info based on
# from the server name + full script web path.  This allows us to host
# multiple instances without having to duplicate the code.
# This file is a Perl fragment to be processed inline.
if (-e "/etc/dnsbl/$cfgname.conf") {
  my $cfg = `cat /etc/dnsbl/$cfgname.conf`;
  ($cfg) = ($cfg =~ /^(.+)$/s);         # avoid warnings, failures, and general nastiness with taint mode
  eval $cfg;
}

my $dbh = $dnsbl->connect($dbhost, $dbname, $dbuser, $dbpass);

my %config;
my $sth = $dbh->prepare("SELECT key,value FROM misc");
$sth->execute;
while (my ($key,$value) = $sth->fetchrow_array) {
  $config{$key} = $value;
}

my $removeme = $ARGV[0];

$sth = $dbh->prepare("SELECT ip,count,s4list,added FROM iplist WHERE ip=?");
$sth->execute($removeme);
my ($ip,$count,$s4list,$added) = $sth->fetchrow_array;

die "IP $removeme not found.  Exiting.\n" if !$ip;

# need to do the next in a single transaction
local $dbh->{AutoCommit} = 0;
local $dbh->{RaiseError} = 1;
eval {
  $sth = $dbh->prepare("INSERT INTO waslisted (ip,count,s4list,origadded) VALUES (?,?,?,?)");
  $sth->execute($ip,$count,$s4list,$added);
  $sth = $dbh->prepare("DELETE FROM iplist WHERE ip=?");
  $sth->execute($ip);
  $dbh->commit;
};
if ($@) {
  my $msg = $@;
  eval { $dbh->rollback; };
  print "Failed to move record from iplist to waslisted: $msg\n";
}
