#!/usr/local/bin/perl -s
# mailgrep - Find regexp in mail folder and say which message it is
#            usage:  mailgrep regexp [file ...]

$msgsep = "^From "; # how do we know when a new message starts?
$hdrend = "^\$"; # how do we know when the headers are done?
$startsig = "^((- )?-- |-----BEGIN PGP SIGNATURE-----)\$"; # line that introduces signature

$msg = 0; # initialize message counter
$header = 1; # start out assuming we're in the header
$signature = 0;
$shownone = 0;

$regexp = shift; # what we're looking for

# worry about filenames later
while (<>) {
  if (/$msgsep/o) {
    $lastmsg = $msg;
    $msg++;
    undef %HDRS;
    @hdrs=();
    $matched = 0;
    $header = 1;
    $signature = 0;

    # get as much info as we can from the envelope
    chop;
    @hdr = split;
    $HDRS{from} = " $hdr[1]" if $hdr[1];
    $hdr[2] = join(" ",@hdr[2..$#hdr]);
    $HDRS{date} = " $hdr[2]" if $hdr[2];

    # now get the real headers
    next;
  } elsif (/$hdrend/o) {
    $header=0;
    next;
  } elsif ($signature || (!$s && /$startsig/o)) {
    # ignore signatures if -s switch not given
    $signature = 1;
    next;
  }

  if ($header) {
    # save headers
    push(@hdrs,$_);
    chop;
    @hdr = split(/:/);
    $hdr[0] = lc($hdr[0]); # make it all lowercase
    $HDRS{$hdr[0]} = join(":",@hdr[1..$#hdr]);
    if ($h) {
      # -h says look for match in headers
      if (/$regexp/o || ($i && /$regexp/oi)) {
	if ($msg != $lastmsg) {
	  $matched=1;
	}
      }
    }
  } else {
    # is it there?
    if ($matched || /$regexp/o || ($i && /$regexp/oi)) {
      if ($msg != $lastmsg) {
        # new message, show some headers
	print "-----\n" if $shownone;
	if ($f) {
	  # print full headers
	  foreach $hdr (@hdrs) {
	    print $hdr;
	  }
	} else {
	  print "Message#: $msg\n";
	  print("Message-Id:$HDRS{'message-id'}\n") if $HDRS{'message-id'};
	  print("From:$HDRS{from}\n") if $HDRS{from};
	  print("Date:$HDRS{date}\n") if $HDRS{date};
	  print("Subject:$HDRS{subject}\n") if $HDRS{subject};
	}
	print "\n";
	$shownone = 1;
      }
      print if (/$regexp/o || ($i && /$regexp/oi));
    }
  }
}
