#!/usr/bin/perl -w

##############################################################################
#
# Print billing management system - bottom-level queue filter, version 4.2.0
#
# Copyright (C) 2000, 2001, 2002, 2003 Daniel Franklin
#
# This program is distributed under the terms of the GNU General Public
# License Version 2.
#
# This filter is used as the final component in the two-stage print queue
# scheme. It accepts any job print job from the special user
# $params{"printbilld_user"} (`lp' on Debian).
#
##############################################################################

use Printbill::printbill_pcfg;
use Getopt::Long;
use Sys::Syslog qw(:DEFAULT setlogsock);
use Locale::gettext;
use POSIX;
use strict;

setlocale (LC_MESSAGES, "");
textdomain ("printbill");

# $config is where we store the prices.

my $config = "/etc/printbill/printbillrc";
my $user = "";
my $JSUCC = 0;
my $JREMOVE = 3;
my %params;
my $deathstr;

setlogsock('unix') or &abortjob (sprintf (gettext ("%s: Error: cannot set log type: %s\n"), $0, $!));

openlog ($0, 'cons', 'lpr');

# Parse standard command-line options sent to us by lprng

if ($] >= 5.005) {
	Getopt::Long::Configure ("pass_through");
	Getopt::Long::Configure ("bundling");
} else {
	Getopt::Long::config ("pass_through");
	Getopt::Long::config ("bundling");
}

GetOptions ("n=s" => \$user);

&abortjob (sprintf (gettext ("%s: Error: user must be specified via -n option.\n"), $0)) if (! defined $user);

%params = pcfg ($config, "");

&abortjob (sprintf (gettext ("%s: Error: problems parsing configuration file.\n"), $0)) if (! scalar (%params));

# At this point we have all configuration options and the command-line
# arguments which have been passed to us by lprng.

if ($user eq $params{'printbilld_user'}) {
	syslog ('info', gettext ("Secondary queue has accepted job."))
		or &abortjob (sprintf (gettext ("%s: Error: could not write to syslog: %s.\n"), $0, $!));

	exit $JSUCC;
} else {
	syslog ('info', sprintf (gettext ("Secondary queue has rejected job - printing user \"%s\" should be %s."), $user, $params{'printbilld_user'}))
		or &abortjob (sprintf (gettext ("%s: Error: could not write to syslog: %s.\n"), $0, $!));

	exit $JREMOVE;
}

sub abortjob {
	my ($text) = @_;
	print STDERR "$text";
	syslog 'err', $text;
	exit $JREMOVE;
}
