#!/usr/bin/perl

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

=head1 NAME

    la-warn-expire - query expiration of user and send mail

=head1 SYNOPSIS

    la-warn-expire [options]

=cut

GetOptions(
    'c|config=s' => \my $config,
#    'b|base=s'   => \my $base,
    'm|mail'     => \my $mail,
    'help'       => sub { pod2usage(0) },
    'users|u=s'  => \my @users,
    'to=s'       => \my $to,
    'at=s'       => \my $delay,
    'test'       => \my $test,
) or pod2usage();

=head1 OPTIONS

=over 4

=item -c|--config configdir

Use this configuration directory instead of the default one.

=item -m|mail

Send a mail to user(s) concerned by the future expiration of his/her/their account(s).

=item -u|user USER

Send email only to this user if his/her account will expire. Usefull for
testing and not sending hundred of mails.

Multiple users can be specified by using -u several times

=item --to MAIL

Instead sending email to user(s) and eventually his/her/their manager(s), send the mail to
only this email address.

=item --at DELAY

Search account expiring in DELAY. Delay must must a number follow by a time
unit. Example:

    1 month
    2 days

=item --test

With -m, do not send mail but tell to who the mail would have been sent

=back

=head1 CONFIGURATION

Some variables are taken from configuration directory:

=over 4

=item mailFrom

Specify the From address to use in mail

=item smtp

The smtp server to use to send mail

=item alwayscc

In normal mode (without --to), the mail is also sent this email address.

=back

=head1 USERS EMAIL ADDRESSES

The mail use to send warning to users and manager is taken from 'mail'
attributes. If the attributes is unset, the user will not receive the mail.

=cut

if (!$test) {
    la_set_log(
        syslog => [],
        console => undef,
    );
}

my $LA = LATMOS::Accounts::Maintenance->new($config);

if ($mail) {
    $LA->warn_next_expire_users(
        to => $to,
        users => (@users ? \@users : undef),
        delay => $delay,
        test => $test,
    );
} else {
    foreach ($LA->find_next_expire_users($delay)) {
        printf("%4s jours: %s (%s)\n", $_->{days}, $_->{obj}->get_c_field('displayName'),
            $_->{obj}->id);
    }
}
