#!/usr/bin/perl

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

=head1 NAME

    la-ban-passwd - Deny password for user

=head1 SYNOPSIS

    la-passwd [options] user password
    la-passwd --current user

=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 --current

Ban the current password for this user

=item -l|--lock

Lock the account

=item -e|--encrypted

The password given is already encrypted and must be store without modification

=back

=cut

GetOptions(
    'c|config=s'  => \my $config,
    'b|base=s'    => \my $base,
    'l|lock'      => \my $lock,
    'e|encrypted' => \my $encrypted,
    'current'     => \my $current,
    'help'        => sub { pod2usage(0) },
) or pod2usage();

my ($user, $password) = @ARGV;

if (!$password && !$current) {
    warn "You must specify a password or --current\n";
    pod2usage(1);
}

my $otype = 'user';

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

$labase->wexported(1);

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

if ($lock) {
    $obj->set_c_fields('locked', 1);
    print "User $user locked\n";
}

if ($current) {
    $obj->banCurrentPassword;
    print "Current password banned\n";
} else {
    if ($encrypted) {
        my @salt_char = (('a' .. 'z'), ('A' .. 'Z'), (0 .. 9), '/', '.');
        my $salt = join('', map { $salt_char[rand(scalar(@salt_char))] } (1 .. 8));
        $password = crypt($password, '$1$' . $salt);
    }
    $obj->storeBannedPassword($password);
    print "Given password banned\n";
}

$labase->commit;
exit 0;
