#!/usr/bin/perl -w

##############################################################################
#
# Print billing management system - admin tools, 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 utility allows all valid users in with accounts on the system to be
# given an initial credit level on the quota system. Originally this pulled
# names out of /etc/passwd, now it does this in a more intelligent way.
#
##############################################################################

use Locale::gettext;
use POSIX;
use strict;
use Printbill::printbill_pcfg;

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

%params = pcfg ($config);

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

my $min = 1000;
my $max = 65533;
my $initial_credit = 5.00;
my ($tmp, $user, @users, $id, $i);

printf gettext ("Minimum UID to recognise as a user? [%i] "), $min;
$tmp = <STDIN>;
chomp $tmp;

if ($tmp ne "") {
	if (!isdigit ($tmp)) {
		printf gettext ("%s: Error: %s is not a valid UID.\n"), $0, $tmp;
		exit -1;
	} else {
		$min = $tmp;
	}
}

printf gettext ("Maximum UID to recognise as a user? [%i] "), $max;
$tmp = <STDIN>;
chomp $tmp;

if ($tmp ne "") {
	if (!isdigit ($tmp)) {
		printf gettext ("%s: Error: %s is not a valid UID.\n"), $0, $tmp;
		exit -1;
	} else {
		$max = $tmp;
	}
}

printf gettext ("Initial credit? [%s%.2f] "), $initial_credit, $params{'currency_symbol'};
$tmp = <STDIN>;
chomp $tmp;

if ($tmp ne "") {
	if (!isreal ($tmp)) {
		printf gettext ("%s: Error: %f is not a valid real number.\n"), $tmp;
		exit -1;
	} else {
		$initial_credit = $tmp;
	}
}

$i = 0;
@users = ();

while ($id = getpwent) {
	$users[$i++] = $id;
};

foreach $user (@users) {
	$id = (getpwnam ($user))[2];
				
	if ($id >= $min && $id <= $max) {
		print "$user (uid = $id)\n";

		`pqm --add $user`;

		if ($? >> 8) {
			printf gettext ("%s: Error: pqm --add %s failed.\n"), $0, $user;
			exit -1;
		} else {
			`pqm --inc $user --amount $initial_credit`;

			if ($? >> 8) {
				printf gettext ("%s: Error: pqm --inc %s --amount %.2f failed.\n"), $0, $user, $initial_credit;
				exit -2;
			}
		}
	}
}

print gettext ("\nDone.\n\n");

exit 0;

sub isreal {
	my ($arg) = shift;
	return ($arg =~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/);
}
