#!/bin/env perl

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

=head1 NAME

    la-group -- add users to a group

=head1 SYNOPSIS

    la-group [options] [-s|-r] group user1 [user2 [...]]

=cut

GetOptions(
    'c|config=s'        => \my $config,
    'b|base=s'          => \my $base,
    's'                 => \my $set,
    'r'                 => \my $remove,
    'no-unexp|wo-unexp' => \my $nounexp,
    'with-unexp'        => \my $unexp,
    'help'              => sub { pod2usage(0) },
) or pod2usage();

$set && $remove and do {
    warn "-s and -r cannot be used together\n";
    pod2usage();
    exit 1;
};

my $otype = 'group';

=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 --with-unexp

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

=item --wo-unexp

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

=item -r

Remove the "group" in the user(s) list instead of adding (cannot be used with -s)

=item -s

Set the "group" to user(s) list instead of adding (cannot be used with -r)

=back

=cut

if (@ARGV < 2) {warn "You must specify 'group' and 'user1', aborting\n"; pod2usage(); }

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

$labase->unexported($nounexp ? 0 : 1);

$labase->is_supported_object($otype) or die "$otype object unsupported\n";
my ($objname, @users) = @ARGV;

if (my $obj = $labase->get_object($otype, $objname)) {
    # getting current value
    {
        my @missing = grep {
            !$labase->get_object('user', $_)
        } @users;
        if (@missing) {
            la_log(LA_ERR, "cannot find user(s) %s", join(', ', sort @missing));
            exit 1;
        }
    }
    my @current_users = $obj->get_attributes('member');
    my %uniq_users;
    if ($set) {
        foreach (@users) {
            $uniq_users{$_} = 1;
        }
    } else {
        foreach (@current_users) {
            $uniq_users{$_} = 1;
        }
        if ($remove) {
            foreach (@users) {
                delete $uniq_users{$_};
            }
        } else {
            foreach (@users) {
                $uniq_users{$_} = 1;
            }
        }
    }
    my @new_users = keys %uniq_users;
    la_log(LA_INFO, "member was:     %s", join(', ', sort @current_users));
    if ($obj->set_c_fields(member => [ @new_users ])) {
        la_log(LA_INFO, "member are now: %s", join(', ', sort @new_users));
        $labase->commit;
        exit 0;
    } else {
        la_log(LA_INFO, "No change done");
        exit 1;
    }
} else {
    la_log(LA_ERR, "Cannot find group %s", $objname);
    exit 1;
}

