<?php
/*
 * Accepts the password from LSWS_ADMIN_PASS (preferred) or argv[1] (legacy).
 *
 * The env var is preferred because argv is world-readable via
 * /proc/<pid>/cmdline for the lifetime of the process. Under normal Linux
 * procfs permissions, environ is not readable by unrelated users. argv remains
 * accepted so existing callers keep working.
 *
 * Fails closed when neither is supplied: hashing a null/empty password
 * silently produces a valid hash that authenticates an EMPTY password.
 *
 * PHP 5.6 compatible: this is run by admin_php5, which is PHP 5.6.40 on
 * current builds. No null coalescing, no scalar/return type declarations.
 */
$raw = getenv('LSWS_ADMIN_PASS');

if ($raw === false || $raw === '') {
    $raw = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : '';

    if ($raw !== '') {
        /* Do not write to stdout: the caller captures it as the hash.
         * error_log() works in both CLI and CGI SAPIs; STDERR is guaranteed
         * only for CLI, while this script may be run by admin_php5 in CGI
         * mode (-q). */
        error_log(
            "htpasswd.php: warning: password supplied via argv is visible in "
                . "the process list; pass LSWS_ADMIN_PASS instead."
        );
    }
}

if ($raw === '') {
    error_log("htpasswd.php: no password supplied");
    exit(1);
}

$encrypted = password_hash($raw, PASSWORD_BCRYPT);

if ($encrypted === false) {
    error_log("htpasswd.php: password hashing failed");
    exit(1);
}

echo "$encrypted\n";
