#!/usr/bin/perl

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

=head1 NAME

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

=head1 SYNOPSIS

    la-sql-loadatt [options] csv_file

=cut

GetOptions(
    'c|config=s' => \my $config,
    'b|base=s'   => \my $base,
    '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.

=back

=cut

if (!$ARGV[0]) {
    warn "You must specify a file to load\n";
    pod2usage();
}

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

open my $fh, "<:encoding(utf8)", $ARGV[0] or die "$ARGV[0]: $!";

my $csv = Text::CSV_XS->new();

while (my $row = $csv->getline($fh)) {
    my ($otype, $attribute, $comment) = @$row;
    if ($labase->is_registered_attribute($otype, $attribute)) {
    } else {
        $labase->register_attribute($otype, $attribute, $comment)
            or die "Error, aborting\n";
        print "Attr. $attribute for object type $otype registred\n";
    }
}

$csv->eof or do {
    $csv->error_diag();
    die "Cannot load attribute\n"
};

$labase->commit;
print "Load terminated w/o error\n";
exit 0;
