#!/usr/bin/perl

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

=head1 NAME

    la-sql-attreg - Tools to register attributes in LA SQL base

=head1 SYNOPSIS

    la-sql-attreg [options] name comment

=cut

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

Set a comment to existing attribute instead adding the attribute

=back

=cut

if (!$ARGV[0]) {
    warn "You must specify attribute name, 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 ($comment) {
    if ($labase->set_attribute_comment($otype, @ARGV)) {
        $labase->commit;
        print "Attribute $ARGV[0] commented for object $otype\n";
        exit(0);
    } else {
        warn "Error commenting attribute $ARGV[0] for object $otype\n";
        exit(1);
    }
} else {
    if ($labase->register_attribute($otype, @ARGV)) {
        $labase->commit;
        print "Attribute $ARGV[0] register for object $otype\n";
        exit(0);
    } else {
        warn "Error registing attribute $ARGV[0] for object $otype\n";
        exit(1);
    }
}
