#!/usr/bin/perl
# Delist an IP
##
# $Id: delist-ip 92 2025-09-16 19:56:31Z kdeugau $
# Copyright 2011,2012,2018,2025 Kris Deugau <kdeugau@deepnet.cx>
# 
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version. 
# 
#    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, see <http://www.gnu.org/licenses/>.
##

use strict;
use warnings;
use DBI;

# push "the directory the script is in" into @INC
use FindBin;
use lib "$FindBin::RealBin/";

use DNSBL 3.0;

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;

my $dnsbl = new DNSBL (configfile => "/etc/dnsbl/$cfgname.conf");
$dnsbl->connect;

my $removeme = $ARGV[0];

$sth = $dbh->prepare("SELECT ip,count,s4list,added,exclude FROM iplist WHERE ip=?");
$sth->execute($removeme);
my ($ip,$count,$s4list,$added,$exclude) = $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,exclude) VALUES (?,?,?,?,?)");
  $sth->execute($ip,$count,$s4list,$added,$exclude);
  $sth = $dbh->prepare("DELETE FROM iplist WHERE ip=?");
  $sth->execute($ip);
  $dbh->do("UPDATE blocks SET ipcount=ipcount-1 WHERE block >> ?", undef, ($ip));
  $dbh->commit;
};
if ($@) {
  my $msg = $@;
  eval { $dbh->rollback; };
  print "Failed to move record from iplist to waslisted: $msg\n";
}
