#!/usr/bin/env node

// Usage: node tools/gen_enc_pass.js
// Run the above command from your Reactor home directory, not from inside the tools directory.

// Version 24111

const fs = require("fs");
const path = require("path");

let mode = 5;
let argv = process.argv.slice( 2 );
if ( "-6" === argv.shift() ) {
    mode = 6;
}

if ( ! fs.existsSync( path.resolve( __dirname, "../server/lib/util.js" ) ) ) {
    console.log("Please run this script from the Reactor home directory (the level above tools).");
    console.log("Example: node tools/gen_enc_pass.js");
    process.exit(1);
}

const util = require("../server/lib/util.js");

const stdin = process.openStdin();

process.stdout.write("Enter password: ");

stdin.addListener("data", d => {
    const { randomBytes } = require("crypto");
    const salt = randomBytes( 16 ).toString( 'base64' ).substring( 0, 16 ); // 12 random would be enough, but JIC
    d = d.toString('UTF-8').replace(/([\r\n]+)/gm, "" );
    console.log( "Hashing", d.length, "byte password using", mode===6?"SHA-512":"SHA-256", "with random salt." );
    console.log( "Copy the entire password hash below to the users.yaml entry for the intended user." );
    console.log( util.genPassword5(d, salt, mode) );
    process.exit(0);
});
