#! /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  => "generating a new ingress https password for your account",
    options => {
        "do-it" => \my $doIt,
    },
    helptext => <<'EOF'
Generate a new ingress password to use the bastion HTTPS proxy

Usage: --osh SCRIPT_NAME --do-it

  --do-it      Required for the password to actually be generated, BEWARE: please read the note below

This plugin generates a new ingress password to use the bastion HTTPS proxy.

NOTE: this is only needed for devices that only support HTTPS API and not ssh,
in most cases you should ignore this command completely, unless you
know that devices you need to access are using an HTTPS API.

BEWARE: once a new password is generated this way, it'll be set as the new
HTTPS proxy ingress password to use right away for your account.
EOF
);

# code
my $fnret;

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

# generate a password
my $pass     = '';
my $antiloop = 1000;
RETRY: while ($antiloop-- > 0) {
    $pass .= chr(int(rand(ord('~') - ord('!')) + ord('!'))) for (1 .. 32);
    if ($pass =~ m{["'\\`:@]}) {
        $pass = '';
        next;
    }
    last;
}
if ($antiloop <= 0) {
    osh_exit('ERR_CANNOT_GENERATE_PASSWORD', "Couldn't generate password, please try again");
}

# get the corresponding hashes
$fnret = OVH::Bastion::get_hashes_from_password(password => $self . ':' . $pass);
$fnret or osh_exit $fnret;

my $hash = $fnret->value->{'sha512crypt'};
osh_exit('ERR_NO_HASH', "Couldn't generate a valid hash") if !$hash;

# push the sha512crypt hash in the proper file
$fnret = OVH::Bastion::account_config(account => $self, key => "proxyhttphash", value => $hash);
$fnret or osh_exit $fnret;

osh_info "Generated a new ingress HTTPS proxy password for your account, $self, here it is:";
osh_info $pass;
osh_ok({password => $pass});
