#!/usr/bin/perl

# Copyright (C) 1996 Friedrich Leisch

# 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, 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 file.  If not, write to the Free Software Foundation,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

# Send any bug reports to Friedrich.Leisch@ci.tuwien.ac.at

# Update by FL on 22.3.1996
# Update for flpr 2.0 on 4.7.1996

# flprlog, creates a logfile for ps printers
# options: -n user name
#          -h host name
# -n and -h are supplied by lpd when used as an input filter

use Getopt::Std;

do getopt('cwlinh');

$logf=$ARGV[0];
@ARGV=();

open(logfile, ">>$logf");

format logfile =
@<<<<<<@<<<<<@<<<<<<<<<<<<<<<@<<<<<<<<<<@||||@||||@<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$date,   $time,$opt_n,         $opt_h, $pages1,$pages2,$title
.

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$date = sprintf("%02d%02d%02d", $year, $mon+1, $mday);
$time = sprintf("%02d:%02d", $ hour, $min);

$pagefound = "";

$pages1=0;
$pages2=0;

$notify="";
$accstring="";

$c1 = getc;
$c2 = getc;

if( ($c1 eq "%") && ($c2 eq "!") ) {
    print $c1,$c2;
    while(<>){
	print;
	if(/%%Page:/){
	    $pages1++;
	}	
	if(/%%Pages:/ && !($pagefound)){
	    chop;
	    ($anfang, $pages2, $rest) = split(/ /, $_, 3);
	    $pagefound=($pages>0);
	}
	if(/%%Title:/){
	    chop;
	    ($anfang, $title) = split(/ /, $_, 2);
	}
	if(/% FLPR send mail/){
	    $notify=1;
	}
	if(/% FLPR accounting subject:/){
	    chop;
	    ($anfang, $accstring) = split(/: /, $_, 2);
	    $title = "$accstring: $title";
	}
    }
}
else{
    $title="!!! NO POSTSCRIPT FILE !!!";
    open(mail, "|mail -s \"Printer Error - Print Job Cancelled\" $opt_n");
    print mail "Are you sure the file you wanted to print";
    print mail " is a Postscript file?\n\n";
    print mail "Possible Solution: use flpr instead of lpr.\n";
    print mail "Contact your system administrator for more information.\n";
    close mail;
}

write logfile;

close logfile;

if($notify){
    open(mail, "|mail -s \"Printed file $title\" $opt_n");
    print mail "Successfully printed file $title\n";
    print mail "Job started at $time\n";
    print mail "$pages1 page(s)";
    close mail;
}


