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

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

# Check for e-smith-user-panel
my $UPanel=`rpm -qa | grep -c "smeserver-userpanel"`;
my  $MSorting=`rpm -qa | grep -c "smeserver-mailsorting"`;
if ( $UPanel < 1 || $MSorting < 1) {
    print "\nThis tool requires the smeserver-userpanel and smeserver-mailsorting  contribution.\n";
    print "Please download them with yum from smecontribs repo and configure them first.\n\n\a";
    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+$//; }}
    my $username = $fields[0];

    if ( @fields >= 2) {  # The first two arguments are manadatory.
        my $enabled = 0; if ($fields[1] =~ /^e/i) { $enabled=-1 }
        my %user = ("deldups",  $fields[2],
                    "loglevel", $fields[3],
                    "mode",     $fields[4]);
        if ( $fields[2] ) { $user{'deldups'}  = $fields[2] } else { $user{'deldups'}  = "no" }
        if ( $fields[3] ) { $user{'loglevel'} = $fields[3] } else { $user{'loglevel'} = "some" }
        if ( $fields[4] ) { $user{'mode'}     = $fields[4] } else { $user{'mode'}     = "normal" }

        if ((db_get(\%accounts, $username)) &&
            (db_get_type(\%accounts, $username) eq "user")) {
            if ($enabled) {
                if (&ValidArguments(\%user, $username)) {
                    print "Activating procmail for user '$username'.\n";
                    db_set(\%processmail, $username, 'settings', \%user);
                    db_set_prop(\%accounts, $username, 'EmailForward', 'procmail');
                    system("/sbin/e-smith/signal-event", "email-update-quick", $username) == 0
                        or die ("An error occurred while updating account '$username'.\n");
                }
            }
            else {
                print "Deactivating procmail for user '$username'.\n";
                db_delete(\%processmail, $username, 'settings', \%user);
                db_set_prop(\%accounts, $username, 'EmailForward', 'local');
                system("/sbin/e-smith/signal-event", "email-update-quick", $username) == 0
                    or die ("An error occurred while updating account '$username'.\n");
            }
        }
        else { print "User '$username' doesn't exist on this server.\n\a"; }
    }
    else { print "We need at least a user name and its status ('enabled' or 'disabled').\n\a"; }
}
#==============================================================================
# Subroutines
#==============================================================================
# Test the various arguments for their validity
sub ValidArguments {
    my $href = $_[0];
    my $nm   = $_[1];
    my $ret  = 1;

    if ( ! ($href->{'deldups'} =~ /^[yn]/i )) {
        print "Can't activate procmail for user '$nm'.\n";
        print "The 'delete duplicates' argument must be either 'yes' or 'no'.\n\a";
        $ret = 0;
    }
    if ( ! ($href->{'loglevel'} =~ /^[nsl]/i )) {
        print "Can't activate procmail for user '$nm'.\n";
        print "The 'loglevel' argument must be either 'none', 'some' or 'lots'.\n\a";
        $ret = 0;
    }
    if ( ! ($href->{'mode'} =~ /^[ng]/i )) {
        print "Can't activate procmail for user '$nm'.\n";
        print "The 'mode' argument must be either 'normal' or 'geek'.\n\a";
        $ret = 0;
    }

    return $ret;
}
#==============================================================================
# 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-procmail> - The lazy administrator's tool to (de)activate procmail for individual users

=head1 DESCRIPTION

Activates or deactivates procmail for individual users on Mitel's SME servers.
This tool is primarily intended to activate B<SpamAssassin> system-wide, but can also be used for other purposes.

It requires  smeserver-userpanel and smeserver-mailsorting.

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

=head1 SYNOPSIS

B<lat-procmail> -c "user| status| deldups| loglevel| mode"

B<lat-procmail> -i /path/to/users.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 (de)activate procmail for individual users.
See F</usr/doc/lazy-admin-tools> for an example of an input file.

=back

=head2 Arguments:

   user*      : Must be an existing account on the server.
                Wildcards (* and ?) are accepted.
   status     : Either 'enabled' or 'disabled'.
                Default is 'disabled'.
   deldups    : Delete duplicates. Use 'yes' or 'no'.
                Default is 'no'.
   loglevel   : Amount of log info. Use 'none', 'some' or 'lots'.
                Default is 'some'.
   mode       : Set 'normal' or 'geek' mode. Default is 'normal'.

   * mandatory field

=head1 EXAMPLES

B<lat-procmail  -c "harry | enabled | yes | lots | geek">

Activates procmail for user 'harry', deletes duplicate mails with extensive logging and activates geek-mode.

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

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

=head1 SEE ALSO

lat-group(8), lat-pseudonyms(8), lat-ibays(8), lat-quota(8), lat-domains(8), lat-hosts(8), lat-users(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

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