#!/usr/bin/perl 
#
# kopiererd; wird mit inetd gestartet.

use strict;
use warnings;

use Sys::Syslog;
openlog('Kopierer', 'pid', 'user');

# Anfangswerte.
our %auftrag = (Anzahl => 1,
	        Schwelle => 70);
our $MinAnzahl = 1;
our $MaxAnzahl = 20;
our $MinSchwelle = 0;
our $MaxSchwelle = 100;
our $Geraet = 'umax:/dev/sg0';     # anpassen! (scanimage -L)

# Eingangsparameter abfragen.
while (my $par = <>) {
  chomp $par;
  $par =~ s/^\s*//;
  $par =~ s/\s*$//;
  last if $par eq '.';
  my ($name, $wert) = split '\s*=\s*', $par;
  $auftrag{$name} = $wert;
}

# Eingangsparameter prfen und plausibilisieren.
$auftrag{Anzahl} = $MinAnzahl if $auftrag{Anzahl} < $MinAnzahl;
if ($auftrag{Anzahl} > $MaxAnzahl) {
  print "Es sind nur $MaxAnzahl Kopien erlaubt.\n";
  exit 0;
}
$auftrag{Schwelle} = $MinSchwelle if $auftrag{Schwelle} < $MinSchwelle;
if ($auftrag{Schwelle} > $MaxSchwelle) {
  print "Es sind nur Schwellenwerte von $MinSchwelle bis $MaxSchwelle erlaubt.\n";
  exit 0;
}

use File::Temp qw/ tempdir /;
my $tempdir = tempdir('Kopierer.XXXX', TMPDIR => 1, CLEANUP => 1);
syslog(info => "Anzahl: $auftrag{Anzahl} / Schwelle: $auftrag{Schwelle}");

# Scanner benutzen.
{
  my $cmd = "/usr/bin/scanimage -d $Geraet --mode Lineart --resolution 600 --threshold '$auftrag{Schwelle}' > $tempdir/pbm";
  syslog(info => $cmd);
  if (system $cmd ) {
    print "Fehler: $! // $?";
    exit 0;
  }
}

# Nach Postscript konvertieren.
{
  my $cmd = "/usr/bin/pnmtops -equalpixels -dpi 600 -width 8 -height 11.6 $tempdir/pbm > $tempdir/ps";
  syslog(info => $cmd);
  if (system $cmd ) {
    print "Fehler: $! // $?";
    exit 0;
  }
}

# Postscript drucken.
{
  my $cmd = "lpr -# $auftrag{Anzahl} $tempdir/ps";
  syslog(info => $cmd);
  if (system $cmd ) {
    print "Fehler: $! // $?";
    exit 0;
  }
}

closelog();
