#!/usr/bin/perl

BEGIN { die "Do not run this as root" unless $>; }

use utf8;
use strict;
use warnings;
# use lib 'lib';
use AmuseWikiFarm::Schema;
use Crypt::XkcdPassword;
use Getopt::Long;
use Pod::Usage;


=pod

=encoding utf8

=head1 NAME

amusewiki-reset-password - reset amusewiki passwords from the command line

=head1 SYNOPSIS

Usage: amusewiki-reset-password <username> [<password>] [ --create-with-role ROLE ] [ --add-to-site SITE-ID ]

Reset the password of an arbitrary user. The password is optional and
will be generated automatically if not provided.

You need to have dbic.yaml in the current directory, or in
~/.dbic.yaml with the C<amuse> stanza with the settings.

=head2 OPTIONS

=over 4

=item --create-with-role ROLE

If the user does not exist, create it with the given role. ROLE can be
C<root>, C<admin> or C<librarian>.

=item --add-to-site SITE-ID

Add the user to the given site. Root users do not need this.

=back

=cut

my %roles = map { $_ => $_ } (qw/root admin librarian/);

my $create_with_role;
my @sites;

GetOptions(
           'create-with-role=s' => \$create_with_role,
           'add-to-site=s' => \@sites,
          ) or die;

my $schema = AmuseWikiFarm::Schema->connect('amuse');

my ($username, $password) = @ARGV;
$password ||= Crypt::XkcdPassword->new(words => 'IT')->make_password(5, qr{\A[0-9a-zA-Z]{3,}\z});

die "Usage: $0 <username> [<password>]\n" unless $username && $password;

my $user = $schema->resultset('User')->find({ username => $username });

if ($user) {
    $user->password($password);
    $user->update;
    print qq{Password for $username is now '$password'\n};
}
elsif ($create_with_role) {
    if (my $role = $roles{$create_with_role}) {
        $user = $schema->resultset('User')->create({
                                                    username => $username,
                                                    password => $password,
                                                   });
        $user->set_roles([{ role => $role }]);
        print "User $username created with password '$password' and role $role\n";
    }
    else {
        die "Invalid role $create_with_role. Must be root, admin or librarian";
    }
}
else {
    print "User not found and --create-with-role not passed!\n\n";
    pod2usage;
    exit 2;
}

if (@sites) {
    my $rs = $schema->resultset('Site')->search({ id => \@sites });
    if ($rs->count) {
        foreach my $site ($rs->all) {
            if ($site->users->find({ username => $user->username })) {
                print "$username already in " . $site->id . "\n";
            }
            else {
                $site->add_to_users($user);
                print "Added $username to " . $site->id . "\n";
            }
        }
    }
    else {
        die "No site found with id " . join(" ", @sites) . "\n";
    }
}

