#!/usr/bin/perl  -w
#==============================================================================
# lat-pseudonyms
# ==============
# 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 %domains;
tie %domains, 'esmith::config', '/home/e-smith/db/domains';
my ($Hlp, $Cml, $Frc, $Inp);
my $Add =0;
my $Del =0;

#==============================================================================
#  Main
#==============================================================================
# Analyze commandline options
GetOptions  ("help"           => \$Hlp,
             "add"            => \$Add,
             "delete"         => \$Del,
             "force"          => \$Frc,
             "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)) ||
    ($Add + $Del != 1))
	{ &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; }

# 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 (((db_get(\%accounts, $fields[0])) && (db_get_type(\%accounts, $fields[0]) eq "user" )) ||
        ((db_get(\%accounts, $fields[0])) && (db_get_type(\%accounts, $fields[0]) eq "group")) ||
        ($fields[0] eq 'admin')) {
        if (@fields == 1 )
            { print "We need at least one pseudonym for user '$fields[0]' to perform this action.\n\a"; }
        for (my $count=1; $count<@fields;++$count) {
            # Add pseudonyms
            if ($Add) {
                if ( ! db_get(\%accounts, $fields[$count])) {
                    if ( &TestName($fields[$count])) {
                        print "Creating pseudonym '$fields[$count]' for user $fields[0]...\n";
                        db_set(\%accounts, $fields[$count], 'pseudonym', {"Account", $fields[0]});
                        system("/sbin/e-smith/signal-event", "pseudonym-create", $fields[$count], $fields[0]) == 0
                            or die("An error occurred while creating pseudonym '$fields[$count]'.\n\a");
                    }
                }
                else { print "Pseudonym '$fields[$count]'already exists.\n\a"; }
            }

            # Delete pseudonyms
            if ($Del) {
                if ((db_get(\%accounts, $fields[$count])) &&
                    (db_get_type(\%accounts, $fields[$count]) eq "pseudonym")) {
                    my $yn = 'yes';
                    if (! $Frc) {
                        print "Do you want to delete pseudonym '$fields[$count]' [yes/NO/all]? ";
                        $yn = <STDIN>;
                        if ($yn =~ /^a/i) { $Frc = -1; $yn="yes"; }
                    }
                    if ($yn =~ /^y/i) {
                        print "Deleting pseudonym '$fields[$count]'.\n";
                        db_delete(\%accounts, $fields[$count], 'pseudonym', {"Account", $fields[0]});
                        system("/sbin/e-smith/signal-event", "pseudonym-delete", $fields[$count], $fields[0]) == 0
                            or die("An error occurred while deleting pseudonym '$fields[$count]'.\n\a");
                    }
                }
                else { print "Pseudonym '$fields[$count]' does not exist on this server.\n\a"; }
            }
        }
    }
    else { print "There is no user or group with the name '$fields[0]' on this server.\a\n"; }
}
#==============================================================================
# Subroutines
#==============================================================================
# Test name for illegal characters
sub TestName {
    if ( $_[0] =~ /^[a-z][a-z\-\_\d\.]*$/ ) {
        return -1;
    }
    elsif ( $_[0] =~ /^[a-z][a-z\-\_\d\.]*\@([a-z\-\_\d\.]*)$/  ) {
        print "Trying to create a pseudonym specific for $1 domain,\n";
        print "checking if domain is configured for this server... \n";
        if (((db_get(\%domains, $1)) && (db_get_type(\%domains, $1) eq "domain" )) ){
                print "yes, it exists, go on!!\n";
                return -1
        }
    }
    else {
        print "The pseudonym '$_[0]' contains illegal characters. The name should ";
        print "contain only\nlower-case letters, numbers, hyphens, periods ";
        print "and underscores, and should\nstart with a lower-case letter.\n\a";
        return 0;
    }
}
#==============================================================================
# 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-pseudonyms> - The lazy administrator's tool to add pseudonyms

=head1 DESCRIPTION

Adds or deletes e-mail pseudonyms to existing user or group accounts on Mitel's SME servers (5.x/6.x).
This tool is functionally equivalent to the 'Pseudonyms' 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 create a large number of e-mail aliases in a batch process, or delete the standard pseudonyms on a remote machine via an ssh console.

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

=head1 SYNOPSIS

B<lat-pseudonyms> -a -c "username | pseudonym1 | pseudonym2"

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

B<lat-pseudonyms> -d [-f] -c "user | pseudonym"

B<lat-pseudonyms> -d [-f] -i /path/to/quota.list

=head1 OPTIONS

The following options are supported:

=over 4

=item B<-a>, B<--add>

Add a pseudonym to a user or group.

=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<-d>, B<--delete>

Delete a pseudonym from the server

=item B<-f>, B<--force>

Don't prompt before deleting.

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

Extended help for this tool

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

Use the information from FILE to create or delete the pseudonyms.

=back

=head2 Arguments:

   user*      : Must be a valid user or group on the server.
   pseudonym* : Must contain only lower-case letters, numbers,
                hyphens, arobase, periods and underscores, and should
                start with a lower-case letter.

   * mandatory field

=head1 EXAMPLES

B<lat-pseudonyms -a -c "harry | wizard | seeker |potter@existinglocaldomain.com">

Creates the pseudonyms 'wizard', 'seeker' and 'potter@existinglocaldomain.com'  for user 'harry'.

B<lat-pseudonyms -a -i /root/pseudonyms.list>

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

B<lat-pseudonyms -d -f -c "harry | wizard | seeker">

Deletes pseudonyms  'wizard' and 'seeker' from user 'harry'. The pseudonyms are deleted without prompting (-f).

=head1 SEE ALSO

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

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