#! /usr/bin/perl -T
# vim: set filetype=perl ts=4 sw=4 sts=4 et:
# FILEMODE 0700
# FILEOWN 0 0

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

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 (not $account) {
    HEXIT('ERR_MISSING_PARAMETER', msg => "Missing argument 'account'");
}

#>RIGHTSCHECK
if ($self eq 'root') {
    osh_debug "Real root, skipping checks of permissions";
}
elsif ($self ne $account) {
    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

$fnret = OVH::Bastion::sys_addmembertogroup(user => $account, group => OVH::Bastion::MFA_TOTP_CONFIGURED_GROUP);
$fnret or HEXIT($fnret);

HEXIT('OK');
