#!/bin/env perl

# $Id$

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

=head1 NAME

    la-chpasswd - Change user password

=head1 SYNOPSIS

    la-chpasswd [-u username]

=head1 OPTIONS

=over4

=item -u username

Specify the username for which the password must be changed. C<$USER>
envirronment variable is used if not given.

=item --url url

Specify the server url to contact. By default the url is fetched from DNS
C<_link_accounts> C<TXT> record.

=back

=cut

GetOptions(
    'url=s'      => \my $url,
    'u|user=s'   => \my $user,
) or pod2usage();

$user ||= $ENV{USER};

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

print "Enter new password: ";
my $password = ReadLine(0);
print "\n";
print "Confirm new password: ";
my $password2 = ReadLine(0);
ReadMode 0;
print "\n";
chomp($password);
chomp($password2);
chomp($oldpassword);

if ($password ne $password2) {
    die "Password mismatch\n";
}

my $lar = Link::Accounts::Remote->new($url);

if ($lar->query(
        'user.change_password',
        $user,
        $oldpassword,
        $password,
    )) {
    print "Password succefully changed\n";
    exit 0;
} else {
    die "Error when trying to change password: " . $Link::Accounts::Remote::ERROR . "\n";
}

