#!/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

=cut

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

my $otype = 'user';

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

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";

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;
}
