#! /usr/bin/perl -T
# vim: set filetype=perl ts=4 sw=4 sts=4 et:
# NEEDGROUP osh-accountUnlock
# SUDOERS %osh-accountUnlock ALL=(root) NOPASSWD:/usr/bin/env perl -T /opt/bastion/bin/helper/osh-accountUnlock *
# FILEMODE 0700
# 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::Result;
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-accountUnlock"
    );
    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

#<PARAMS:ACCOUNT

osh_info("Attempting to unlock account... system helper output will follow.");
osh_info("\n");

# we need a list because we want to try in that specific order
my @programs = qw{ faillock pam_tally2 pam_tally };
my %cmds     = (
    faillock   => [qw{ faillock --user },  $account],
    pam_tally2 => [qw{ pam_tally2 -u },    $account, '-r'],
    pam_tally  => [qw{ pam_tally --user }, $account, '--reset'],
);

my $found;
foreach my $program (@programs) {
    next if not $cmds{$program};
    next if not OVH::Bastion::is_in_path(binary => $cmds{$program}[0]);
    $found = $program;
    last;
}

if (!$found) {
    if (OVH::Bastion::is_linux()) {
        warn_syslog(
            "Couldn't unlock account $account, as neither faillock, pam_tally2 or pam_tally seem to be installed");
        HEXIT('ERR_HELPER_MISSING', msg => "Found no unlock helper on this system. Please contact your sysadmin!");
    }
    else {
        HEXIT('ERR_UNSUPPORTED_FEATURE', msg => "Can't unlock account, your system might not support it");
    }
}

$fnret = OVH::Bastion::execute(cmd => $cmds{$found}, must_succeed => 1, noisy_stdout => 1, noisy_stderr => 1);
if (!$fnret) {
    my $error = '(empty)';
    if ($fnret->value->{'stderr'}) {
        $error = $fnret->value->{'stderr'}[0];
    }
    elsif ($fnret->value->{'stdout'}) {
        $error = $fnret->value->{'stdout'}[0];
    }
    warn_syslog("Got an error trying to unlock account $account through $found, first returned line was '$error'");
    HEXIT R('ERR_INTERNAL', msg => "Failed to unlock $account");
}

HEXIT('OK', value => {account => $account}, msg => "Account '$account' has been successfully unlocked.");
