#! /usr/bin/perl -T
# vim: set filetype=perl ts=4 sw=4 sts=4 et:
# KEYSUDOERS # as an owner, we can modify the group settings
# KEYSUDOERS SUPEROWNERS, %%GROUP%-owner      ALL=(%GROUP%)     NOPASSWD: /usr/bin/env perl -T %BASEPATH%/bin/helper/osh-groupModify --group %GROUP% *
# 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;
use OVH::Result;

# Fetch command options
my $fnret;
my ($result, @optwarns);
my ($group, $mfaRequired, $ttl, $idleLockTimeout, $idleKillTimeout);
eval {
    local $SIG{__WARN__} = sub { push @optwarns, shift };
    $result = GetOptions(
        "group=s"             => sub { $group //= $_[1] },
        "mfa-required=s"      => \$mfaRequired,
        "guest-ttl-limit=i"   => \$ttl,
        "idle-lock-timeout=i" => \$idleLockTimeout,
        "idle-kill-timeout=i" => \$idleKillTimeout,
    );
};
if ($@) { die $@ }

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

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

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

if (!$mfaRequired && !defined $ttl && !defined $idleLockTimeout && !defined $idleKillTimeout) {
    HEXIT('ERR_MISSING_PARAMETER',
        msg => "Missing argument 'mfa-required', 'guest-ttl-limit', 'idle-lock-timeout' or 'idle-kill-timeout'");
}

#<HEADER

#>PARAMS:GROUP
$fnret = OVH::Bastion::is_valid_group_and_existing(group => $group, groupType => "key");
$fnret or HEXIT($fnret);

# get returned untainted value
$group = $fnret->value->{'group'};
my $shortGroup = $fnret->value->{'shortGroup'};

#<PARAMS:GROUP

#>RIGHTSCHECK
if ($self eq 'root') {
    osh_debug "Real root, skipping checks of permissions";
}
$fnret = OVH::Bastion::is_group_owner(account => $self, group => $shortGroup, superowner => 1, sudo => 1);
if (!$fnret) {
    HEXIT('ERR_SECURITY_VIOLATION', msg => "You're not allowed to run this, dear $self");
}

#<RIGHTSCHECK

#>CODE
my %result;

if (defined $mfaRequired) {
    osh_info "Modifying mfa-required policy of group...";
    if (grep { $mfaRequired eq $_ } qw{ password totp any none }) {
        $fnret = OVH::Bastion::group_config(group => $group, key => "mfa_required", value => $mfaRequired);
        if ($fnret) {
            osh_info "... done, policy is now: $mfaRequired";
        }
        else {
            osh_warn "... error while changing mfa-required policy (" . $fnret->msg . ")";
        }
        $result{'mfa_required'} = $fnret;
    }
    else {
        osh_warn "... invalid option '$mfaRequired'";
        $result{'mfa_required'} = R('ERR_INVALID_PARAMETER');
    }
}

my %idleTimeout = (
    lock => {
        name  => "idle lock timeout",
        key   => \%{OVH::Bastion::OPT_GROUP_IDLE_LOCK_TIMEOUT()},
        value => $idleLockTimeout,
    },
    kill => {
        name  => "idle kill timeout",
        key   => \%{OVH::Bastion::OPT_GROUP_IDLE_KILL_TIMEOUT()},
        value => $idleKillTimeout,
    },
);

foreach my $item (keys %idleTimeout) {
    next if !defined $idleTimeout{$item}{'value'};

    osh_info "Modifying " . $idleTimeout{$item}{'name'} . " policy of group...";
    if ($idleTimeout{$item}{'value'} >= 0) {
        $fnret = OVH::Bastion::group_config(
            group => $group,
            %{$idleTimeout{$item}{'key'}}, value => $idleTimeout{$item}{'value'}
        );
        if ($fnret) {
            if ($idleTimeout{$item}{'value'} == 0) {
                osh_info "... done, this group's " . $idleTimeout{$item}{'name'} . " policy is now set to: disabled";
            }
            else {
                osh_info "... done, this group is now configured to use a "
                  . $idleTimeout{$item}{'name'}
                  . " policy of "
                  . OVH::Bastion::duration2human(seconds => $idleTimeout{$item}{'value'})->value->{'human'};
            }
        }
        else {
            osh_warn "... error while setting the group-specific "
              . $idleTimeout{$item}{'name'}
              . " policy ("
              . $fnret->msg . ")";
            warn_syslog "Error setting the group-specific "
              . $idleTimeout{$item}{'name'}
              . " policy of $group ("
              . $fnret->msg . ")";
        }
    }
    else {
        $fnret = OVH::Bastion::group_config(group => $group, %{$idleTimeout{$item}{'key'}}, delete => 1);
        if ($fnret) {
            osh_info "... done, this group will now use the global " . $idleTimeout{$item}{'name'} . " policy";
        }
        else {
            osh_warn "... error while removing the group-specific "
              . $idleTimeout{$item}{'name'}
              . " policy ("
              . $fnret->msg . ")";
            warn_syslog "Error removing the group-specific "
              . $idleTimeout{$item}{'name'}
              . " policy of $group ("
              . $fnret->msg . ")";
        }
    }
    $result{$idleTimeout{$item}{'key'}} = $fnret;
}

if (defined $ttl) {
    osh_info "Modifying guest TTL limit policy of group...";
    if ($ttl > 0) {
        $fnret = OVH::Bastion::group_config(group => $group, key => "guest_ttl_limit", value => $ttl);
        if ($fnret) {
            osh_info "... done, guest accesses must now have a TTL set on creation, with maximum allowed duration of "
              . OVH::Bastion::duration2human(seconds => $ttl)->value->{'human'};
        }
        else {
            osh_warn "... error while setting guest-ttl-limit (" . $fnret->msg . ")";
        }
    }
    else {
        $fnret = OVH::Bastion::group_config(group => $group, key => "guest_ttl_limit", delete => 1);
        if ($fnret) {
            osh_info "... done, guest accesses no longer need to have a TTL set";
        }
        else {
            osh_warn "... error while removing guest-ttl-limit (" . $fnret->msg . ")";
        }
    }
    $result{'guest_ttl_limit'} = $fnret;
}

HEXIT('OK', value => \%result);
