#!/usr/bin/env perl

package tcms::useradd;

use strict;
use warnings;

use FindBin::libs;
use Getopt::Long;
use Pod::Usage;
use List::Util qw{first};

use Trog::Auth;
use Trog::Data;
use Trog::Config;
use Trog::Log;

# Don't murder our terminal when done
$ENV{NOHUP} = 1;

=head1 SYNOPSIS

Add or edit a tCMS user.  In the event of a user edit, every option save for user is optional.

does not update user pages.  Use this to reset user passwords or fix broken users.

=head2 USAGE

tcms-useradd --user foo --password bar --display_name baz --contact_email foo@bar.baz --acl fred --acl wilma

=head2 OPTIONS

=over 4

=item --user

Specify the user to add, or edit if the user already exists.

=item --password

Set a password for the user.  Leave blank if you want to keep the password for an existing user.

=item --display_name

Set the display name for the user.

=item --contact_email

Set the contact email for the user.

=item --acl

Set an acl for this user.  May be passed multiple times.
Defaults to 'admin' acl.

=item --help, --man

Display this output.

=back

=cut

sub main {
    my %options;
    Getopt::Long::GetOptionsFromArray(
        \@_,
        'user=s'          => \$options{user},
        'display_name=s'  => \$options{display_name},
        'help|?'          => \$options{help},
        'password=s'      => \$options{password},
        'contact_email=s' => \$options{contact_email},
        'acl=s@'          => \$options{acl},
    );
    pod2usage( -exitval => 0, -verbose => 1 ) if $options{help};

    $options{acl} //= [];
    $options{acl} = [ $options{acl} ] if $options{acl} && ref $options{acl} ne 'ARRAY';
    $options{acl} = ['admin'] unless @{ $options{acl} };

    Trog::Auth::killsession( $options{user} );
    eval { Trog::Auth::useradd( $options{user}, $options{display_name}, $options{password}, $options{acl}, $options{contact_email} ) } or do {
        return 1;
    };

    # Find the user's post and edit it
    my $conf = Trog::Config::get();
    my $data = Trog::Data->new($conf);

    my @userposts = $data->get( tags => ['about'], acls => [qw{admin}] );
    my $user_obj  = first { ( $_->{user} || '' ) eq $options{user} } @userposts;
    my %merged    = (
        %$user_obj,
        %options,
        $options{display_name} ? ( local_href => "/users/$options{display_name}" ) : ( local_href => $user_obj->{local_href} ),
    );

    # We don't want the password in plain text
    delete $merged{password};

    # The ACLs a user posesses is not necessarily what ACLs you need to view or edit a user's profile.
    delete $merged{acl};

    $data->add( \%merged );
    return 0;
}

exit main(@ARGV) unless caller;

1;
