#! /usr/bin/env perl
# vim: set filetype=perl ts=4 sw=4 sts=4 et:
use common::sense;
use Term::ANSIColor qw{ colored };
use POSIX           qw{ strftime };

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

my $remainingOptions = OVH::Bastion::Plugin::begin(
    argv    => \@ARGV,
    header  => "public bastion key of an account",
    options => {
        "account=s" => \my $account,
    },
    helptext => <<'EOF',
List the public egress keys of an account

Usage: --osh SCRIPT_NAME --account ACCOUNT

  --account ACCOUNT  Account to display the public egress keys of

The keys listed are the public egress SSH keys tied to this account.
They can be used to gain access to another machine from this bastion,
by putting one of those keys in the remote machine's ``authorized_keys`` file,
and adding this account access to this machine with ``accountAddPersonalAccess``.
EOF
);

my $fnret;

if (not $account) {
    help();
    osh_exit 'ERR_MISSING_PARAMETER', "Missing 'account' parameter";
}

$fnret = OVH::Bastion::is_bastion_account_valid_and_existing(account => $account);
$fnret or osh_exit $fnret;
$account = $fnret->value->{'account'};

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

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

my @command = qw{ sudo -n -u keyreader -- /usr/bin/env perl -T };
push @command, $OVH::Bastion::BASEPATH . '/bin/helper/osh-accountListEgressKeys';
push @command, ('--account', $account);

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

my $result_hash = {};
foreach my $keyfile (@{$fnret->value->{'sortedKeys'}}) {
    my $key = $fnret->value->{'keys'}{$keyfile};
    $key->{'prefix'} = $from;
    undef $key->{'filename'};
    undef $key->{'fullpath'};
    OVH::Bastion::print_public_key(key => $key);
    $result_hash->{$key->{'fingerprint'}} = $key;
}

osh_ok $result_hash;
