#!/usr/bin/perl

use strict;

sub match_email
{
	my ($pattern, $subject) = @_;
	return ( defined($pattern) && (
		$pattern =~ /^@/
		? ( $subject =~ /(\@.*)$/ && lc($pattern) eq lc($1) )
		: ( lc($pattern) eq lc($subject) )
	) );
}

#print( match_email("\@drh.net", "dharris\@drh.net") ? "true\n" : "false\n");
#exit 1;

my $envelope_sender;
my $recipient;

while (@ARGV) {
	my $option = lc(shift);
	if ( $option eq "--sender" ) {
		die "missing argument for --sender" if ( @ARGV < 1 );
		$envelope_sender = shift;
	}
	elsif ( $option eq "--recipient" ) {
		die "missing argument for --recipient" if ( @ARGV < 1 );
		$recipient = shift;
	}
	else {
		die "bad option ($option)";
	}
}

my $watching_message_ids = {};
my $watching_delivery_ids = {};

my $saved_info_lines = {};

while( <> )
{
	if ( /info msg (\d+): bytes \d+ from <(.*)>/ ) {
		if ( match_email($envelope_sender, $2) ) {
			$watching_message_ids->{$1} = 1;
			print;
		} else {
			$saved_info_lines->{$1} = $_;
		}
	}
	elsif ( /end msg (\d+)/ && exists($watching_message_ids->{$1}) ) {
		delete $watching_message_ids->{$1};
		print;
	}
	elsif ( /starting delivery (\d+): msg (\d+) to \S+ (\S+)/ ) {
		if ( exists($watching_message_ids->{$2}) ) {
			$watching_delivery_ids->{$1} = 1;
			print;
		} elsif ( match_email($recipient, $3) ) {
			if ( exists $saved_info_lines->{$2} ) {
				print $saved_info_lines->{$2};
				print "--> only showing deliveries for this recipient on msg $1\n";
			}
			print;
			$watching_delivery_ids->{$1} = 1;
		}
		delete($saved_info_lines->{$2});
	}
	elsif ( /delivery (\d+):/ && exists($watching_delivery_ids->{$1}) ) {
		delete $watching_delivery_ids->{$1};
		print;
	}
	elsif ( /msg (\d+)/ && exists($watching_message_ids->{$1}) ) {
		print;
	}
}


