#!/usr/bin/perl

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

=head1 NAME

    la-delete - Tools to delete object in LATMOS-Accounts

=head1 SYNOPSIS

    la-delete [options] obj_id

=cut

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

$otype ||= 'user';

=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 -o|object object_type

Query will be performed on this object. Default is the 'User' object.

=item --force

Do not ask confirmation before deleting

=back

=cut

if (!$ARGV[0]) {warn "You must specify 'obj_id', aborting\n"; pod2usage(); }

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

if (!$labase->get_object($otype, $ARGV[0])) {
    die "Cannot find object $otype $ARGV[0]\n";
}

if (!$force) {
    my $alea = int(rand(1000));
    print "Deleting object is definitive !\n";
    print "Are you sure you want to delete objet $otype $ARGV[0] ?\n";
    print "To confirm please enter this number: $alea\n";
    my $enter = <STDIN>;
    chomp($enter);
    if (!($enter =~ /^\d+$/ && $enter == $alea)) {
        die "Wonrg input, aborting\n";
    }
}

if ($labase->delete_object($otype, $ARGV[0])) {
    $labase->commit;
    print "$otype/$ARGV[0] succefully deleted\n";
    $LA->call_batch_sync;
} else {
    warn "Cannot delete $otype/$ARGV[0]\n";
    exit(1);
}
