#! /usr/bin/env perl

#
# postrace - find logentrys for a specific mail
#
use 5.10.0;
use feature qw/switch/;

#
# where to find the mail logfile
#
my $OS_MAILLOG = '';
given ($^O) {
  when('netbsd') { $OS_MAILLOG="/var/log/maillog" }
### by jan
#  default { $OS_MAILLOG="/var/log/mail" }
  default { $OS_MAILLOG="/var/log/syslog" }
}

################################################
# Change below at your own risk
#
use strict;
use diagnostics;
use warnings;

use Getopt::Long;
use Pod::Usage;
use IO::File;
use IO::Uncompress::AnyUncompress qw(anyuncompress $AnyUncompressError);

my %opt=();
#
# check arguments
#
GetOptions(\%opt,
           'help|?',
           'man',
           'debug|d',
           'id=s',
           'email=s',
    ) or pod2usage(2);

# print help if option help is set or no arguments are given
pod2usage(-exitstatus => 0, -verbose => 2) if $opt{man};
pod2usage(1) if ($opt{help} );

my $MAILLOGS = ($#ARGV >= 0 )? \@ARGV : [ $OS_MAILLOG ] ;
my $msgid = $opt{id};
my $email = $opt{email};

#
# main
#
foreach my $MAILLOG ( @$MAILLOGS ) {
    my %QueueIDs = ();
    print "searching file $MAILLOG\n" if $opt{debug};
    my $fh;
    if ($MAILLOG =~ /.*\.(bz2|gz|Z)$/) {
        $fh = new IO::Uncompress::AnyUncompress $MAILLOG;
    } else {
        $fh = new IO::File $MAILLOG;
    }
    if (defined $fh) {
        # search queue IDs
        while (<$fh>) {
            chomp;
            if ( $msgid && /^.+ message-id=<$msgid>.*$/) {
                my $queueID = $_;
                $queueID =~ s/.*\]:? (.+):.+/$1/;
                print "$queueID" if ($opt{debug});
                $QueueIDs{$queueID}+=1;
            }
            if ($email && /postfix\/(from|to)=<$email>/i) {
                my $queueID = $_;
                $queueID =~ s/^.+ postfix\/.*\]:? ([A-Z0-9]{8,10}):?.+/$1/;
                print "$queueID\n" if ($opt{debug});
                #print $_."\n" if ($opt{debug});
                $QueueIDs{$queueID}+=1;
            }
        }
        $fh->close;
        ## rewind and print every line with relevant queue IDs
        print "\n\n------- Output --------\n\n" if ($opt{debug});
        print "\nopening logfile $MAILLOG\n\n";
        if ($MAILLOG =~ /.*\.(bz2|gz|Z)$/) {
            $fh = new IO::Uncompress::AnyUncompress $MAILLOG;
        } else {
            $fh = new IO::File $MAILLOG;
        }
        while (<$fh>) {
            my $ID_FOUND = 0;
            foreach my $id ( keys %QueueIDs ) {
                if ( / $id:/) {
                    print $_;
                    $ID_FOUND = 1;
                }
            }
            print $_ if ( $ID_FOUND == 0 && $msgid && /$msgid/ );
            print $_ if ( $ID_FOUND == 0 && $email && /<$email>/i );
        }
        $fh->close();
    } else {
      warn "cant open $MAILLOG: $!";
    }
}
