#!/usr/bin/perl

use strict;
use warnings;
use LATMOS::Accounts;
use Getopt::Long;
use Pod::Usage;
use LATMOS::Accounts::Cli::Context;
use LATMOS::Accounts::Cli;

=head1 NAME

    la-cli - A powerfull commandline tool to manage LATMOS::Accounts contents

=head1 SYNOPSIS

    la-cli [options]

=cut

GetOptions(
    'c|config=s'        => \my $config,
    'b|base=s'          => \my $base,
    't|transaction'     => \my $transmode,
    'no-unexp|wo-unexp' => \my $nounexp,
    'with-unexp'        => \my $unexp,
    'u|username=s'      => \my $username,
    'help'              => sub { pod2usage(0) },
) or pod2usage();

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

Enable transaction mode: don't commit at earch command

=item --unexp

Take into account all objects (even non propagated ones, with attribute 'exported'=0)

=item --no-unexp

Take into account only propagated objects (attribute 'exported'=1) (default)

=item -u|--username USER

Simulated access like user USER is login

=back

=cut

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

$labase->unexported($nounexp ? 0 : 1);

my $Context = LATMOS::Accounts::Cli::Context->new(
    base => $labase,
    TransMode => $transmode ? 1 : 0,
);

my $Env = LATMOS::Accounts::Cli->new(
    Context => $Context,
);

if (@ARGV) {
    $Env->run(@ARGV);
} else {
     my $history = "$ENV{HOME}/.lacli_history";
     $Env->Context->Term->ReadHistory($history);
     $Env->cli;
     if (! $Env->Context->Term->WriteHistory($history)) {
         warn "Cannot write history:  $!\n";
     }
}
print "\n";

exit 0;

