#!/usr/bin/perl  -w
#==============================================================================
# lat-quota
# =========
# 0.9.0 (2004-09-08)
# (c)2003-2004 Altiplano bvba
#==============================================================================
package esmith;
use strict;
use esmith::db;
use Getopt::Long;
use Pod::Usage;
my %conf;
my %accounts;
tie %conf, 'esmith::config';
tie %accounts, 'esmith::config', '/home/e-smith/db/accounts';
my ($Hlp, $Cml, $Inp);

#==============================================================================
#  Main
#==============================================================================
# Analyze commandline options
GetOptions  ("help"           => \$Hlp,
             "command-line=s" => \$Cml,
             "input-file=s"   => \$Inp);
if ( $Hlp ) { &PrintPod(9); exit; }

# We need one argument or the other, but not both
if (($Cml && $Inp) || (! $Cml && ! $Inp))
	{ &PrintPod(1); exit; }

my @records;
if ($Inp) {
    open(LIST,"< $Inp")  ||  die "Can't find $Inp.\n";
    @records = grep(!/(^\s*#)|(^\s*$)/,<LIST>);
    close(LIST); }
elsif ($Cml) { @records=($Cml); }
else { &PrintPod(1); exit; }

&ExpandWildCard;  # Check for wildcards and expand if necessary

# Process each user
foreach my $record (@records)
{
    my @fields=split(/\|/,$record);
    for (my $cnt=0; $cnt <= $#fields; ++$cnt) { for ($fields[$cnt]) { s/^\s+//; s/\s+$//; }}

    if ( @fields == 3) # All three arguments must be given
    {
        my $Soft = &CalculateKB($fields[1]);
        my $Hard = &CalculateKB($fields[2]);
        if ((db_get(\%accounts, $fields[0])) &&
            (db_get_type(\%accounts, $fields[0]) eq "user"))
        {
            print "Setting quota for user $fields[0] ($fields[1]/$fields[2])\n";
            db_set_prop(\%accounts, $fields[0], "MaxBlocksSoftLim", $Soft);
            db_set_prop(\%accounts, $fields[0], "MaxBlocks", $Hard);
            system("/sbin/e-smith/signal-event", "user-modify", $fields[0]) == 0
                or die ("Error occurred while updating quota values for user $fields[0].\n");
        }
        else { print "User $fields[0] does not exist on this server.\n"; }
    }
    else { print "Illegal number of arguments for user $fields[0]\n\a";}
}

#==============================================================================
# Subroutines
#==============================================================================
# Convert from Gigabytes or Megabytes to true Kilobytes
sub CalculateKB {
   if ( $_[0] =~ m/M$|G$/ ) {
      if ($& eq "M") { return $`*1024 }
      if ($& eq "G") { return $`*1024*1024 }
   }
   else { return $_[0]; }
}
#==============================================================================
# Test for wildcards in the username. If any wildecards are found, the array
# @records is expanded with the user names that meet the conditions.
sub ExpandWildCard {
    my $ctrec = 0;
    foreach my $record (@records)
    {
        my @fld=split(/\|/,$record);
        for (my $cnt=0; $cnt <= $#fld; ++$cnt) { for ($fld[$cnt]) { s/^\s+//; s/\s+$//; }}

        if ($fld[0] =~ /\*|\?/) {   # Does it contain the wildcards?
            $fld[0] =~ s/\*/\.\*/g; # Replace * with .* to allow for grep.
            $fld[0] =~ s/\?/\./g;   # Replace ? with . to allow for grep.

            open USRS, "</home/e-smith/db/accounts" or die "Can't open /home/e-smith/db/accounts: $!";
            my @match = grep /^$fld[0]\=user\|/i, <USRS>;
            close(USRS);

            my $cu = 0;
            foreach my $tst (@match) {
                $tst =~ /\=/; $tst = $`;
                for (my $cnt=1; $cnt <= $#fld; ++$cnt) { $tst = $tst." | ".$fld[$cnt]; };
                if ($cu == 0 ) {
                    $records[$ctrec] = $tst;
                    $cu =1;
                }
                else {
                    push(@records, $tst);
                }
            }
        }
        ++$ctrec;
    }
}
#==============================================================================
# Print the pod text as a help screen
sub PrintPod {
    my ($verbose, $message) = @_;
    pod2usage(-verbose => $verbose, -message => $message, -exitval => 64);
}

#==============================================================================

=pod

=head1 NAME

B<lat-quota> - The lazy administrator's tool to set user quota

=head1 DESCRIPTION

Sets the disk quota for individual users on Mitel's SME servers (5.x/6.x).
This tool is functionally equivalent to the 'Quota management' option in the server-manager, but can be run from the command line or called from an other script.
It allows you, for example, to set the disk quota for a large number of accounts in a batch process or on a remote machine via an ssh console.

See F</usr/doc/lazy-admin-tools/example.quota> for the format of the input file.

=head1 SYNOPSIS

B<lat-quota> -c "user | softlimit | hardlimit"

B<lat-quota> -i /path/to/quota.list

=head1 OPTIONS

The following options are supported:

=over 4

=item B<-c "Arguments">, B<--command-line="Arguments">

Take arguments from the command line.
See the 'Arguments' section below for the various arguments that are accepted.

=item B<-h>, B<--help>

Extended help for this tool

=item B<-i FILE>, B<--input-file=FILE>

Use the information from F<FILE> to set the disk quota for individual users.

=back

=head2 Arguments:

   user*      : Must be an existing user name. Wildcards (* and ?)
                are accepted.
   softlimit* : Limit with grace period in kilobytes, unless
                followed by M (megabytes) or G (gigabytes).
   hardlimit* : Absolute limit in kilobytes, unless followed by
                M (megabytes) or G (gigabytes).
   * mandatory field

=head1 EXAMPLES

B<lat-quota -c "harry | 800M | 1G">

Sets the quota for user 'harry' to 800 MByte (soft limit) and 1 GByte (hard limit).

B<lat-quota -i /root/quota.list>

Sets the quota for the users defined in F</root/quota.list>.
Refer to F</usr/doc/lazy-admin-tools/example.quota> for an example of an input file.

B<lat-quota -c "* | 100M | 120M">

Sets the qquota for all users to 100M / 120M.

B<lat-quota -c "hermione | 0 | 0">

Turns off quota for user 'hermione'.

=head1 SEE ALSO

lat-group(8), lat-pseudonyms(8), lat-ibays(8), lat-users(8), lat-domains(8), lat-hosts(8), lat-procmail(8), lat-pptp(8), lat-dump(8)

=head1 VERSION

Version 0.9.0 (2004-09-08). The latest version is hosted at B<http://www.contribs.org/contribs/mblotwijk/>

=head1 COPYRIGHT

(c)2003-2004, Altiplano bvba (B<http://www.altiplano.be>). Released under the terms of the GNU license.

=head1 BUGS

Please report bugs to <Bugs@Altiplano.Be>

=cut

#==============================================================================
