#!/usr/bin/perl -w

##############################################################################
#
# Print billing management system - admin tools, 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 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 POSIX;
use strict;

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

print "Minimum UID to recognise as a user? [$min] ";
$tmp = <STDIN>;
chomp $tmp;

if ($tmp ne "") {
	if (!isdigit ($tmp)) {
		print "Error: $tmp is not a valid UID\n";
		exit -1;
	} else {
		$min = $tmp;
	}
}

print "Maximum UID to recognise as a user? [$max] ";
$tmp = <STDIN>;
chomp $tmp;

if ($tmp ne "") {
	if (!isdigit ($tmp)) {
		print "Error: $tmp is not a valid UID\n";
		exit -1;
	} else {
		$max = $tmp;
	}
}

printf "Initial credit? [\$%.2f] ", $initial_credit;
$tmp = <STDIN>;
chomp $tmp;

if ($tmp ne "") {
	if (!isreal ($tmp)) {
		print "Error: $tmp is not a valid real number\n";
		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) {
			print "$0: error running pqm --add $user.\n";
		} else {
			`pqm --inc $user --amount $initial_credit`;

			if ($? >> 8) {
				print "$0: error running pqm --inc $user --amount $initial_credit.\n";
				exit -1;
			}
		}
	}
}

print "\nDone.\n\n";

exit 0;

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