#! /usr/bin/perl -T
# vim: set filetype=perl ts=4 sw=4 sts=4 et:
# NEEDGROUP osh-accountPIV
# SUDOERS # modify PIV policy of an account
# SUDOERS %osh-accountPIV ALL=(allowkeeper)    NOPASSWD:/usr/bin/env perl -T /opt/bastion/bin/helper/osh-accountPIV --step 1 --account *
# SUDOERS %osh-accountPIV ALL=(%bastion-users) NOPASSWD:/usr/bin/env perl -T /opt/bastion/bin/helper/osh-accountPIV --step 2 --account *
# 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 ($account, $policy, $ttl, $step);
eval {
    local $SIG{__WARN__} = sub { push @optwarns, shift };
    $result = GetOptions(
        "account=s" => sub { $account //= $_[1] },
        "policy=s"  => sub { $policy  //= $_[1] },
        "step=i"    => sub { $step    //= $_[1] },
        "ttl=i"     => sub { $ttl     //= $_[1] },
    );
};
if ($@) { die $@ }

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

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

if (!$account || !$policy || !$step) {
    HEXIT('ERR_MISSING_PARAMETER', msg => "Missing argument 'account' or 'modify' or 'step'");
}

#<HEADER

#>PARAMS:ACCOUNT
$fnret = OVH::Bastion::is_bastion_account_valid_and_existing(account => $account, localOnly => 1);
$fnret or HEXIT($fnret);

# get returned untainted value
$account = $fnret->value->{'account'};

#<PARAMS:ACCOUNT

#>PARAMS:POLICY
if (not grep { $policy eq $_ } qw{ default enforce grace never }) {
    HEXIT('ERR_INVALID_PARAMETER',
        "Expected either 'default,' enforce', 'grace' or 'never' as a parameter to --policy");
}

#<PARAMS:POLICY

#>PARAMS:TTL
if ($policy eq 'grace' && !defined $ttl) {
    HEXIT('ERR_MISSING_PARAMETER', "The use of 'grace' requires to specify the --ttl parameter as well");
}

#<PARAMS:TTL

#>PARAMS:STEP
if ($step ne '1' && $step ne '2') {
    HEXIT('ERR_INVALID_PARAMETER', "Only 1 or 2 are allowed for --step");
}

#<PARAMS:STEP

#>RIGHTSCHECK
if ($self eq 'root') {
    osh_debug "Real root, skipping checks of permissions";
}
$fnret = OVH::Bastion::is_user_in_group(user => $self, group => "osh-accountPIV");
if (!$fnret) {
    HEXIT('ERR_SECURITY_VIOLATION', msg => "You're not allowed to run this, dear $self");
}

if (OVH::Bastion::is_admin(account => $account, sudo => 1) && !OVH::Bastion::is_admin(account => $self, sudo => 1)) {
    HEXIT('ERR_SECURITY_VIOLATION', msg => "You can't modify the account of an admin without being admin yourself");
}

#<RIGHTSCHECK

#>CODE
$fnret =
  OVH::Bastion::account_config(account => $account, key => OVH::Bastion::OPT_ACCOUNT_INGRESS_PIV_POLICY, public => 1);

# no file means the policy is 'default' (we can also have a file with a written policy of 'default', it's the same)
my $currentPolicy = $fnret ? $fnret->value : 'default';

# 'yes' is an old synonym of 'enforce'
$currentPolicy = 'enforce' if $currentPolicy eq 'yes';

$fnret =
  OVH::Bastion::account_config(account => $account, key => OVH::Bastion::OPT_ACCOUNT_INGRESS_PIV_GRACE, public => 1);
my $currentGrace = $fnret ? $fnret->value : 0;

if ($step == 1) {

    # step1: we're run under allowkeeper user, set the account config

    if ($policy ne 'grace') {

        # is the policy we're asked to apply already the current one?
        if ($currentPolicy eq $policy) {
            HEXIT('OK_NO_CHANGE', msg => "PIV policy was already set to '$policy' for this account, no change needed");
        }

        # no, ok: apply the requested policy
        $fnret = OVH::Bastion::account_config(
            account => $account,
            key     => OVH::Bastion::OPT_ACCOUNT_INGRESS_PIV_POLICY,
            public  => 1,
            value   => $policy
        );
        if (!$fnret) {
            warn_syslog(
                "Couldn't apply the requested PIV policy '$policy' (current is '$currentPolicy'): " . $fnret->msg);
            HEXIT($fnret);
        }
        else {
            $fnret = OVH::Bastion::syslogFormatted(
                severity => 'info',
                type     => 'account',
                fields   => [
                    [action  => 'modify'],
                    [account => $account],
                    [item    => 'piv_policy'],
                    [old     => $currentPolicy],
                    [new     => $policy]
                ]
            );
        }

        # and delete any existing grace
        if ($currentGrace) {
            $fnret = OVH::Bastion::account_config(
                account => $account,
                key     => OVH::Bastion::OPT_ACCOUNT_INGRESS_PIV_GRACE,
                public  => 1,
                delete  => 1
            );
            if (!$fnret) {
                warn_syslog("Couldn't remove the grace TTL PIV policy: " . $fnret->msg);

                # attempt to continue nevertheless...
            }
            else {
                my $human = OVH::Bastion::duration2human(seconds => ($currentGrace - time()))->value;
                $fnret = OVH::Bastion::syslogFormatted(
                    severity => 'info',
                    type     => 'account',
                    fields   => [
                        [action  => 'modify'],
                        [account => $account],
                        [item    => 'piv_grace'],
                        [old     => 'true'],
                        [new     => 'false'],
                        [comment => "PIV grace up to " . $human->{'human'} . " has been removed"]
                    ]
                );
            }
        }
        HEXIT('OK', msg => "PIV policy set to '$policy' for this account");
    }
    else {
        # grace is not really a policy per se, it just sets a grace period for which the account will behave as it had the "never" policy set
        $fnret = OVH::Bastion::account_config(
            account => $account,
            key     => OVH::Bastion::OPT_ACCOUNT_INGRESS_PIV_GRACE,
            public  => 1,
            value   => (time() + $ttl)
        );
        if (!$fnret) {
            warn_syslog("Couldn't apply the requested grace ttl PIV policy: " . $fnret->msg);
            HEXIT($fnret);
        }
        my $human = OVH::Bastion::duration2human(seconds => $ttl)->value;
        $fnret = OVH::Bastion::syslogFormatted(
            severity => 'info',
            type     => 'account',
            fields   => [
                [action  => 'modify'],
                [account => $account],
                [item    => 'piv_grace'],
                [old     => 'false'],
                [new     => 'true'],
                [comment => "PIV grace up to " . $human->{'human'} . " has been set"]
            ]
        );
        HEXIT('OK', msg => "PIV grace up to " . $human->{'human'} . " has been set for this account");
    }
}
elsif ($step == 2) {

    # step2: now we're running under the own account's user, modify the authkeys file accordingly
    my $pivAction =
      (OVH::Bastion::is_effective_piv_account_policy_enabled(account => $account)->is_ok) ? 'enable' : 'disable';
    $fnret = OVH::Bastion::ssh_ingress_keys_piv_apply(action => $pivAction, account => $account);
    $fnret or HEXIT($fnret);

    if ($pivAction eq 'enable') {
        HEXIT('OK', msg => "All non-PIV account's ingress keys have been disabled");
    }
    else {
        HEXIT('OK', msg => "Non-PIV account's ingress keys, if any, have been restored");
    }
}

# unreachable
HEXIT('ERR_INTERNAL', msg => "Unknown step specified");
