File: grepmail

package info (click to toggle)
grepmail 3.4.1-4
  • links: PTS
  • area: main
  • in suites: slink
  • size: 44 kB
  • ctags: 10
  • sloc: perl: 519; makefile: 41
file content (932 lines) | stat: -rwxr-xr-x 24,320 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
#!/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.1

# 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. The latest version is always at
# http://www.cs.virginia.edu/~dwc3q/code/.

# 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.1 Fixed a small bug that inserted a newline at the start of output.
#   (Thanks to Moritz Barsnick <barsnick@gmx.net> for helping to find this.)
# 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;
  }

  print "$message.\n";

  exit;
}

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

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

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

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

  getopt("ed",\%opts);

  # At this point, we have 4 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.
  # - They did something like "grepmail -h", in which case do nothing
  if ($opts{d})
  {
    $pattern = "." if !$opts{e};
  }
  elsif ($#ARGV > 0 && $ARGV[1] eq "-d")
  {
    $pattern = shift @ARGV;
    getopt("d",\%opts);
  }
  elsif (!$opts{e} && @ARGV)
  {
    $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 (defined $pattern);
    
    $pattern = $opts{e};
  }
  elsif (!defined $pattern)
  {
    # 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";
}

# Catch everything I can...
$SIG{PIPE} = \&cleanExit;
$SIG{HUP} = \&cleanExit;
$SIG{INT} = \&cleanExit;
$SIG{QUIT} = \&cleanExit;
$SIG{TERM} = \&cleanExit;

# 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;

    # 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;
      $fileHandle->open("tzip -cd $file|") 
        or cleanExit "Can't execute tzip for file $file";
    }
    # If it is a gzipped file
    elsif ($file =~ /\.(gz|Z)$/)
    {
      print "DEBUG: Calling gunzip to decompress file.\n" if DEBUG;
      $fileHandle->open("gunzip -c $file|")
        or cleanExit "Can't execute gunzip for file $file";
    }
    # If it is a bzipped file
    elsif ($file =~ /\.bz2$/)
    {
      print "DEBUG: Calling bzip2 to decompress file.\n" if DEBUG;
      $fileHandle->open("bzip2 -dc $file|")
        or cleanExit "Can't execute bzip2 for file $file";
    }

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

  my $fileHandle = new FileHandle;

  # If it looks binary, try to uncompress it.
  if (-B STDIN)
  {
    binmode STDIN;

    my $testChars;
    read STDIN,$testChars,2;
    seek(STDIN,0,0);

    # 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;
      $fileHandle->open("tzip -cd -|")
        or cleanExit "Can't execute tzip on stdin";
    }
    elsif ($testChars eq "BZ")
    {
      print "DEBUG: Trying to decompress using bzip2.\n" if DEBUG;
      $fileHandle->open("bzip2 -dc -|")
        or cleanExit "Can't execute bzip2 on stdin";
    }
    else
    {
      print "DEBUG: Trying to decompress using gunzip.\n" if DEBUG;
      $fileHandle->open("gunzip -c -|")
        or cleanExit "Can't execute gunzip on stdin";
    }

    ProcessMailFile($fileHandle,"compressed standard input");
    $fileHandle->close();
  }
  # Otherwise process it directly
  else
  {
    ProcessMailFile(*STDIN,"Standard input");
  }
}

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

my $buffer;

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

$email_buffer='';
$numberOfMatches = 0;

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

# This is the main loop. It's executed once for each email
while (!eof($fileHandle))
{
  $email_buffer='';
  
  # Read the header
  if (! defined $buffer) {
	  $paragraph = <$fileHandle>;
  }
  else {
  	print "DEBUG: Processing buffer\n" if DEBUG;
	$paragraph = $buffer;
	undef $buffer;
  }

  $email_buffer.=$paragraph;

  if (DEBUG)
  {
    print "DEBUG: ------------------------------------------------------\n";
    print "DEBUG: Processing email:\n";
    $paragraph =~ /^from:.*$/im;
    print "DEBUG:   $&\n";
    $paragraph =~ /^subject:.*$/im;
    print "DEBUG:   $&\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)
     )
  {
    print "DEBUG: Checking for early printout based on header.\n" if (DEBUG);

    # Skip to the next email if the date is wrong.
    if (!&CheckDate(\$header))
    {
      print "DEBUG: Header 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,$email_buffer);
    }

    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>;
    $email_buffer.=$paragraph;
  }
  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, buffering\n" if (DEBUG);
    $buffer = $paragraph;
    $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,$email_buffer);
    }
  }
  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);

  # If we have something buffered, it's the beginning of the next email
  # address, so we don't need to do anything. Joy.
  return if defined $buffer;

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

  # Buffer if we went too far.
  $buffer = $paragraph if (!eof);
}

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

sub PrintEmail($$$)
{
  my $fileHandle = shift;
  my $fileName = shift;
  
  # Read in and process parts of message we already have.
  my ($paragraph, @paragraphs);
  foreach $paragraph (split(/\n\n/,shift)) {
    push @paragraphs, "$paragraph\n\n";
  }
  undef $paragraph;
  
  # Read in remainder of message.
  do
  {
    $paragraph = <$fileHandle>;
    push @paragraphs, $paragraph;
  }
  while (!eof && ($paragraph !~ /^\n?From .*\d{4}/)) ;

  # Buffer if we read too far.
  $buffer=$paragraph if (!eof);

  print "DEBUG: Printing email.\n" if (DEBUG);
  $paragraph=shift @paragraphs;

  # Strip any newline at the start of the header. Because the pattern is
  # "\n\n", there will sometimes be an extra newline if there are an odd
  # number of newlines between emails.
  $paragraph =~ s/^\n(From .*\d{4})/$1/;

  # 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 = shift @paragraphs;

    print $paragraph if $paragraph !~ /^\n?From .*\d{4}/;

    # Print the extra newline that appears when there are an odd number of
    # newlines bewteen messages. Basically I consider the newline to be part
    # of the previous message, although I don't think it matters.
    if ($paragraph =~ /^\nFrom .*\d{4}/)
    {
      $paragraph =~ s/^\n//;
      print "\n";
    }
  }
  while (@paragraphs && ($paragraph !~ /^\n?From .*\d{4}/)) ;
}

#-------------------------------------------------------------------------------
    
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