#! /usr/bin/env perl
# vim: set filetype=perl ts=4 sw=4 sts=4 et:
use common::sense;
use Term::ANSIColor qw{ colored };
use POSIX           qw{ strftime };

use File::Basename;
use lib dirname(__FILE__) . '/../../../lib/perl';
use OVH::Result;
use OVH::Bastion;
use OVH::Bastion::Plugin qw( :DEFAULT help );

my ($account);
OVH::Bastion::Plugin::begin(
    argv     => \@ARGV,
    header   => "unexpire an inactivity-expired account",
    options  => {"account=s" => \$account},
    helptext => <<'EOF',
Unexpire an inactivity-expired account

Usage: --osh SCRIPT_NAME --account ACCOUNT

  --account ACCOUNT  Account to work on

When the bastion is configured to expire accounts that haven't been seen in a while,
this command can be used to activate them back.
EOF
);

#
# code
#
my $fnret;

if (not $account) {
    help();
    osh_exit 'ERR_MISSING_PARAMETER', "Missing 'account' parameter";
}

# Here we parse account name
$fnret = OVH::Bastion::is_bastion_account_valid_and_existing(account => $account);
$fnret or osh_exit $fnret;
$account = $fnret->value->{'account'};

my @command = qw{ sudo -n -u };
push @command, ($account, '--');
push @command, qw{ /usr/bin/env perl -T };
push @command, $OVH::Bastion::BASEPATH . '/bin/helper/osh-accountUnexpire';
push @command, ('--account', $account);

$fnret = OVH::Bastion::helper(cmd => \@command);
$fnret or osh_exit $fnret;

if ($fnret->err eq 'OK') {
    my $days = $fnret->value->{'days'};
    osh_ok R(
        'OK',
        value => {account => $account, days => $days},
        msg   => "Account $account was expired ($days days without connection), it is now active again."
    );
}
elsif ($fnret->is_ok) {
    osh_ok R('OK_NO_CHANGE', msg => "Account $account wasn't expiring, no change was needed or made.");
}

osh_exit $fnret;
