#!/usr/bin/perl

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

=head1 NAME

    la-sql-alias - Tools to create or edit object alias

=head1 SYNOPSIS

    la-sql-properties [options] obj_id

=cut

GetOptions(
    'c|config=s' => \my $config,
    'b|base=s'   => \my $base,
    'o|object=s' => \my $otype,
    'r|remove'   => \my $remove,
    '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 -r|remove

Remove the alias given in argument

=back

=cut

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

my ($name, $for) = @ARGV;

if (!$name) {
    foreach my $id ($labase->search_objects($otype, 'oalias=*')) {
        my $isfor = '';
        if (my $obj = $labase->GetAlias($otype, $id)) {
            $isfor = $obj->get_attributes('oalias');
        }
        print "$id -> $isfor\n";
    }
    exit 0;
}

if ($remove) {
    if($labase->RemoveAlias($otype, $name)) {
        print "Alias $otype/$name removed\n";
        exit(0);
    } else {
        die "Error while remove alias $otype/$name";
    }
}

$for or do { pod2usage(1); };

if (my $obj = $labase->GetAlias($otype, $name)) {
    if ($obj->set_c_fields(oalias => $for)) {
        $labase->commit;
        print "Alias $name updated\n";
    } else {
        die "Alias $name unchanged\n";
    }
} else {
    if ($labase->CreateAlias($otype, $name, $for)) {
        $labase->commit;
        print "Alias $name created\n";
    } else {
        die "Alias $name not created\n";
    }
}

