#!/usr/bin/perl

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

=head1 NAME

    la-query - Tools to query base in LATMOS::Accounts system

=head1 SYNOPSIS

    la-query [options] [obj_id]

=cut

GetOptions(
    'c|config=s' => \my $config,
    'b|base=s'   => \my $base,
    'o|object=s' => \my $otype,
    'e|empty'    => \my $empty_attr,
    'fmt=s'      => \my $fmt,
    'ro'         => \my $with_ro,
    'help'       => sub { pod2usage(0) },
) or pod2usage();

$otype ||= 'user';

=head1 OPTIONS

=over 4

=item -c|--config configfile

Use this cofngiuration file instead the default one

=item -b|--base basename

Query this specific base instead default.

=item -o|object object_type

Query should be performed on this objects. Default is to user 'User' object.

=item -e|--empty

Include also unset attributes

=item --ro

Include also read-only attributes as comment 

=item --fmt format

When listing all object, specify a format of output.

The string may query tag in form:

    %{ATTRIBUTE:printflike}

Where ATTRIBUTE is the name of an attribute and the optionnal
C<:printflike> is a printf like string to print the attributes content (without
the C<%>.

Examples for users:

    Name %{sn}, First Name {givenName}

    Name %{sn:20s}, First Name {givenName}

=back

=cut

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";

if (my $ouid = shift(@ARGV)) {
    my $obj = $labase->get_object($otype, $ouid) or do {
        die "Object $otype $ouid not found\n";
    };
    $obj->text_dump(*STDOUT,
        {
            empty_attr => $empty_attr,
            only_rw => !$with_ro,
        }
    );
} else {
    foreach (sort $labase->list_objects($otype)) {
        if ($fmt) {
            my $o = $labase->get_object($otype, $_) or next;
            print $o->queryformat($fmt);
        } else {
            print "$_\n";
        }
    }
}
