#! /usr/bin/env perl
# vim: set filetype=perl ts=4 sw=4 sts=4 et:
use common::sense;
use Term::ReadKey;

use File::Basename;
use lib dirname(__FILE__) . '/../../../lib/perl';
use OVH::Result;
use OVH::Bastion;
use OVH::Bastion::Plugin qw( :DEFAULT );
use OVH::Bastion::Plugin::generateEgressKey;

my $remainingOptions = OVH::Bastion::Plugin::begin(
    argv    => \@ARGV,
    header  => "generating a new key pair for a group",
    options => {
        "group=s"   => \my $group,
        "algo=s"    => \my $algo,
        "size=i"    => \my $size,
        "encrypted" => \my $encrypted,
    },
    help => \&help,
);

sub help {
    osh_info <<"EOF";
Create a new public + private key pair for a group

Usage: --osh $scriptName --group GROUP --algo ALGO --size SIZE [--encrypted]

  --group GROUP  Group name to generate a new egress key for.

  --algo ALGO    Specifies the algo of the key, either rsa, ecdsa or ed25519.

  --size SIZE    Specifies the size of the key to be generated.
                   For RSA, choose between 2048 and 8192 (4096 is good).
                   For ECDSA, choose either 256, 384 or 521.
                   For Ed25519, size is always 256.

  --encrypted    If specified, a passphrase will be prompted for the new key

EOF
    OVH::Bastion::print_accepted_key_algorithms(way => "egress", generate => 0);
    return 0;
}

#
# code
#
my $fnret;

$fnret = OVH::Bastion::Plugin::generateEgressKey::preconditions(
    context => 'group',
    self    => $self,
    group   => $group,
    algo    => $algo,
    size    => $size
);
if ($fnret->err eq 'ERR_MISSING_PARAMETER') {
    help();
    osh_exit(R('ERR_MISSING_PARAMETER', msg => "Missing the 'algo', 'size' or 'group' parameter'"));
}
$fnret or osh_exit $fnret;

my ($shortGroup, $keyhome);
($group, $algo, $size, $shortGroup, $keyhome) = @{$fnret->value}{qw{ group algo size shortGroup keyhome }};

my $passphrase = '';    # empty by default
if ($encrypted) {
    $fnret = OVH::Bastion::Plugin::generateEgressKey::ask_passphrase();
    $fnret or osh_exit $fnret;
    $passphrase = $fnret->value;
}

my @command = qw{ sudo -n -u root -- /usr/bin/env perl -T };
push @command, $OVH::Bastion::BASEPATH . '/bin/helper/osh-groupGenerateEgressKey';
push @command, '--group', $group;
push @command, '--algo',  $algo;
push @command, '--size',  $size;
push @command, '--encrypted' if $encrypted;

$fnret = OVH::Bastion::helper(cmd => \@command, stdin_str => $passphrase);
$fnret or osh_exit $fnret;

my $key = $fnret->value;

$fnret = OVH::Bastion::get_bastion_ips();
$fnret or osh_exit $fnret;

$key->{'prefix'} = 'from="' . join(',', @{$fnret->value}) . '"';

OVH::Bastion::print_public_key(key => $key);

osh_ok($key);
