#!/usr/bin/perl

use strict;
use warnings;
use LATMOS::Accounts;
use LATMOS::Accounts::Utils;
use Getopt::Long;
use Pod::Usage;

=head1 NAME

    la-gen-passwd - set random password to user.

=head1 SYNOPSIS

    la-gen-passwd [options] userid [userid1 [...]]

=head1 OPTIONS

=over 4

=item -c|--config configdir

Use this configuration directory instead of the default one.

=item -b|--base basename

Query this specific base instead of the default one.

=item -s|--sync syncname

Use this synchronisation

=item -l length

Generate password of C<length> characters

=item -p

Include non alpha-numeric characters (such as C<#>, C<:>, etc.).

=item --syl

Use syllable instead full random characters

=item -o file

Store the list of username and generated password into F<file>.

=back

=cut

my %gen_options;

GetOptions(
    'c|config=s' => \my $config,
    'b|base=s'   => \my $base,
    's|sync=s'   => \my $sync,
    'p'          => \$gen_options{nonalpha},
    'syl'        => \$gen_options{syllables},
    'l=i'        => \$gen_options{length},
    'o=s'        => \my $output,
    'help'       => sub { pod2usage(0) },
) or pod2usage();

my $otype = 'user';

my $LA = LATMOS::Accounts->new($config, noacl => 1);
my $labase = $base ? $LA->base($base) : $LA->sync_access($sync);
$labase && $labase->load or die "Cannot load base";

$labase->wexported(0);

my $handle;
if ($output) {
    open($handle, '>', $output) ||
        die "Cannot open $output file $!\n";
}

foreach my $user (@ARGV) {
    my $obj = $labase->get_object($otype, $user) or do {
        warn "Object $otype $user not found\n";
        next;
    };

    my $password = LATMOS::Accounts::Utils::genpassword(
        %gen_options
    );

    if ($obj->set_password($password)) {
        print "$user $password\n";
        print $handle "$user $password\n" if ($handle);
        $labase->commit;
    } else {
        warn "Error when trying to change password for $user\n";
    }
}

close($handle) if ($handle);

exit 0;
