#!/usr/bin/perl
#
#   Author: Tom Mutdosch
#   Sort mail file and create new mail file with specified headers
#   usage:
#       mailsort -from tommut [davek] [windmill]
#       mailsort -to davek
#       mailsort -subject ass
#       mailsort -to tanyai -date (sort by date and to: tanyai)
#   if just name given (tommut) then matches tommut@anything;
#   else, matches exact address only: tommut@csh.rit.edu
# -to davek tommut jonny
# output to stdout
#
#   $Id: mailsort.pl,v 1.1 1999/11/16 04:34:57 tommut Exp tommut $
# 
#   $Log: mailsort.pl,v $
#   Revision 1.1  1999/11/16 04:34:57  tommut
#   Initial revision
#
#  
# scan for case insensitive people

use Getopt::Long;

sub parseCommandLine {
    &GetOptions( "to=s@" => \@to, "from=s@" => \@from, "subject=s@" => \@sub,
            "date" => \$sortByDate, "insensitive" => \$insensitive);
}
    
sub printUsage {
    print 
       "Usage:\n" . 
       "\tmailsort -from tommut\n" .
       "\tmailsort -to davek\n" .
       "\tmailsort -subject ass\n" .
       "\tmailsort -to tanyai -date (sort by date and to: tanyai)\n";
}

sub ParseHeader {
    $i = $#message+1;
    while ( ($line = <STDIN> ) ne "\n" ) {
        if ( $line eq "" ) {
            $finished = 1;
            return;
        }
        @message[$i++] = $line;
    }
    @message[$i++] = $line;

    for ( $j = $i; $j>=0 && !$printLine; $j-- ) {
    $caseInsensitive = ( $insensitive == 1  ) ? "i" : "";
        foreach $elem ( @from ) {
            if ( @message[$j] =~ /^From: .*$elem/ ) {
            #if ( @message[$j] =~ /^From: .*$elem/$caseInsensitive ) {
                $printLine = 1;
            }
        }
        foreach $elem ( @to ) {
            if ( @message[$j] =~ /^To: .*$elem/ ) {
                $printLine = 1;
            }
        }
        foreach $elem ( @subject ) {
            if ( @message[$j] =~ /^Subject: .*$elem/ ) {
                $printLine = 1;
            }
        }
    }
}

sub GetMessage {
    $done = 0;
    while ( !$done && not ( ($line = <STDIN> ) =~ /^Message-id: </i) ) {
        if ( $line eq "" ) {
            $finished = 1;
            $done = 1;
        }
        @message[$i++] = $line;
    }
    @message[$i++] = $line;

    $wedone = 0;
    for ( $j = $i; $j > 0 && !$wedone && !$done; $j-- ) {
        if ( @message[$j] eq "\n" ) {
            $wedone = 1;
        }
    }

    for ( $k = 0; $k < $j+2; $k++ ) {
        if ( $printLine ) {
            print @message[$k];
        }
    }

    @message = @message[$j+2 .. $i];
}

parseCommandLine();

foreach $element (@to) {
#    print $element . "\n";
}
foreach $element (@from) {
#    print $element . "\n";
}
foreach $element (@sub) {
#    print $element . "\n";
}

$done = 0;
$i=0;
@message;
$sortByDate = 0;
$finished = 0;

while ( not ( ($line = <STDIN> ) =~ /^Message-id: </i) ) {
    @message[$i++] = $line;
}
@message[$i++] = $line;

while ( !$finished ) {
    $printLine = 0;
    $done = 0;
    ParseHeader();
    GetMessage();
}

