#! /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-groupAddServer --group %GROUP% *
# FILEMODE 0755
# FILEOWN 0 0

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

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, $user, $ip, $port, $action, $force, $forcePassword, $forceKey, $ttl, $comment);
eval {
    local $SIG{__WARN__} = sub { push @optwarns, shift };
    $result = GetOptions(
        "group=s"          => sub { $group         //= $_[1] },    # ignore subsequent --group on cmdline (anti-sudoers-override)
        "user=s"           => sub { $user          //= $_[1] },
        "ip=s"             => sub { $ip            //= $_[1] },
        "port=i"           => sub { $port          //= $_[1] },
        "action=s"         => sub { $action        //= $_[1] },
        "force"            => sub { $force         //= $_[1] },
        "force-password=s" => sub { $forcePassword //= $_[1] },
        "force-key=s"      => sub { $forceKey      //= $_[1] },
        "ttl=i"            => sub { $ttl           //= $_[1] },
        "comment=s"        => sub { $comment       //= $_[1] },

    );
};
if ($@) { die $@ }

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

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

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

if (not grep { $action eq $_ } qw{ add del }) {
    HEXIT('ERR_INVALID_PARAMETER', msg => "Argument action should be 'add' or 'del'");
}

#<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

# 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);

#>CODE
my $machine = OVH::Bastion::machine_display(ip => $ip, port => $port, user => $user)->value;

# access_modify validates all its parameters, don't do it ourselves here for clarity
$fnret = OVH::Bastion::access_modify(
    way           => 'group',
    action        => $action,
    group         => $group,
    ip            => $ip,
    user          => $user,
    port          => $port,
    forcePassword => $forcePassword,
    forceKey      => $forceKey,
    ttl           => $ttl,
    comment       => $comment,
);
if ($fnret->err eq 'OK') {
    my $ttlmsg = $ttl ? ' (expires in ' . OVH::Bastion::duration2human(seconds => $ttl)->value->{'human'} . ')' : '';
    HEXIT(
        'OK',
        value => {
            action        => $action,
            group         => $shortGroup,
            ip            => $ip,
            user          => $user,
            port          => $port,
            forcePassword => $forcePassword,
            forceKey      => $forceKey,
            ttl           => $ttl,
            comment       => $comment
        },
        msg => $action eq 'add'
        ? "Entry $machine was added to group $shortGroup$ttlmsg"
        : "Entry $machine was removed from group $shortGroup$ttlmsg"
    );
}
elsif ($fnret->err eq 'OK_NO_CHANGE') {
    HEXIT('OK_NO_CHANGE',
        msg => $action eq 'add'
        ? "Entry $machine was already added to group $shortGroup, nothing done"
        : "Entry $machine was not in group $shortGroup, nothing done");
}
HEXIT($fnret);
