#!/usr/bin/perl -w

##############################################################################
#
# Print billing management system - bill thyself, version 4.1.2
#
# Copyright (C) 2000, 2001, 2002, 2003 Daniel Franklin
#
# This program is distributed under the terms of the GNU General Public
# License Version 2.
#
# This script lets users deduct fixed-price items from their own print
# quota. Think of it as an electronic coffee kitty.
#
##############################################################################

use Printbill::PTDB_File;
use Printbill::printbill;
use Printbill::printbill_pcfg;
use POSIX 'setsid';
use File::Temp qw/ tempdir /;
use Fcntl;
use strict;

# $config is where we store the prices.

my $configdir = "/etc/printbill";
my $BILLPRINTER = "billme";
my $config = "$configdir/printbillrc";
my %params = pcfg ($config);
my (%wareshash, $key, $user, $indefinite_article, %userhash, $dir);

tie %wareshash, "Printbill::PTDB_File", "$params{'db_home'}/wares.db", "TRUE"
	or die "Sorry - can't open the products database: $!\n";
	
umask 0077;
$dir = tempdir (CLEANUP => 1);

if ($#ARGV != 0) {
	print "Usage: $0 [item]\n\nPrices follow:\n\n";
		
	foreach $key (sort keys %wareshash) {
		printf "$key:\t$params{'currency_symbol'}%.2f\n", $wareshash{$key};
	}

	print "\n";
		
	untie %wareshash;
	
	exit 0;
}

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

# Check the names - do any of them match things for which we are billing?

$user = POSIX::cuserid ();

if (defined ($wareshash{$ARGV[0]})) {
# Best get our grammar correct... :)
	if ($ARGV[0] =~ /^[aeiou]/) {
		$indefinite_article = "an";
	} else {
		$indefinite_article = "a";
	}
	
	tie %userhash, "Printbill::PTDB_File", "$params{'db_home'}/users/$user.db", "TRUE"
		or die "You have no print quota, it seems. Pay in cash or harrass the admin.\n";

	if ($userhash{"quota"} >= $wareshash{$ARGV[0]}) {
		`/bin/echo > $dir/$ARGV[0]`;
		`$params{'lpr'} -P$BILLPRINTER $dir/$ARGV[0]`;
	
		if ($? == 0) {
# Wait a moment - the print daemon has to `process' the job.
			printf "Your original quota was %.2f.\n", $userhash{"quota"};
			printf "You just tried to buy $indefinite_article $ARGV[0] for $params{'currency_symbol'}%.2f.\n", $wareshash{$ARGV[0]};
			print "Your honesty is appreciated.\n";
			printf "Remaining quota is %.2f.\n", $userhash{"quota"} - $wareshash{$ARGV[0]};
		} else {
			print "Something screwed up. Blame the admin, he's probably drunk again.\n";
		}
	} else {
		print "
You are too poor to afford $indefinite_article $ARGV[0]. Have a glass of
refreshing tapwater instead, your teeth will thank you for it.\n";
	}
	
	untie %userhash;
} else {
	print "Usage: $0 [item] (e.g. pie, can, beer, pizza etc. - see $params{'db_home'}/wares.db\n";
	exit 0;
}
