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

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  => "list the egress passwords of the group",
    options => {
        "group=s" => \my $group,
    },
    helptext => <<'EOF'
List the hashes and metadata of egress passwords of a group

Usage: --osh SCRIPT_NAME --group GROUP

  --group GROUP  Show the data for this group

The passwords corresponding to these hashes are only needed for devices that don't support key-based SSH
EOF
);

# code
my $fnret;

if (not $group) {
    help();
    osh_exit 'ERR_MISSING_PARAMETER', "Expected a --group argument";
}

$fnret = OVH::Bastion::is_valid_group_and_existing(group => $group, groupType => "key");
$fnret or osh_exit($fnret);

# get returned untainted value
$group = $fnret->value->{'group'};
my $shortGroup = $fnret->value->{'shortGroup'};

$fnret = OVH::Bastion::is_group_member(account => $self, group => $shortGroup, superowner => 1);
$fnret or osh_exit('ERR_NOT_ALLOWED', "Sorry, you must be a member of group $shortGroup");

$fnret = OVH::Bastion::get_hashes_list(context => 'group', group => $shortGroup);
$fnret or osh_exit $fnret;

foreach my $item (@{$fnret->value}) {
    osh_info $item->{'description'};
    foreach my $hash (sort keys %{$item->{'hashes'}}) {
        osh_info(sprintf("... %11s: %s\n", $hash, $item->{'hashes'}{$hash}));
    }
    osh_info "\n";
}
if (not @{$fnret->value}) {
    osh_info "This group doesn't have any egress password configured";
}

osh_ok($fnret);
