#!/usr/bin/perl -w
###########################################################################
#
#      greylist_canary.pl
#
###########################################################################

use strict;
use DBI;

my $date = localtime;
my $i = 0;
my $host = "";
my $mail_from = "";
my $rcpt_to = "";
my $block = "";
my $pass = "";

# put your mysql connect options here
my $mydb = "XXX";
my $myhost = "XXX";
my $myuser = "XXX";
my $mypasswd = 'XXX';



my $dbh = DBI->connect("DBI:mysql:$mydb:$myhost", "$myuser", "$mypasswd") || print FILE "$date Can't connect\n";

my $sth = $dbh->prepare("SELECT name from $mydb.canary");
my $passed_sth = $dbh->prepare("SELECT id  from $mydb.relaytofrom where passed_count > 0 AND relay_ip = ?");
my $ip_sth = $dbh->prepare("SELECT relay_ip from $mydb.relaytofrom where rcpt_to = ?");
my $black_sth = $dbh->prepare("UPDATE $mydb.relaytofrom SET block_expires=DATE_ADD(NOW(), INTERVAL 6 DAY) , record_expires=DATE_ADD(NOW(), INTERVAL 6 DAY) WHERE relay_ip = ? AND block_expires != record_expires");

$sth->execute();
my @ban;
while ($_ = $sth->fetchrow_array) {
	$ip_sth->execute($_);
	while ($_ = $ip_sth->fetchrow_array) {
		$passed_sth->execute($_);
		push @ban, $_ unless $passed_sth->fetchrow_array;
	}
}

foreach (@ban) {
	$black_sth->execute($_);
}

$sth->finish;
$ip_sth->finish;
$passed_sth->finish;

$dbh->disconnect;
close(FILE);
