#!/usr/bin/perl -w
#
# Copyright 2001 Erik Hensema <erik@hensema.net>
#
#      This program is free software; you can redistribute it and/or modify
#      it under the terms of the GNU General Public License as published by
#      the Free Software Foundation; either version 2 of the License, or
#      (at your option) any later version.
#
#      This program is distributed in the hope that it will be useful,
#      but WITHOUT ANY WARRANTY; without even the implied warranty of
#      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#      GNU General Public License for more details.
#
#      You should have received a copy of the GNU General Public License
#      along with this program; if not, write to the Free Software
#      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

use MIME::Entity;

####  You need to configure this:
$tmpdir = "/tmp";
$domain = "hensema.net";

# Flavour of printing subsystem. Currently supported are:
# - trad: Traditional BSD lpd system
# - ng:   LPRng system
$lpd = "trad";

#### You may want to configure this:
$ps2pdf = "/usr/bin/ps2pdf";
$sendmail = "/usr/sbin/sendmail -t";

#### End of configuration.

$pstmp = "$tmpdir/pdfwrite$$.ps";
$pdftmp = "$tmpdir/pdfwrite$$.pdf";
$output = "$tmpdir/pdfwrite$$.out";

umask 077;

open PS, ">$pstmp" or die "Cannot create $pstmp: $!";

while(<STDIN>) {
	$psname = "$1.pdf" if m/^\%\%Title: ([^\r\n]*)/i;
	print PS;
}

close PS;

if($lpd eq "ng") {
	foreach (@ARGV) {
		$user = $1 if m/-n(.*)/;
		$date = $1 if m/-t(.*)/;
		$name = $1 if m/-f(.*)/;
	}
	$name =~ s/^.*[\/\\]//;

	# $name = $lpname if defined $lpname;
}

if($lpd eq "trad") {
	foreach $arg (@ARGV) {
		$user = $arg if defined $state && $state eq "user";

		undef $state;
		
		$state = "user" if $arg eq "-n";
	}

	$date = localtime time;
	$name = $psname || "converted.pdf";
}

open MAIL, "|$sendmail $user\@$domain" or die "Cannot open mail: $!\n";

if(!system "$ps2pdf $pstmp $pdftmp > $output 2>&1") {
	$top = MIME::Entity->build(Type    => "multipart/mixed",
				   From    => "PDF Writer System <root\@$domain>",
				   To      => "$user\@$domain",
				   Subject => "Your PDF file");
	
	
	$message = <<EOM;
Hello,

This is the PDF Writer System. I have converted your printjob
from $date to PDF format.

The output is attached to this mail.

EOM
	
	$top->attach(Data => $message);
	
	$top->attach(Path     => $pdftmp,
		     Filename => $name,
		     Type     => "application/pdf",
		     Encoding => "base64");
		     
	$top->print(\*MAIL);
} else {
	print MAIL <<EOM;
From: PDF Writer System <root\@$domain>
To: $user\@$domain
Subject: Error converting your document

Hello,

This is the PDF Writer System. You have sent me a document to convert
to PDF format, but something went wrong. Below is the output of the
ps2pdf program:

EOM
	
	open ERR, "<$output" or die "Cannot open $output: $!\n";

	while(<ERR>) {
		print MAIL;
	}

	close ERR;
}
	
close MAIL;

unlink $pstmp;
unlink $pdftmp;
unlink $output;

