#! /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   => "account egress passwords",
    options  => {"account=s" => \my $account},
    helptext => <<'EOF'
List the hashes and metadata of the egress passwords associated to an account

Usage: --osh SCRIPT_NAME --account ACCOUNT

  --account ACCOUNT  The account name to work on

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

# code
my $fnret;

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

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

$fnret = OVH::Bastion::helper(cmd => \@command);
$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 account doesn't have any egress password configured";
}

osh_ok($fnret);
