#! /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 $sysaccount = $fnret->value->{'sysaccount'};

my @command = qw{ sudo -n -u };
push @command, ($sysaccount, '--');
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;

my $retvalue = {account => $account};
$retvalue->{'days'} = $fnret->value->{'days'} if ($fnret->value && defined $fnret->value->{'days'});

if ($fnret->err eq 'OK') {
    osh_ok R(
        'OK',
        value => $retvalue,
        msg   => "Account $account was expired ("
          . $retvalue->{'days'}
          . " days without connection), it is now active again."
    );
}
elsif ($fnret->err eq 'OK_EXPIRATION_NOT_CONFIGURED') {
    osh_ok R(
        $fnret->err,
        value => $fnret->value,
        msg   => "Account $account is not expired and expiration is not configured on this bastion, "
          . "but its last activity date has been refreshed nevertheless."
    );
}
elsif ($fnret->err eq 'OK_NOT_EXPIRED') {
    osh_ok R(
        $fnret->err,
        value => $fnret->value,
        msg   => "Account $account is not expired, but its last activity date has been refreshed nevertheless."
    );
}
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;
