#!/usr/bin/perl -w
#
# postfix-pdel.nl - deletes message containing specified address from
# Postfix queue. Matches either sender or recipient address.
#
# Usage: postfix-pdel.nl <pattern>
#

use strict;
use File::Basename;

my $scriptname = basename($0);

my $func = "";
if ( $scriptname eq "postfix-pdel.nl" ) {
    $func = "-d";
} elsif ( $scriptname eq "postfix-phold.nl" ) {
    $func = "-h";
} elsif ( $scriptname eq "postfix-punhold.nl" ) {
    $func = "-H";
}

my $MAILCONF = "/etc/postfix-nl";

$ENV{'MAIL_CONFIG'} = $MAILCONF;

# Change these paths if necessary.
my $CHRBIN = "/usr/sbin/chroot";
my $CHRDIR = "/chroot/maild";

my $LISTQ = "/usr/sbin/postqueue -c $MAILCONF -p";
my $POSTSUPER = "/usr/sbin/postsuper";

my $CHRMAILCONF = "$CHRDIR/etc/postfix-nl";

if (-d $CHRMAILCONF) {
	$LISTQ = "$CHRBIN $CHRDIR /usr/sbin/postqueue -c $MAILCONF -p";
}

my $email_addr = "";
my $qid = "";
my $euid = $>;

if ( @ARGV !=  1 ) {
    die "Usage: $0 <pattern>\n";
} else {
    $email_addr = $ARGV[0];
}

if ( $euid != 0 ) {
        die "You must be root to manage queue files.\n";
}


open(QUEUE, "$LISTQ |") || 
  die "Can't get pipe to $LISTQ: $!\n";

my $entry = <QUEUE>;	# skip single header line
$/ = "";		# Rest of queue entries print on
	    # multiple lines.
while ( $entry = <QUEUE> ) {
#    if ( $entry =~ / $email_addr$/m ) {
    if ( $entry =~ /$email_addr[^\s]*$/m ) {
	($qid) = split(/\s+/, $entry, 2);
	$qid =~ s/[\*\!]//;
	next unless ($qid);

	#
	# Execute postsuper -d with the queue id.
	# postsuper provides feedback when it deletes
	# messages. Let its output go through.
	#
#	if ( system($POSTSUPER, $func, $qid) != 0 ) {
#	    # If postsuper has a problem, bail.
#	    die "Error executing $POSTSUPER: error " .
#	       "code " .  ($?/256) . "\n";
#	}
	if (-d $CHRMAILCONF) {
		if ( system($CHRBIN, $CHRDIR, $POSTSUPER, "-c", $MAILCONF, $func, $qid) != 0 ) {
		    # If postsuper has a problem, bail.
		    die "Error executing $POSTSUPER in $CHRDIR chroot: error " .
		       "code " .  ($?/256) . "\n";
		}
	} else {
		if ( system($POSTSUPER, "-c", $MAILCONF, $func, $qid) != 0 ) {
		    # If postsuper has a problem, bail.
		    die "Error executing $POSTSUPER: error " .
		       "code " .  ($?/256) . "\n";
		}
	}

    }
}
close(QUEUE);

if (! $qid ) {
    die "No messages with the address <$email_addr> " .
      "found in queue.\n";
}

exit 0;
