#! /usr/bin/perl -w
# vim:syntax=perl

use strict;

my $program = $0;
$program =~ s#^.*/##;

sub usage {
    print("$program <SMTP field> [<message file>]\n") or die;
}

if (defined $ARGV[1]) {
    open(FIN,"$ARGV[1]") || die("Cannot open $ARGV[1]");
} elsif (defined $ARGV[0]) {
    open(FIN,"<&STDIN") or die "cannot open stdin\n";
} else {
    usage();
    exit 2
}
$|=1;

my $string = lc $ARGV[0];
my ($line,$found_field,$rfc822);

$rfc822 = 0;
$found_field=0;
while ( defined ($line = <FIN>) ) {
    chomp $line ;
    next if ( $line =~ /^From\s/ );
    $rfc822 = 1 if ( $line =~ /^Received:\s(.*)$/ && ! $rfc822 );
    last if ( $line =~ /^\s*$/ );

    if ( $line =~ /^([-\w]+):/ ) {
	if ( lc $1 eq $string ) {
	    my ( $field, $value ) = split / /, $line, 2;
	    print "$value\n" or die;
	    $found_field = 1;
	} else {
	    $found_field = 0;
	}
    } elsif ( $found_field && $line =~ /^\s+(.*)/ ) {
	# Print header continuation
	print $line, "\n" or die;
    }
}
close(FIN) or die;

if ($rfc822) {
    exit 0;
} else {
    exit 1;
}

__END__

=pod

=head1 NAME 

lr_smtpfield - extract a message header field from an 822 message

=head1 SYNOPSIS

B<lr_smtpfield> I<fieldname>

=head1 DESCRIPTION

The format of an email header, when stored in a traditional
var/spool/mail-type mailbox, is

 "From <user>"
 "Field: <something>"
 ""

B<lr_smtpfield> expects an RFC822 message on stdin or a file containing
such a message as it's last argument.  It prints the I<fieldname>'s value
to stdout, if found.  Return value is 0 if input was an RFC822 message,
1 if input was not an RFC822 message, 2 if a command line error occured.

=head1 SEE ALSO

822field(1), in the mess822 package

=head1 AUTHOR

Edwin Groothuis <edwin@mavetju.org>

=head1 VERSION

$Id: lr_smtpfield.in,v 1.8 2001/11/14 17:07:31 flacoste Exp $

=head1 COPYRIGHT

Copyright (C) 2000-2001 Stichting LogReport Foundation LogReport@LogReport.org

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 2 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 (see COPYING); if not, check with
http://www.gnu.org/copyleft/gpl.html or write to the Free Software 
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.

=cut

# Local Variables:
# mode: cperl
# End:
