#!/usr/bin/perl -w

# use perl                                  -*- mode: Perl; -*-
eval 'exec perl -S $0 "$@"'
  if $running_under_some_shell;

use vars qw($running_under_some_shell);         # no whining!

use constant DEBUG => 0;

require 5.00396;

# grepmail version 3.4

# Grepmail searches a normal, gzip'd, or bzip2'd mailbox for a given regular
# expression and returns those emails that match the query. It also supports
# piped compressed or ascii input, and searches constrained by date. 

# If you would like to be notified of updates, send email to me at
# coppit@cs.virginia.edu

# Do a pod2text on this file to get full documentation, or pod2man to get
# man pages.

# Written by David Coppit (coppit@cs.virginia.edu,
#  http://www.cs.virginia.edu/~dwc3q/index.html)

# Please send me any modifications you make. (for the better, that is. :) I
# have a suite of tests that I can give you if you ask. Keep in mind that I'm
# likely to turn down obscure features to avoid including everything but the
# kitchen sink.

# This code is distributed under the GNU General Public License (GPL). See
# http://www.opensource.org/gpl-license.html and http://www.opensource.org/.

# Version History (major changes only)
# 3.4 Added tzip support (thanks to Marc Lehmann <pcg@goof.com>). Changed
#   command line syntax again. (Last time, I hope.)
# 3.3 Added bzip2 support (thanks to Josh Plautz <plautz@milner.com>).
#   Improved error checking on piped binary input. Added debugging code.
# 3.2 Added TMPFILE environment variable support, and a signal handler (thanks
#   to Ulli Horlacher (<framstag@moep.bb.bawue.de>). Fixed a bug where the
#   last paragraph of the last email in a mailbox would not be printed on
#   Linux. (How's that for obscure? Thanks to Eli Criffield
#   <rexracer@mammoth.org> for discovering it.)
# 3.1 Added -m, which prints the folder name in which the email was found as
#   an "X-Mailfolder" addition to the header (by Ulli Horlacher
#   <framstag@moep.bb.bawue.de>). Improved error checking on flags. Changed
#   "zcat" to "gunzip -c" to help with backwards compatibility with older
#   versions of gzip (thanks to Eugene Kim <eekim@eekim.com>).
# 3.0 -h and -b can be used together. Rewrote the ProcessMailFile to run 2 to
#   3 times faster, and use less memory. Correctly diagnoses directories as
#   such (by Gerald Pfeifer <pfeifer@dbai.tuwien.ac.at>).
# 2.1 Added -l,-r, and -e, as suggested by Reinhard Max <max@suse.de>. Now
#   uses about 1/3 the memory, and is a little faster.
# 2.0 Added POD documentation at the end of the script (thanks, Jeffrey
#   Haemer <jsh@boulder.qms.com>). -h for headers only -b for body only
# 1.9 "Ignore empty files" by Gerald Pfeifer <pfeifer@dbai.tuwien.ac.at>.
#   Emails without dates are now automatically output no matter what the
#   date specification is. (Better safe than sorry!)
# 1.7 Sped up by Andrew Johnson. It no longer looks for dates unless
#   the email matches the search string.
# 1.6 removed use of Compress::Zlib because it was 30% slower, complicated the
#   code, and because any user with gzip'd mail has zcat...
# 1.5 Andrew Johnson <ajohnson@gpu.srv.ualberta.ca> fixed a couple of bugs.
# 1.4 Incorporated conditional loading of the date module, use of
#   compress::Zlib instead of shelling out to gunzip, as well as some bug
#   fixes, as submitted by Andrew Johnson <ajohnson@gpu.srv.ualberta.ca>
#   (Many thanks!). Also restructured the code a bit.
# 1.3 Made it pipeable so you can do:
#   grepmail <pattern> file | grepmail <pattern>
# 1.1 Support for dates.
# 1.0 Initial version, with -v -i, and gzip support

# Notes:
# It turns out that -h, -b, and -v have some nasty feature interaction. Here's
# a table of how matching should occur for each combination of flags:
#
#  B, H,!V
#  Match if body and header matches
#  B,!H,!V
#  Match if body matches -- don't care about header
# !B, H,!V
#  Match if header matches -- don't care about body
# -V strictly inverts each of the above cases.
#
#  The best way to think about this is using Venn diagrams. (Especially when
#  trying to figure out whether the header uniquely determines whether the
#  email matches.

use strict;
use FileHandle;
use Getopt::Std;
use Carp;

sub usage
{
<<EOF;
usage: grepmail [-vihblrm] [[-e] <expr>] [-d \"datespec\"] <files...>

-h Search must match header
-b Search must match body
-l Output the names of files having an email matching the expression
-r Output the names of the files and the number of emails matching the
   expression
-m Append "X-Mailfolder: <folder>" to all headers to indicate in which folder
   the match occurred
-i Ignore case in the search expression
-v Output emails that don't match the expression
-e Explicitely name expr (when searching for strings beginning with "-")

Date specifications must be of the form of:
a date like "today", "1st thursday in June 1992", "05/10/93",
  "12:30 Dec 12th 1880", "8:00pm december tenth",
OR "before", "after", or "since", followed by a date as defined above,
OR "between <date> and <date>", where <date> is defined as above.

Files can be plain ASCII or ASCII files compressed with gzip, tzip, or bzip2.
You can also pipe normal or compressed ASCII to grepmail.
EOF
}

#-------------------------------------------------------------------------------

sub cleanExit
{
  my $message;

  if (@_)
  {
    $message = shift;
  }
  else
  {
    $message = "Cancelled";
  }

  if (defined $MAIN::mbox)
  {
    unlink $MAIN::mbox;
  }

  if (defined $MAIN::tempFile)
  {
    unlink $MAIN::tempFile;
  }

  print "$message.\n";

  exit;
}

#-------------------------------------------------------------------------------

my (%opts, $pattern, $unzipMethod);

BEGIN
{
  if (DEBUG)
  {
    print "DEBUG: Command line was:\n";
    print "DEBUG:   $0 @ARGV\n";
  }

  $pattern = "";

  # Print usage error if no arguments given
  print "No arguments given. grepmail -h for help.\n" and exit if ($#ARGV < 0);

  getopt("ed",\%opts);

  # At this point, we have 3 cases:
  # - The -d was specified without a pattern before it, in which case $opts{d}
  #   will be set. An implicit "." is used unless -e was specified.
  # - The pattern is in $ARGV[0], and -d is in $ARGV[1]
  # - There is no -d in $ARGV[1], and a pattern or file is in $ARGV[0]. Take
  #   is as a pattern if -e was not given.
  if ($opts{d})
  {
    $pattern = "." if !$opts{e};
  }
  elsif ($#ARGV > 0 && $ARGV[1] eq "-d")
  {
    $pattern = shift @ARGV;
    getopt("d",\%opts);
  }
  elsif (!$opts{e})
  {
    $pattern = shift @ARGV;
  }

  if (DEBUG)
  {
    print "DEBUG: Options are:\n";
    foreach my $i (keys %opts)
    {
      print "DEBUG:   $i: $opts{$i}\n";
    }

    print "DEBUG: INC is:\n";
    foreach my $i (@INC)
    {
      print "DEBUG:   $i\n";
    }
  }

  if ($opts{e})
  {
    print "You specified two search patterns.\n" and exit if ($pattern ne "");
    
    $pattern = $opts{e};
  }
  elsif ($pattern eq "")
  {
    # The only time you can't specify the pattern is when -d is being used.
    # This should catch people who do "grepmail -h" thinking it's help.
    print usage and exit if !$opts{d};

    $pattern = ".";
  }

  if ($opts{d})
  {
    unless (eval "require Date::Manip")
    {
      print "You specified -d, but do not have Date::Manip. Get it from CPAN.\n";
      exit;
    }

    import Date::Manip;
  }
}

#-------------------------------------------------------------------------------

# Make the pattern insensitive if we need to
$pattern = "(?i)$pattern" if ($opts{i});

my ($dateRestriction, $date1, $date2);

if ($opts{d})
{
  ($dateRestriction,$date1,$date2) = &ProcessDate($opts{d});
}
else
{
  $dateRestriction = "none";
}

if (DEBUG)
{
  print "DEBUG: PATTERN: $pattern\n";
  print "DEBUG: FILES: @ARGV\n";
}

$SIG{HUP} =  \&cleanExit;
$SIG{INT} =  \&cleanExit;
$SIG{QUIT} = \&cleanExit;
$SIG{TERM} = \&cleanExit;

my $tempDir;
if (defined $ENV{TMPDIR})
{
  $tempDir = $ENV{TMPDIR};
}
else
{
  $tempDir = "/tmp";
}

# If the user provided input files...
if (@ARGV)
{
  # For each input file...
  foreach my $file (@ARGV)
  {
    if (DEBUG)
    {
      print "DEBUG: ######################################################.\n";
      print "DEBUG: Processing file $file.\n";
    }

    # First of all, silently ignore empty files...
    next if -z $file;

    # ...and also ignore directories.
    warn "** Skipping directory: '$file' **\n" and next if -d $file;

    my $fileHandle = new FileHandle;
    my $tempFile = "$tempDir/grepmail.$$";

    # If it's not a compressed file
    if ($file !~ /\.(gz|Z|bz2|tz)$/)
    {
      warn "** Skipping binary file: '$file' **\n" and next if -B $file;

      $fileHandle->open($file) || cleanExit "Can't open $file";
    }
    # If it is a tzipped file
    elsif ($file =~ /\.tz$/)
    {
      print "DEBUG: Calling tzip to decompress file.\n" if DEBUG;
      system("tzip -cd $file > $tempFile") == 0
        or cleanExit "Can't execute tzip for file $file";
      # Make sure our email stays private!
      chmod 0600, $tempFile;

      $fileHandle->open($tempFile)
        || cleanExit "Can't open temporary file used to decompress the file $file";
    }
    # If it is a gzipped file
    elsif ($file =~ /\.(gz|Z)$/)
    {
      print "DEBUG: Calling gunzip to decompress file.\n" if DEBUG;
      system("gunzip -c $file > $tempFile") == 0
        or cleanExit "Can't execute gunzip for file $file";
      # Make sure our email stays private!
      chmod 0600, $tempFile;

      $fileHandle->open($tempFile)
        || cleanExit "Can't open temporary file used to decompress the file $file";
    }
    # If it is a bzipped file
    elsif ($file =~ /\.bz2$/)
    {
      print "DEBUG: Calling bzip2 to decompress file.\n" if DEBUG;
      system("bzip2 -dc $file > $tempFile") == 0
        or cleanExit "Can't execute bzip2 for file $file";
      # Make sure our email stays private!
      chmod 0600, $tempFile;

      $fileHandle->open($tempFile)
        || cleanExit "Can't open temporary file used to decompress the file $file";
    }

    ProcessMailFile($fileHandle,$file);
    $fileHandle->close();
    unlink $tempFile;
  }
}
# Using STDIN
else
{ 
  print "DEBUG: Handling STDIN\n" if DEBUG;

  my $fileHandle = new FileHandle;
  $fileHandle->open("<&STDIN") || cleanExit "Can't dup STDIN $!";

  # If it looks binary, try to uncompress it.
  if (-B $fileHandle)
  {
    binmode $fileHandle;
    my $tempFile = "$tempDir/grepmail.$$";

    my $testChars;
    read $fileHandle,$testChars,2;

    # Make it so we don't die if the pipe fails
    $SIG{PIPE} = 'IGNORE';
    
    # This seems to work. I'm not sure what the "proper" way to distinguish
    # between gzip'd and bzip2'd and tzip'd files is.
    if ($testChars eq "TZ")
    {
      print "DEBUG: Trying to decompress using tzip.\n" if DEBUG;
      open(TMP,"|tzip -cd >$tempFile") || cleanExit "Can't create $tempFile $!";
    }
    elsif ($testChars eq "BZ")
    {
      print "DEBUG: Trying to decompress using bzip2.\n" if DEBUG;
      open(TMP,"|bzip2 -d >$tempFile") || cleanExit "Can't create $tempFile $!";
    }
    else
    {
      print "DEBUG: Trying to decompress using gunzip.\n" if DEBUG;
      open(TMP,"|gunzip -c >$tempFile") || cleanExit "Can't create $tempFile $!";
    }

    binmode TMP;
    print TMP $testChars;
    print TMP while <$fileHandle>;
    close TMP;
    # Make sure our email stays private!
    chmod 0600, $tempFile;

    $fileHandle->close() || cleanExit "Error writing $tempFile $!";

    cleanExit "** Couldn't uncompress standard input **" if -z $tempFile;

    $fileHandle->open($tempFile) || cleanExit "Can't open $tempFile $!";
    ProcessMailFile($fileHandle,"Gzip'd standard input");
    $fileHandle->close();
    unlink $tempFile;      
  }
  # Otherwise save it directly
  else
  {
    print "DEBUG: Saving text from STDIN to a temporary file.\n" if DEBUG;

    my $tempFile = "/tmp/grepmail.$$";
    open(TMP,">$tempFile") || cleanExit "Can't create $tempFile $!";
    print TMP while <$fileHandle>;
    close TMP;
    # Make sure our email stays private!
    chmod 0600, $tempFile;

    $fileHandle->close() || cleanExit "Error writing $tempFile $!";

    $fileHandle->open($tempFile) || cleanExit "Can't open $tempFile $!";
    ProcessMailFile($fileHandle,"Standard input");
    $fileHandle->close();
    unlink $tempFile;
  }
}

#-------------------------------------------------------------------------------

sub ProcessMailFile ($$)
{
my $fileHandle = shift @_;
my $fileName = shift @_;
my ($numberOfMatches,$start,$matchesBody,$matchesHeader,$paragraph);

$numberOfMatches = 0;

# Read whole paragraphs
$/ = "\n\n";

# This is the main loop. It's executed once for each email
while (!eof($fileHandle))
{
  # Read the header
  $start = tell $fileHandle;
  $paragraph = <$fileHandle>;

  if (DEBUG)
  {
    print "DEBUG: ------------------------------------------------------\n";
    print "DEBUG: Processing email:\n";
    $paragraph =~ /^from:.*$/im;
    my $info = $&;
    print "DEBUG:   $info\n";
    $paragraph =~ /^subject:.*$/im;
    $info = $&;
    print "DEBUG:   $info\n";
  }

  # Save the header for later when we check the date.
  my $header = $paragraph;

  my ($matchesHeader,$matchesBody); 

  # See if the header matches the pattern
  $matchesHeader = ($paragraph =~ /$pattern/om);

  # At this point, we might know enough to print the email.
  if (
      ($opts{h} && $opts{b} && $opts{v} && !$matchesHeader) ||
      ($opts{h} && !$opts{b} && $opts{v} && !$matchesHeader) ||
      (!$opts{h} && !$opts{b} && !$opts{v} && $matchesHeader)
     )
  {
    # Skip to the next email if the date is wrong.
    if (!&CheckDate(\$header))
    {
      print "DEBUG: Failed date constraint.\n" if (DEBUG);
      SkipToNextEmail($fileHandle);
      next;
    }

    print "DEBUG: Doing an early printout based on header match.\n" if (DEBUG);

    if ($opts{l})
    {
      print "$fileName\n";

      # We can return since we found at least one email that matches.
      return;
    }
    elsif ($opts{r})
    {
      $numberOfMatches++;
      SkipToNextEmail($fileHandle);
    }
    else
    {
      PrintEmail($fileHandle,$fileName,$start);
    }

    next;
  }

  # We might have enough information to abort early
  if (
      ($opts{h} && $opts{b} && !$opts{v} && !$matchesHeader) ||
      ($opts{h} && !$opts{b} && !$opts{v} && !$matchesHeader) ||
      ($opts{h} && !$opts{b} && $opts{v} && !$matchesHeader) ||
      (!$opts{h} && !$opts{b} && $opts{v} && $matchesHeader)
     )
  {
    print "DEBUG: Doing an early abort based on header.\n" if (DEBUG);

    SkipToNextEmail($fileHandle);
    next;
  }

  print "DEBUG: Searching body for pattern.\n" if (DEBUG);

  # Now search the body for the pattern
  do
  {
    $paragraph = <$fileHandle>;
  }
  while (!eof && ($paragraph !~ /^\n*From .*\d{4}/) &&
        ($paragraph !~ /$pattern/om));

  if (eof)
  {
    print "DEBUG: Found EOF.\n" if (DEBUG);
    $matchesBody = 0;
  }
  elsif ($paragraph =~ /^\n*From .*\d{4}/)
  {
    print "DEBUG: Found next email message.\n" if (DEBUG);
    seek ($fileHandle, -(length $paragraph), 1);
    $matchesBody = 0;
  }
  else
  {
    $matchesBody = ($paragraph =~ /$pattern/om);
  }

  my $isMatch = (
                 ($opts{b} && $opts{h} && $matchesBody && $matchesHeader) ||
                 ($opts{b} && !$opts{h} && $matchesBody) ||
                 (!$opts{b} && $opts{h} && $matchesHeader) ||
                 (!$opts{b} && !$opts{h} && ($matchesBody || $matchesHeader))
                );

  $isMatch = !$isMatch if $opts{v};

  # If the match occurred in the right place...
  if ($isMatch)
  {
    print "DEBUG: Found a pattern match on the body.\n" if (DEBUG);

    # Skip to the next email if the date is wrong.
    if (!&CheckDate(\$header))
    {
      print "DEBUG: Failed date constraint.\n" if (DEBUG);

      SkipToNextEmail($fileHandle);
      next;
    }

    if ($opts{l})
    {
      print "$fileName\n";

      # We can return since we found at least one email that matches.
      return;
    }
    elsif ($opts{r})
    {
      $numberOfMatches++;
      SkipToNextEmail($fileHandle);
    }
    else
    {
      PrintEmail($fileHandle,$fileName,$start);
    }
  }
  else
  {
    print "DEBUG: Did not find a pattern match on the body.\n" if (DEBUG);

    # It doesn't match the pattern
    SkipToNextEmail($fileHandle);
  }

}

 print "$fileName: $numberOfMatches\n" if ($opts{r});
}

#-------------------------------------------------------------------------------

sub SkipToNextEmail($)
{
  my $fileHandle = shift;
  my $paragraph;

  print "DEBUG: Skipping to next email.\n" if (DEBUG);

  do
  {
    $paragraph = <$fileHandle>;
  }
  while (!eof && ($paragraph !~ /^\n*From .*\d{4}/)) ;

  # Back up if we went too far
  seek ($fileHandle, -(length $paragraph), 1) if (!eof);
}

#-------------------------------------------------------------------------------

sub PrintEmail($$$)
{
  my $fileHandle = shift;
  my $fileName = shift;
  my $start = shift;
  my $paragraph;

  print "DEBUG: Printing email.\n" if (DEBUG);

  seek ($fileHandle, $start, 0);
  $paragraph = <$fileHandle>;

  # Print the mailfolder in the headers if -m was given
  if ($opts{"m"})
  {
    chop $paragraph;
    $paragraph .= "X-Mailfolder: $fileName\n\n";
  }
  print $paragraph;

  do
  {
    $paragraph = <$fileHandle>;
    print $paragraph if ($paragraph !~ /^\n*From .*\d{4}/);
  }
  while (!eof && ($paragraph !~ /^\n*From .*\d{4}/)) ;

  # Back up if we went too far
  seek ($fileHandle, -(length $paragraph), 1) if (!eof);
}

#-------------------------------------------------------------------------------
    
sub CheckDate($)
{
my $emailref = shift;
my ($emailDate, $isInDate);
$emailDate = "";
$isInDate = 0;

if ($opts{d})
{
  # The email might not have a date. In this case, print it out anyway.
  if ($$emailref =~ /^Date:\s*(\S*\s*\S*\s*\S*\s*\S*\s*\S*)/m)
  {
    print "DEBUG: Date in email is: $1.\n" if (DEBUG);

    $emailDate = &ParseDate($1);
    $isInDate = &IsInDate($emailDate,$dateRestriction,$date1,$date2);
  }
  else
  {
    print "DEBUG: No date found in email.\n" if (DEBUG);

    $isInDate = 1;
  }
}
else
{
  $isInDate = 1;
}

return $isInDate;

}

#-------------------------------------------------------------------------------

# Figure out what kind of date restriction they want, and what the dates in
# question are.
sub ProcessDate($)
{
my ($dateRestriction, $date1, $date2);

if(!defined($_[0]))
{
  return ("none","","");
}

my $datestring = $_[0];

if ($datestring =~ /^before (.*)/)
{
  $dateRestriction = "before";
  $date1 = &ParseDate($1);
  $date2 = "";

  cleanExit "\"$1\" is not a valid date" if (!$date1);
}
elsif ($datestring =~ /^(after |since )(.*)/)
{
  $dateRestriction = "after";
  $date1 = &ParseDate($2);
  $date2 = "";

  cleanExit "\"$2\" is not a valid date" if (!$date1);
}
elsif ($datestring =~ /^between (.*) and (.*)/)
{
  $dateRestriction = "between";
  $date1 = &ParseDate($1);
  $date2 = &ParseDate($2);

  cleanExit "\"$1\" is not a valid date" if (!$date1);
  cleanExit "\"$2\" is not a valid date" if (!$date2);

  # Swap the dates if the user gave them backwards.
  if ($date1 gt $date2)
  {
    my $temp;
    $temp = $date1;
    $date1 = $date2;
    $date2 = $temp;
  }

}
elsif ($date1 = &ParseDate($datestring))
{
  $dateRestriction = "on"
}
else
{
  cleanExit "Invalid date specification. Use \"$0 -h\" for help";
}

return ($dateRestriction,$date1,$date2);

}

#-------------------------------------------------------------------------------

sub IsInDate($$$$)
{
my ($emailDate,$dateRestriction,$date1,$date2);
$emailDate = shift @_;
$dateRestriction = shift @_;
$date1 = shift @_;
$date2 = shift @_;

# Here we do the date checking.
if ($dateRestriction eq "none")
{
  return 1;
}
else
{
  if ($dateRestriction eq "before")
  {
    if ($emailDate lt $date1)
    {
      return 1;
    }
    else
    {
      return 0;
    }
  }
  elsif ($dateRestriction eq "after")
  {
    if ($emailDate gt $date1)
    {
      return 1;
    }
    else
    {
      return 0;
    }
  }
  elsif ($dateRestriction eq "on")
  {
    if (&UnixDate($emailDate,"%m %d %Y") eq &UnixDate($date1,"%m %d %Y"))
    {
      return 1;
    }
    else
    {
      return 0;
    }
  }
  elsif ($dateRestriction eq "between")
  {
    if (($emailDate gt $date1) && ($emailDate lt $date2))
    {
      return 1;
    }
    else
    {
      return 0;
    }
  }
}

}

#-------------------------------------------------------------------------------

=head1 NAME

grepmail - search mailboxes for mail matching a regular expression

=head1 SYNOPSIS

  grepmail [-vihblrm] [-e <regex>] [-d "datespec"] [mailbox ...]

=head1 DESCRIPTION

=over 2

I<grepmail> looks for mail messages containing a pattern, and prints the
resulting messages on standard out.

By default I<grepmail> looks in both header and body for the specified pattern.

When redirected to a file, the result is another mailbox, which can, in turn,
be handled by standard User Agents, such as I<elm>, or even used as input for
another instance of I<grepmail>.

The pattern is optional if -d is used, and must precede the -d flag unless it
is specified using -e.

=back

=head1 OPTIONS AND ARGUMENTS

Many of the options and arguments are analogous to those of grep.

=over 8

=item B<pattern>

The pattern to search for in the mail message.  May be any Perl regular
expression, but should be quoted on the command line to protect against
globbing (shell expansion). To search for more than one pattern, use the form
"(pattern1|pattern2|...)".

=item B<mailbox>

Mailboxes must be traditional, UNIX C</bin/mail> mailbox format.  The
mailboxes may be compressed by gzip, bzip2, or tzip, in which case gunzip,
bzip2, or tzip must be installed on the system.

If no mailbox is specified, takes input from stdin, which can be compressed or
not. grepmail's behavior is undefined when ASCII and binary data is piped
together as input.

=item B<-b>

Asserts that the pattern must match in the body of the email.

=item B<-h>

Asserts that the pattern must match in the header of the email.

=item B<-i>

Make the search case-insensitive (by analogy to I<grep -i>).

=item B<-v>

Invert the sense of the search, (by analogy to I<grep -v>). Note that this
affects only -h and -b, not -d. This results in the set of emails printed
being the complement of those that would be printed without the -v switch.

=item B<-l>

Output the names of files having an email matching the expression, (by analogy
to I<grep -l>).

=item B<-r>

Generate a report of the names of the files containing emails matching the
expression, along with a count of the number of matching emails.

=item B<-m>

Append "X-Mailfolder: <folder>" to all email headers, indicating which folder
contained the matched email.

=item B<-e>

Explicitely specify the search pattern. This is useful for specifying patterns
that begin with "-", which would otherwise be interpreted as a flag.

=item B<-d>

Date specifications must be of the form of:
  - a date like "today", "1st thursday in June 1992", "05/10/93", "12:30 Dec 12th 1880", "8:00pm december tenth",
  - OR "before", "after", or "since", followed by a date as defined above,
  - OR "between <date> and <date>", where <date> is defined as above.

=back

=head1 EXAMPLES

Get all email that you mailed yesterday

  grepmail -d yesterday sent-mail

Get all email that you mailed before the first thursday in June 1998 that
pertains to research:

  grepmail research -d "before 1st thursday in June 1992" sent-mail

Get all email you received since 8/20/98 that wasn't about research or your
job, ignoring case:

  grepmail -iv "(research|job)" -d "since 8/20/98" saved-mail

Get all email about mime but not about Netscape. Constrain the search to match
the body, since most headers contain the text "mime":

  grepmail -b mime saved-mail | grepmail Netscape -v

Print a list of all mailboxes containing a message from Rodney. Constrain the
search to the headers, since quoted emails may match the pattern:

  grepmail -hl "^From.*Rodney" saved-mail*

Find all emails with the text "Pilot" in both the header and the body:

  grepmail -hb "Pilot" saved-mail*

Print a count of the number of messages about grepmail in all saved-mail
mailboxes:

  grepmail -br grepmail saved-mail*

=head1 AUTHOR

  David Coppit, <coppit@cs.virginia.edu>,
  http://www.cs.virginia.edu/~dwc3q/index.thml

=head1 SEE ALSO

elm(1), mail(1), grep(1), perl(1), printmail(1), Mail::Internet(3)
Crocker,  D.  H., Standard for the
Format of Arpa Internet Text Messages, RFC822.

=cut
