#! /usr/bin/perl -T
# vim: set filetype=perl ts=4 sw=4 sts=4 et:
# NEEDGROUP osh-accountUnexpire
# SUDOERS %osh-accountUnexpire ALL=(%bastion-users) NOPASSWD:/usr/bin/env perl -T /opt/bastion/bin/helper/osh-accountUnexpire *
# FILEMODE 0755
# FILEOWN 0 0

#>HEADER
use common::sense;
use Getopt::Long qw(:config no_auto_abbrev no_ignore_case);

use File::Basename;
use lib dirname(__FILE__) . '/../../lib/perl';
use OVH::Bastion;
use OVH::Bastion::Helper;

# Fetch command options
my $fnret;
my ($result, @optwarns);
my ($account);
eval {
    local $SIG{__WARN__} = sub { push @optwarns, shift };
    $result = GetOptions("account=s" => sub { $account //= $_[1] });
};
if ($@) { die $@ }

if (!$result) {
    local $" = ", ";
    HEXIT('ERR_BAD_OPTIONS', msg => "Error parsing options: @optwarns");
}

OVH::Bastion::Helper::check_spurious_args();

if (!$account) {
    HEXIT('ERR_MISSING_PARAMETER', msg => "Missing argument 'account'");
}

#<HEADER

#>RIGHTSCHECK
if ($self eq 'root') {
    osh_debug "Real root, skipping checks of permissions";
}
else {
    # need to perform another security check
    $fnret = OVH::Bastion::is_user_in_group(user => $self, group => "osh-accountUnexpire");
    if (!$fnret) {
        HEXIT('ERR_SECURITY_VIOLATION', msg => "You're not allowed to run this, dear $self");
    }
}

#<RIGHTSCHECK

#>PARAMS:ACCOUNT
osh_debug("Checking account");
$fnret = OVH::Bastion::is_bastion_account_valid_and_existing(account => $account);
$fnret or HEXIT($fnret);
$account = $fnret->value->{'account'};    # untainted
my $sysaccount    = $fnret->value->{'sysaccount'};
my $remoteaccount = $fnret->value->{'remoteaccount'};
my $accounthome   = $fnret->value->{'dir'};

#<PARAMS:ACCOUNT

# for this special helper, $sysaccount must be equal to $ENV{'USER'}
if (OVH::Bastion::get_user_from_env()->value ne $sysaccount) {
    HEXIT('ERR_SECURITY_VIOLATION', msg => "You're not allowed to run this on $account, dear $self");
}

if (!-d $accounthome) {
    HEXIT('ERR_INVALID_HOME', msg => "Invalid HOME directory for this account");
}

$fnret = OVH::Bastion::is_account_nonexpired(
    sysaccount       => $sysaccount,
    remoteaccount    => $remoteaccount,
    update_lastlog   => 1,
    no_create_remote => 1,
);
$fnret->is_err and HEXIT($fnret);    # couldn't read file or other error
$fnret->is_ok  and HEXIT($fnret);    # wasn't expired (lastlog already refreshed inside is_account_nonexpired)

my $days = $fnret->value->{'days'};

# is_ko: is expired, so we reset expiration on both the realm support user and the remote user specific file
my @filesToTouch = ("/home/$sysaccount/lastlog");
if ($remoteaccount) {
    my $remoteFile = "/home/$sysaccount/lastlog_$remoteaccount";
    push @filesToTouch, $remoteFile if -e $remoteFile;
}
foreach my $file (@filesToTouch) {
    $fnret = OVH::Bastion::touch_file($file);
    osh_warn("Couldn't touch $file: " . $fnret->msg) if !$fnret;
}

HEXIT('OK', value => {account => $account, days => $days});
