#!/usr/bin/perl

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

=head1 NAME

    la-search - Perform object search in Latmos::Accounts base

=head1 SYNOPSIS

    la-search [options] filter [filter2 [...]]

=head1 OPTIONS

=over 4

=item --config configfile

Use this configuration file instead default

=item --base basename

Perform search in this specific base instead default

=item --fmt format

(Only if NO obj_id is given) Specify a format of output.

The "format" string may query tags in form:

    %{ATTRIBUTE:printflike}

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

Examples for users:

    --fmt "Name %{sn}, First Name %{givenName}\n"

    --fmt "Name %{sn:20s}, First Name %{givenName}\n"

=item FILTER

Filter are in form "[ATTRIBUTE][OPERATOR][VALUE]"

where attribute is a supported attribute.

OPERATOR can be:

=over 4

=item C<=>

Search object having attribute strictely equal to VALUE. If VALUE is C<*> match
any non empty value.

=item C<~>

Search object having attribute containing VALUE.

=back

=cut

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

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

$otype ||= 'user';

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

my @result = $labase->search_objects($otype, @ARGV);
foreach (@result) {
    if ($fmt) {
        my $o = $labase->queryformat($fmt);
    } else {
        print "$_\n";
    }
}

warn "\n" . scalar(@result) . " results\n";
exit(0);
