#!/usr/bin/perl -w

# $Id: new_fax,v 1.1 1998/08/18 17:32:06 torsten Exp torsten $
# Program which is called for newly received faxes

# Some functions for dealing with files
use File::Basename;

# The user to receive the fax and the get the fax viewer on its display
#my $user = 'torsten';

my $faxviewer = '/usr/local/bin/faxview';

my $sendmail = '/usr/sbin/sendmail';
my $tar = '/bin/tar';
my $gzip = '/usr/bin/gzip';
my $su = '/bin/su';
my $mmencode = '/usr/local/bin/mmencode';

# Information received from mgetty
my $type = shift;
my $user = shift;
my $sender_id = shift;
my $number_pages = shift;

# change all / in sender_id to -
$sender_id=~s,/,-,gm;

my $subject_line = 
  "Subject: incoming $type message from $sender_id with $number_pages ";
	if ($type eq "FAX")
	{
		if($number_pages != 1)
		{
  		$subject_line .= "pages";
  	} else {
			$subject_line .= "page";
		}
	} else {
		$subject_line .= "seconds";
		$number_pages = 1;
	}
		
my $tmp = "/tmp/new_message-$$";
mkdir $tmp, 0755
  or die "Unable to create dir $tmp";

my $archive_tmp = "$tmp/$sender_id.new";
my $archive = "$tmp/$sender_id.faxes";

my $mail = "$tmp/mail";

foreach $file (@ARGV) {
  # Ignore non-existing files
  -f $file && -r $file or next;

  chdir dirname($file)
    or die "Unable to chdir to directory of $file";

  system($tar, "rf", $archive_tmp, basename $file) == 0
    or die "Tar failed for adding $file to archive $archive_tmp";
}

system("$gzip -c9 \"$archive_tmp\" > \"$archive\"") == 0
  or die "Gzip failed for compressing $archive_tmp to $archive";

# Now build a file for sending mail
$args = basename $archive;

open MAIL, ">$mail"
  or die "Unable to compose mail in $mail";
print(MAIL "$subject_line\n");
print(MAIL "X-Sender: KMsgModem ");
if ($type eq "FAX")
{
	print(MAIL "(FAX)\n");
} else {
	print(MAIL "(VOICE)\n");
}
print(MAIL "MIME-Version: 1.0\n");
print(MAIL "Content-Type: multipart/mixed; boundary=\"attachment\"\n\n");
print(MAIL "--attachment\n");
if ($type eq "FAX")
{
	print(MAIL "Content-Type: application/x-faxarchive; name=\"$args\"\n");
} else {
	print(MAIL "Content-Type: application/x-voicearchive; name=\"$args\"\n");
}
print(MAIL "Content-Transfer-Encoding: base64\n\n");
close MAIL;

# Encode the file and add it to the mail
system("$mmencode -b \"$archive\" >> \"$mail\"") == 0
  or die "Error while encoding $archive into $mail";

open MAIL, ">>$mail"
  or die "Unable to append to mail in $mail";
print(MAIL "\n--attachment--\n");
close MAIL;

# Now call sendmail
system("$sendmail $user < \"$mail\"") == 0
  or die "Error while sending the mail";

END {
  defined $tmp and
    system("rm -rf $tmp");
}
