#! /usr/bin/perl -T
# vim: set filetype=perl ts=4 sw=4 sts=4 et:
# KEYSUDOERS # as an aclkeeper, we can add/del a server from the group server list in /home/%GROUP%/allowed.ip
# KEYSUDOERS SUPEROWNERS, %%GROUP%-aclkeeper  ALL=(%GROUP%)     NOPASSWD: /usr/bin/env perl -T %BASEPATH%/bin/helper/osh-groupSetServers --group %GROUP%
# FILEMODE 0755
# FILEOWN 0 0

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

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 $group;
eval {
    local $SIG{__WARN__} = sub { push @optwarns, shift };
    $result = GetOptions(
        "group=s" => sub { $group //= $_[1] },    # ignore subsequent --group on cmdline (anti-sudoers-override)
    );
};
if ($@) { die $@ }

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

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

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

#<HEADER

#>PARAMS:GROUP
osh_debug("Checking group $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'};
osh_debug("got group $group/$shortGroup");

#<PARAMS:GROUP

#>RIGHTSCHECK
if ($self eq 'root') {
    osh_debug "Real root, skipping checks of permissions";
}
else {
    $fnret = OVH::Bastion::is_group_aclkeeper(account => $self, group => $shortGroup, sudo => 1, superowner => 1);
    $fnret or HEXIT('ERR_NOT_ALLOWED', msg => "Sorry, you must be an aclkeeper of group $shortGroup");
}

#<RIGHTSCHECK

#>CODE

# the new ACL is built by the plugin and sent to our STDIN in pre-parsed JSON format
my $jsonData = <STDIN>;
my $data     = eval { decode_json($jsonData); };
if ($@) {
    HEXIT('ERR_INVALID_ARGUMENT', msg => "Invalid JSON data sent by the plugin, couldn't decode");
}

if (!$data || ref $data ne 'ARRAY') {
    HEXIT('ERR_INVALID_ARGUMENT', msg => "Invalid JSON import format sent by the plugin");
}

# take a lock here, to block other group ACL modifying commands for this group until we're done.
$fnret = OVH::Bastion::Helper::get_lock_fh(category => "groupacl", basepath => "/home/$group");
$fnret or HEXIT($fnret);
my $lock_fh = $fnret->value;
$fnret = OVH::Bastion::Helper::acquire_lock($lock_fh);
$fnret or HEXIT($fnret);

$fnret = OVH::Bastion::access_modify(
    way    => 'group',
    action => 'clear',
    group  => $group,
);
$fnret or HEXIT($fnret);

osh_info("Setting ACL entries, this may take a while...");

my @errors;
foreach my $entry (@$data) {
    $fnret = OVH::Bastion::access_modify(
        way     => 'group',
        action  => 'add',
        group   => $group,
        ip      => $entry->{ip},
        user    => $entry->{user},
        port    => $entry->{port},
        comment => $entry->{comment},
    );
    push @errors, $fnret if !$fnret;
}

if (!@errors) {
    HEXIT('OK', value => {ACL => $data, errors => []});
}
HEXIT('OK_WITH_ERRORS', value => {ACL => $data, errors => \@errors});
