#!/usr/bin/perl
# Copyright (C) Dirk Husemann, Computer Science Department IV, 
# 	Friedrich-Alexander-Universitt Erlangen-Nrnberg, Germany, 1993
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 3. All advertising materials mentioning features or use of this software
#    must display the following acknowledgement:
#      This product includes software developed by the Dirk Husemann,
#      Friedrich-Alexander-Universitt Erlangen-Nrnberg, Germany
# 4. The name of the University may not be used to endorse or promote
#    products derived from this software without specific prior written
#    permission. 
# 
# THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE UNIVERSITY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 

# debugging output
#open(STDOUT, ">>/tmp/faxmailer.out");

$ls = "/bin/ls";
$sendmail = "/usr/sbin/sendmail";
$faxinfo = "/usr/spool/fax/bin/faxinfo";
$fax2ps = "/usr/contrib/fax/bin/fax2ps";
$mimencode = "/usr/contrib/metamail/bin/mimencode";
$tiffsplit = "/usr/contrib/tiff/bin/tiffsplit";
$compress = "/usr/contrib/bin/gzip -c";

$faxmaster = "FaxMaster";
$plusexecpath = "/usr/contrib/fax/bin:/usr/contrib/tiff/bin";
$hostname = `hostname`; chop $hostname;
$myname = "i4fax-daemon";
$tiffsplitprefix = "/tmp/.faxnotify.split";

$delivery_mode = "PS";		# might be "PS", "PS+TIFF", or "TIFF"

# get path right
$execpath = $ENV{'PATH'};
$execpath = $plusexecpath . ":" . $execpath;
$ENV{'PATH'} = $execpath;

sub mime_head {
    local($MAILER, $MIME_boundary, $to, $from, $subject) = @_;
    local($preserve) = select($MAILER);

print <<END_OF_MIMEMAILHEAD;
To: $to
From: $from
Subject: $subject
MIME-Version: 1.0
Content-Description: A MIME message composed by the I4FAX-Daemon.
Content-type: multipart/mixed; boundary=$MIME_boundary

> This is  a multimedia message in MIME  format.  If you are reading this
> prefix, your mail reader does  not understand MIME.  You may wish
> to look into upgrading to a newer version of  your mail reader.
END_OF_MIMEMAILHEAD
    select($preserve);
}

sub mime_frame {
    local($MAILER, $MIME_boundary, $ct, $cte, *generator) = @_;
    local($preserve) = select($MAILER);

    print  <<END_OF_MIME_CHUNK;
--$MIME_boundary
Content-Type: $ct
Content-Transfer-Encoding: $cte

END_OF_MIME_CHUNK

    &generator($MAILER);

    select($preserve);
}   

sub mime_chunk {
    local($MAILER, $MIME_boundary, $facsimile, $ct, $cte, 
	  $preprocessor, $encoder) = @_;
    local($preserve) = select($MAILER);

    print <<END_OF_MIME_CHUNK;
--$MIME_boundary
Content-Type: $ct
Content-Transfer-Encoding: $cte

END_OF_MIME_CHUNK

    if ($preprocessor) {
	open(MIMENCODE, "$preprocessor $facsimile | $encoder |");
    } else {
	open(MIMENCODE, "$encoder $facsimile |");
    }	
    while ($mimeline = <MIMENCODE>) {
	print $mimeline;
    }
    close(MIMENCODE);
    select($preserve);
}   

sub mime_tail {

    local($MAILER, $MIME_boundary) = @_;
    local($preserve) = select($MAILER);

    print <<END_OF_MIME_TAIL;

--$MIME_boundary
END_OF_MIME_TAIL
    select($preserve);
}

sub normmonth {
    local($_) = @_;

    study;
    s/oct|10/Oct/i;
    s/nov|11/Nov/i;
    s/dec|12/Dec/i;
    s/jan|0?1/Jan/i;
    s/feb|0?2/Feb/i;
    s/mar|0?3/Mar/i;
    s/apr|0?4/Apr/i;
    s/may|0?5/May/i;
    s/jun|0?6/Jun/i;
    s/jul|0?7/Jul/i;
    s/aug|0?8/Aug/i;
    s/sep|0?9/Sep/i;
    $_;
}

sub fax_notification {
    local ($MAILER) = @_;
    local ($preserve) = select($MAILER);
    local ($error);

    if ($receive_error eq "") {
	$error = "None";
    } else {
	$error = $receive_error;
    }

    print <<FAX_NOTIFICATION_END;
The following facsimile consisting of $pages $page_noun was received
from >$sender< at $time on $month $day, $year.

    Quality:            $quality
    Pagesize:           $pagesize
    Time to receive:    $receive_duration
    Speed:              $receive_sigrate
    Protocol:           $receive_format
    Error:		$error
    

The facsimile has been enclosed as a PostScript image.

    Sincerely,
    i4fax-daemon

FAX_NOTIFICATION_END
    select($preserve);
}

$received_fax = $ARGV[0];
$receive_duration = $ARGV[1];
$receive_sigrate = $ARGV[2];
$receive_format = $ARGV[3];
$receive_error = $ARGV[4];
if (! defined($received_fax)) {
   exit -1;
}

open(FAXINFO, "$faxinfo $received_fax|") || 
              die "$faxinfo didn't work out...\n";
@faxinfo = <FAXINFO>;
close(FAXINFO);

(($sender) = grep(/\s*Sender:/, @faxinfo)) && (chop $sender) 
           && ($sender =~ /:\s*([+\d\s]+)$/) && ($sender = $1) && 
           ($sender =~ s/\s/\./g);
$sender =~ s/^\.$/no-TSI-string/;
(($pages) = grep(/\s*Pages:/, @faxinfo)) && (chop $pages) 
           && ($pages =~ /:\s*(\d+)$/) && ($pages = $1);
(($quality) = grep(/\s*Quality:/, @faxinfo)) && (chop $quality) 
           && ($quality =~ /:\s*(\w+)$/) && ($quality = $1);
(($pagesize) = grep(/\s*Page:/, @faxinfo)) && (chop $pagesize) 
           && ($pagesize =~ /:\s*([\w\d][\w\d\s]*)$/) && ($pagesize = $1);
(($timestamp) = grep(/\s*Received:/, @faxinfo)) && (chop $timestamp) 
           && ($timestamp =~ /:\s*([:\d\s]+)$/) && ($timestamp = $1);

($timestamp =~ /(\d+)\:(\d+)\:(\d+)\s+(\d+\:\d+:\d+)/)
           && ($year = $1, $month = $2, $day = $3, $time = $4);

$month = &normmonth($month);

if ($pages > 1) {
   $page_noun = "pages";
} else {
  $page_noun = "page";
}

open(MAILER, "|$sendmail -oib -f$myname -t") || 
    die "Couldn't pipe to $sendmail ...\n";
#open(MAILER, ">/tmp/faxnotify.$$") || 
#    die "Couldn't open mail file ...\n";

close(STDERR);			# because of fax2ps ...
# let's MIME a bit ...
$MIME_boundary = "MIME-FlexFax";
&mime_head(MAILER, $MIME_boundary, $faxmaster, "$sender@i4fax", 
	   "FAX from >$sender< ($pages $page_noun)");
&mime_frame(MAILER, $MIME_boundary, "text/plain; charset=ISO-8859-1", 
	    "quoted-printable", *fax_notification);

# Send as compressed PostScript
if ($delivery_mode =~ /PS/i) {
    &mime_chunk(MAILER, $MIME_boundary, $received_fax, 
	        "application/compressed-postscript", "base64", 
		"$fax2ps -s ", "$compress | $mimencode -b");
}

# Send as is, i.e. as TIFF file
if ($delivery_mode =~ /TIFF/i) {
    # split the TIFF file into appropriate chunks (i.e. pages)
    system("$tiffsplit $received_fax $tiffsplitprefix");
    $tiffsplitls = `$ls $tiffsplitprefix*`;
    @tiffchunks = split(/\n/, $tiffsplitls);

    foreach $tiffpage (@tiffchunks) {
        &mime_chunk(MAILER, $MIME_boundary, $tiffpage, "image/tiff", "base64",
    		    "", "$mimencode -b");
        unlink($tiffpage);
    }
}

&mime_tail(MAILER, $MIME_boundary);

close(MAILER);

# dump tiff image file
unlink($received_fax);

exit;
