#!/usr/bin/perl

use strict;
use warnings;
use LATMOS::Accounts;
use Getopt::Long;
use Pod::Usage;
use POSIX qw(strftime);

=head1 NAME

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

=head1 SYNOPSIS

    la-query [options] [obj_id]

=item [obj_id] : If present, all set attributes (rw) will be displayed for that obj_id.
        If none is given, all obj_ids will be printed.

For the default object_type (user), obj_id = login.

Example : la-query lambda

=cut

GetOptions(
    'c|config=s' => \my $config,
    'b|base=s'   => \my $base,
    'noexp'      => \my $noexp,
    'exp'        => \my $exp,
    'noexpire'   => \my $noexpire,
    'filter=s'   => \my @filters,
    'help'       => sub { pod2usage(0) },
) or pod2usage();

=head1 OPTIONS

=over 4

=item -c|--config configfile

Use this configuration file instead of the default one.

=item -b|--base basename

Query this specific base instead of the default one.

=item --noexp

Take into account all objects (even non propagated ones, with attribute 'exported'=0)
(default)

=item --exp

Take into account only propagated objects (attribute 'exported'=1)

=item --noexpire

Exclude expired accounts

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

$labase->wexported($exp ? 1 : 0);
my %users;
my $now = strftime('%Y/%m/%d', gmtime);
my @depts = $labase->search_objects('group', 'sutype=dpmt');

foreach my $user (sort $labase->search_objects('user',
            @filters ? @filters : 'sn=*')) {
    my $ouser = $labase->get_object('user', $user);
    $ouser->get_attributes('sn') or next;
    if ($noexpire && (my $expdate = $ouser->get_attributes('expireText'))) {
        if ($now gt $expdate) {
            next;
        }
    }

# On ne prend que le personnel LATMOS et les heberges, sauf Novimet

    my $company = $ouser->get_attributes('company');
    my $contrat = $ouser->get_attributes('contratType');
    if ($company){
        if (($company ne "LATMOS")&&($contrat ne "heberges")) {
            next;
        }
        if ($company eq "Novimet") {
            next;
        }
    } else {
        if ((!$contrat)||($contrat ne "heberges")) {
            next;
        }
    }

    my @oaddress;

    if ($labase->is_supported_object('address')) {
        @oaddress = 
            grep { $_ } (
            map { $labase->get_object('address', $_) }
                $ouser->get_attributes('otheraddress'),
            );
    } else {
        @oaddress = ($ouser);
    }

    # Si c'est un heberge, on place departement a "EXT"

    my $department;

    if ($contrat eq "heberges") {
        $department = "EXT";
    } else {
        # On recherche les departements en plus de l'attribut "department"
        # en scrutant l'ensemble des groupes de l'utilisateur
        my @userdepts;
        foreach my $gr ($ouser->get_attributes('memberOf')) {
            grep { $_ eq $gr } (@depts) and push(@userdepts, $gr);
        } 
        $department = join(' ', @userdepts);
    }
            
    my $line = join(';', map { $_ || '' } (
            $ouser->get_attributes('sn'),
            $ouser->get_attributes('givenName'),
            $department,
            ($oaddress[0] ? join(' ', map { $_ || '' }
                    $oaddress[0]->get_attributes('l'), grep { $_ }
                    $oaddress[0]->get_attributes('physicalDeliveryOfficeName'),
                ) : ''),
            ($oaddress[1] ? join(' ', map { $_ || '' } grep { $_ }
                    $oaddress[1]->get_attributes('l'),
                    $oaddress[1]->get_attributes('physicalDeliveryOfficeName'),
                ) : ''),
            ($oaddress[0] ? $oaddress[0]->get_attributes('telephoneNumber') : ''),
            ($oaddress[1] ? $oaddress[1]->get_attributes('telephoneNumber') : ''),
            $ouser->get_attributes('mail'),
            $ouser->get_attributes('nickname'),
        ));
        $line =~s/Paris */PAR-/g;
        $line =~s/Guyancourt */GUY-/g;
        $line =~s/Vélizy-Villacoublay */VEL-/g;
        $line =~s/Verrières le Buisson */VLB-/g;
        $line =~s/St Maur des Fossés */STM-/g;
        $line =~s/\+ *33 *1 *//g;

    $users{$ouser->get_attributes('sn')}{$ouser->get_attributes('givenName')} = $line;
}

foreach my $sn (sort keys %users) {
    foreach my $givenName (sort keys %{$users{$sn}}) {
        print "$users{$sn}{$givenName}\n";
    }
}
