#!/usr/bin/perl -w
#This is multi printer `lpr' frontend <steffen@dett.de> $Revision: 1.1 $
#
# Invokes the command $prog for each -P option, passing this
#   single -P option, ALL others and STDIN (standard input).
#   Aborts on first error.
#   STDIN is held in RAM completely, so it shouldn't be too large.
#
# The option --std-debug enables debug (it is not passed to $prog).

use strict;

#my $prog = '/usr/bin/lpr';
my $prog = '/home/steffen/public_html/cgi/test.cgi';

# for --std-debug
my $debug = 0;
sub dprint($$);

my @opts = ();
my @printers = ();

# opts to opts, except -P to printers
foreach my $opt (@ARGV) {
    if ($opt =~ m/^--std-debug/) {
        $debug++;
    } elsif ($opt =~ m/^-P/) {
        push @printers, $opt;
    } else {
        push @opts, $opt;
    }
}

dprint(1, "Debuglev: " . $debug);
dprint(1, "Printers: " . join(",", @printers));
dprint(1, "Opts:     " . join(",", @opts));

# more than one: iterate
if ($#printers > 0) {
    # store complete stdin
    my @stdin = (<STDIN>);
    foreach my $printer (@printers) {
        my $pipe = "$prog $printer " . join(" ", @opts);
        dprint(1, "Command:  " . $pipe);
        open(PIPE, "| $pipe")
            or die "Failed to open pipe to $prog: $!\n";
        local $SIG{PIPE} = sub {
            die "spooler pipe broke:\n" . "  " . $pipe . "\n"
        };
        binmode PIPE;
        print PIPE @stdin
            or die "Failed to pipe to $prog: $!\n";
        close(PIPE)
            or die "Failed to pipe to $prog: $!\n";
        dprint(1, "Command ok");
    }
} else {
    dprint(1, ($#printers + 1) . " printer(s) only -> exec");
    exec $prog, @opts
        or die "Failed to exec $prog: $!\n";
}



# debug print (stderr)
sub dprint($$)
{
    my $level = shift;
    if ($debug < $level) {
        return;
    }
    my $message = shift;
    warn "DBG: $message\n";
}


