#!/usr/bin/perl

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

=head1 NAME

    la-rename - rename object in database

=head1 SYNOPSIS

    la-rename [options] oid newoid

=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 -s|--sync syncname

Use this synchronisation

=item -o|--otype otype

Modify object having type 'otype', default is user

=back

=cut

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

if (@ARGV != 2) { pod2usage(); }

$otype ||= 'user';

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

$labase->wexported(1);

if ($labase->can('SetCB')) {
    $labase->SetCB( sub {
        my ( $base, $res ) = @_;
        if ($res) {
            print $base->label . ': Object renamed' . "\n";
            $base->commit;
        } else {
            warn $base->label . ': Cannot rename object' . "\n";
            $base->rollback;
        }
    } );
}

if (!$labase->rename_object($otype, @ARGV)) {
    die "Some errors occurs, please check\n";
}

