#!/usr/bin/perl

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

=head1 NAME

    la-passwd - set user password                                          
                                                                            
=head1 SYNOPSIS                                                            
                                                                             
    la-passwd [options] userid                                             

=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 -t|--test

Don't change the password but check its validity using CrackLib.

=back

=cut

GetOptions(
    'c|config=s' => \my $config,
    'b|base=s'   => \my $base,
    't|test'     => \my $test,
    's|sync=s'   => \my $sync,
    'f|force'    => \my $force,
    'help'       => sub { pod2usage(0) },
) or pod2usage();

if (!$ARGV[0]) {warn "You must specify 'userid', aborting\n"; 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(1);

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

ReadMode('noecho');
print "Enter password: ";
my $password = ReadLine(0);
ReadMode 0;
print "\n";
chomp($password);

my $res = $obj->check_password($password);

if ($res !~ /^ok$/) {
    print "Password quality: " . $res . "\n";
    die "Cannot set bad password, use --force to bypass security\n" unless($force);
}

exit(0)  if($test);

if ($obj->set_password($password)) {
    print "Password succefully changed\n";
    $labase->commit;
    exit 0;
} else {
    warn "Error when trying to change password\n";
    exit 1;
}
