#! /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 );
use OVH::Bastion::Plugin::generatePassword;

my $remainingOptions = OVH::Bastion::Plugin::begin(
    argv    => \@ARGV,
    header  => "generating a new egress password for your account",
    options => {
        "size=i" => \my $size,
        "do-it"  => \my $doIt,
    },
    helptext => <<'EOF'
Generate a new egress password for your account

Usage: --osh SCRIPT_NAME [--size SIZE] --do-it

  --size SIZE  Specify the number of characters of the password to generate
  --do-it      Required for the password to actually be generated, BEWARE: please read the note below

This plugin generates a new egress password to be used for ssh or telnet

NOTE: this is only needed for devices that don't support key-based SSH,
in most cases you should ignore this command completely, unless you
know that devices you need to access only support telnet or password-based SSH.

BEWARE: once a new password is generated this way, it'll be set as the new
egress password to use right away for your account, for any access that requires it.
A fallback mechanism exists that will auto-try the previous password if this one
doesn't work, but please ensure that this new password is deployed on the remote
devices as soon as possible.
EOF
);

# code
my $fnret;

$size = 16 if not defined $size;

$fnret = OVH::Bastion::Plugin::generatePassword::preconditions(
    self    => $self,
    context => 'account',
    account => $self,
    size    => $size
);
$fnret or osh_exit($fnret);

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

$fnret = OVH::Bastion::plugin_config(plugin => $scriptName, key => "minPasswordSize");
if ($fnret && $fnret->value && $size < $fnret->value) {
    osh_exit('ERR_INVALID_PARAMETER',
            "The minimum allowed password size defined by policy is "
          . $fnret->value
          . " characters, you asked only $size");
}

if (not $doIt) {
    help();
    osh_exit('ERR_MISSING_PARAMETER', "Missing mandatory parameter: please read the BEWARE note above.");
}

$fnret =
  OVH::Bastion::Plugin::generatePassword::act(self => $self, context => 'account', account => $self, size => $size);
$fnret or osh_exit($fnret);

osh_info "Generated a new password of length $size for your account, $self, hashes follow:\n\n";
my $hashes = $fnret->value->{'hashes'};
foreach my $type (qw{ md5crypt sha256crypt sha512crypt type8 type9 }) {
    osh_info(sprintf("%11s: %s\n", $type, $hashes->{$type})) if $hashes->{$type};
}
osh_info "\nThis new password will now be used by default.";
osh_exit $fnret;
