#!/usr/bin/env perl 
#     to start perl, if it is in the PATH
#
# This program is used to parse out the first subject and recipient fields
# found in the standard input stream and subsequently mailing the given
# input stream. If the environment variable MAIL_LOG_FILE is present, the
# given input stream, with date stamp, is appended to the named file.

sub get_line
{
    local ($this_line) = $LOOKAHEAD;
    $stream = $_[0];
    
    while( $LOOKAHEAD = <$stream> )
    {
        #--------------------------------------------------
        # Only do this line concatatonation in mail header.
        #--------------------------------------------------
        if( $in_header == 0 )
        {
            last;
        }
        else
        {
            #---------------------------------------------------
            # Find a named field (with ':'), or an empty line,
            # stop concatonating.
            #---------------------------------------------------
            if( $LOOKAHEAD =~ /^[ \t]*[a-zA-Z]+:/o ||
                $LOOKAHEAD =~ /^[ \t]*$/o             )
            {
                last;
            }
            $this_line =~ s/[ \t\n]*$//o; # trim trailing whitespace.
            $LOOKAHEAD =~ s/^[ \t]*/ /o;  # trim leading white space down to ' '
            $this_line .= $LOOKAHEAD;
        }
    }
    
    return $this_line;
}

sub extract_mail_address 
{
    #---------------------------------------------------------------------
    # This turns names like this: "Steven Haehn" <haehn@sdsp.mc.xerox.com>
    # into names like this:       haehn@sdsp.mc.xerox.com
    #---------------------------------------------------------------------
    local ($name) = $_[0];
    $name =~ s/".*"[ \t]*<(.+)>/$1/go;
    return $name;
}

$subject = "";
$recipient = "";
$carbonCopy = "";
$blindCarbonCopy = "";
$log_file = "$ENV{MAIL_LOG_FILE}";
$in_header = 1;
$tmp = "$ENV{HOME}/.mailfile.body";
$tmpHdr = "$ENV{HOME}/.mailfile.hdr";
$completeFile = "$ENV{HOME}/.mailfile.cplt";
$name = "";

open( MAILFILE, ">$tmp" );
open( HEADERFILE, ">$tmpHdr" );

#------------------------------
# Scan the entire input stream.
#------------------------------
$LOOKAHEAD = <STDIN>;  # get 1st line, priming the get_line pump

while( $_ = &get_line( STDIN ) )
{
    if( $in_header == 1 )
    {
        #------------------------------------------------------------
        # We are no longer parsing the mail header when we
        # encounter the first empty line.
        # Need this to protect ourselves from other included messages.
        #-------------------------------------------------------------
        if( $LOOKAHEAD =~ /^[ \t\n]*$/o )
        {
            $in_header = 0;
        }
        
        if( $subject eq "" && /^[ \t]*[Ss]ubject:[ \t]*(.+)$/o )
        {
            $subject = $1;
            next;
        }
        elsif( $recipient eq "" && /^[ \t]*[Tt]o:[ \t]*(.+)$/o )
        {
            $name = &extract_mail_address( $1 );
            $recipient = "$recipient $name";
            next;
        }
        elsif( $carbonCopy eq "" && /^[ \t]*[Cc]c:[ \t]*(.*)$/o )
        {
            $ccField = $1;
            
            # Ignore if this is a left over 'expander' field
            next if( $ccField =~ /\|>.*<\|/o || $ccField eq "" );

            $name = &extract_mail_address( $ccField );
            $carbonCopy = "$carbonCopy $name";
            $_ = "~c $ccField\n";
            print HEADERFILE $_;
            next;
        }
        elsif( $blindCarbonCopy eq "" && /^[ \t]*[Bb]cc:[ \t]*(.*)$/o )
        {
            $ccField = $1;

            # Ignore if this is a left over 'expander' field
            next if( $ccField =~ /\|>.*<\|/o || $ccField eq "" );
            
            $name = &extract_mail_address( $ccField );
            $blindCarbonCopy = "$blindCarbonCopy $name";
            $_ = "~b $ccField\n";
            print HEADERFILE $_;
            next;
        }
        elsif( /^[ \t]*[Ll]og:[ \t]*(.*)/o )
        {
            if( $1 !~ /([^ \t\n]+)/o )
            {
                $log_file = "";  # no log file
            }
            else
            {
                $log_file = $1;  # new log file
            }
            next;
        }
    }
    
    print MAILFILE $_;
}

close MAILFILE;
close HEADERFILE;

#--------------------------------------
# Holler about missing required fields.
#--------------------------------------
if( $subject eq "" )
{
    print STDERR "No subject field (Subject:) specified in message!\n";
    exit 1;
}
elsif( $recipient eq "" )
{
    print STDERR "No recipient field (To:) specified in message!\n";
    exit 1;
}

$date = `date`;
$timestamp = "From $ENV{ 'USER' } $date";
`cat $tmpHdr $tmp > $completeFile`;
`/usr/ucb/mail -s "$subject" "$recipient" < $completeFile`;

if( $log_file ne "" )
{
    if( $carbonCopy ne "" )
    {
        $recipient = $recipient . "\nCc: $carbonCopy";
    }
    if( $blindCarbonCopy ne "" )
    {
        $recipient = $recipient . "\nBcc: $blindCarbonCopy";
    }
    $timestamp = $timestamp . "Date: $date" . "To: $recipient\nSubject: $subject";
    `echo >> $log_file; echo >> $log_file; echo "$timestamp" >> $log_file; cat $tmp >> $log_file`
}

unlink "$tmp", "$tmpHdr", "$completeFile";
