<?php
/**
 * encrypt_secret.php - produce and verify MsaCrypt-encrypted env values. CLI only.
 *
 *   --genkey [--env=dev|prod]      generate a master key (once per environment)
 *   --encrypt --name=VAR           prompt for a secret, print deployment lines
 *   --decrypt                      prompt for a payload, print the plaintext
 *   --check [--scope=PREFIX]       verify this host's env decrypts
 *           [--envfile=PATH]      ...loading a key file first, for cron hosts
 */

require_once dirname(dirname(__FILE__)) . '/lib/php/include/MsaCrypt.php';

if (PHP_SAPI !== 'cli') {
    header('HTTP/1.1 403 Forbidden');
    exit("This script is CLI-only.\n");
}

$opts = parseArgs($argv);

if (isset($opts['help']) || count($opts) === 0) {
    usage();
    exit(0);
}

/* ------------------------------------------------------------------ */
/* --genkey                                                            */
/* ------------------------------------------------------------------ */
if (isset($opts['genkey'])) {
    $key = MsaCrypt::generateMasterKey();
    $env = isset($opts['env']) && $opts['env'] !== true ? $opts['env'] : 'ENVIRONMENT';

    echo "\n";
    echo "Master key for: " . $env . "\n";
    echo str_repeat('=', 64) . "\n";
    echo $key . "\n";
    echo str_repeat('=', 64) . "\n\n";
    echo "This decrypts every enc:v1: value in " . $env . ". Generate a DIFFERENT one\n";
    echo "for each environment, so a prod payload cannot be decrypted on dev.\n\n";
    emitDelivery(MsaCrypt::ENV_MASTER_KEY_NAME, $key, true);
    exit(0);
}

/* ------------------------------------------------------------------ */
/* --encrypt                                                           */
/* ------------------------------------------------------------------ */
if (isset($opts['encrypt'])) {
    $master = resolveMaster($opts);
    $name   = isset($opts['name']) && $opts['name'] !== true ? $opts['name'] : 'SECRET';

    if (isset($opts['value'])) {
        fwrite(STDERR, "WARNING: --value puts the secret in your shell history and in `ps`.\n");
        fwrite(STDERR, "         Prefer omitting it so the secret is read from stdin.\n\n");
        $plain = $opts['value'];
    } else {
        $plain = prompt('Secret to encrypt (input hidden): ', true);
    }

    if ($plain === '' || $plain === true) {
        fwrite(STDERR, "ERROR: empty secret\n");
        exit(1);
    }

    $payload = MsaCrypt::encrypt($plain, $master);

    if (MsaCrypt::decrypt($payload, $master) !== $plain) {
        fwrite(STDERR, "ERROR: round-trip verification failed - do not use this output\n");
        exit(1);
    }

    echo "\nround-trip verified. fingerprint " . fingerprint($plain)
       . " (compare across hosts without revealing the secret)\n\n";
    emitDelivery($name, $payload, false);
    exit(0);
}

/* ------------------------------------------------------------------ */
/* --decrypt                                                           */
/* ------------------------------------------------------------------ */
if (isset($opts['decrypt'])) {
    $master  = resolveMaster($opts);
    $payload = isset($opts['value']) && $opts['value'] !== true
        ? $opts['value']
        : prompt('enc:v1: payload: ', false);

    try {
        echo MsaCrypt::decrypt(trim($payload), $master) . "\n";
    } catch (Exception $e) {
        fwrite(STDERR, 'ERROR: ' . $e->getMessage() . "\n");
        exit(1);
    }
    exit(0);
}

/* ------------------------------------------------------------------ */
/* --check : verify THIS host's environment, without printing secrets  */
/* ------------------------------------------------------------------ */
if (isset($opts['check'])) {
    // --scope expands to _ACCESS_KEY, _SECRET_KEY and _REGION. Comma-separate for several.
    $names = array();
    $plainOnly = array();
    if (isset($opts['scope']) && $opts['scope'] !== true) {
        foreach (explode(',', $opts['scope']) as $scope) {
            $scope = trim($scope);
            if ($scope === '') { continue; }
            $names[] = $scope . '_ACCESS_KEY';
            $names[] = $scope . '_SECRET_KEY';
            $plainOnly[] = $scope . '_REGION';
        }
    } else {
        $names = array(
            isset($opts['name']) && $opts['name'] !== true ? $opts['name'] : 'S3_BUCKET_SECRET_KEY'
        );
    }
    $rc = 0;

    // Cron hosts read their values from a key file, not the real environment.
    if (isset($opts['envfile']) && $opts['envfile'] !== true) {
        $loaded = MsaCrypt::loadEnvFile($opts['envfile']);
        echo "\nenvfile: " . $opts['envfile'] . ($loaded ? " (loaded)" : " (NOT readable)");
        if (!$loaded) { $rc = 1; }
    }

    if (isset($opts['reveal'])) {
        echo "\n*** --reveal: plaintext secrets WILL be printed. Do not redirect this to a file. ***\n";
    }

    echo "\nhost   : " . php_uname('n') . "\n";
    echo "php    : " . PHP_VERSION . " (" . PHP_SAPI . ")\n";
    echo "NOTE   : this is the CLI environment. Under php-fpm, clear_env defaults to\n";
    echo "         yes, so a value visible here is NOT necessarily visible to a web\n";
    echo "         request. Verify that separately via the fpm pool.\n\n";

    $masterRaw = MsaCrypt::env(MsaCrypt::ENV_MASTER_KEY_NAME);
    if ($masterRaw === null) {
        echo "  [FAIL] " . MsaCrypt::ENV_MASTER_KEY_NAME . " is not set in this environment\n";
        $rc = 1;
    } else {
        try {
            MsaCrypt::masterKey();
            echo "  [ ok ] " . MsaCrypt::ENV_MASTER_KEY_NAME . " present and well-formed"
               . " (fingerprint " . fingerprint($masterRaw) . ")\n";
        } catch (Exception $e) {
            echo "  [FAIL] " . $e->getMessage() . "\n";
            $rc = 1;
        }
    }

    foreach ($names as $name) {
        $val = MsaCrypt::env($name);
        if ($val === null) {
            echo "  [FAIL] " . $name . " is not set in this environment\n";
            $rc = 1;
        } elseif (strpos($val, MsaCrypt::PREFIX) !== 0) {
            if (isset($opts['strict'])) {
                echo "  [FAIL] " . $name . " is set but PLAINTEXT (not " . MsaCrypt::PREFIX . ")\n";
                $rc = 1;
            } else {
                echo "  [warn] " . $name . " is set but PLAINTEXT (not " . MsaCrypt::PREFIX . ")"
                   . " - re-run with --strict to treat this as a failure\n";
            }
        } else {
            try {
                $pt = MsaCrypt::secret($name, true);
                echo "  [ ok ] " . $name . " decrypts, length " . strlen($pt)
                   . ", fingerprint " . fingerprint($pt)
                   . (isset($opts['reveal']) ? "\n         value = " . $pt : "") . "\n";
            } catch (Exception $e) {
                echo "  [FAIL] " . $name . ": " . $e->getMessage() . "\n";
                $rc = 1;
            }
        }
    }

    foreach ($plainOnly as $name) {
        $val = MsaCrypt::env($name);
        if ($val === null) {
            echo "  [FAIL] " . $name . " is not set (needed for SigV4 signing)\n";
            $rc = 1;
        } else {
            echo "  [ ok ] " . $name . " = " . $val . " (not a secret)\n";
        }
    }

    echo "\n" . ($rc === 0 ? "OK\n\n" : "FAILED\n\n");
    exit($rc);
}

usage();
exit(1);

/* ================================================================== */

/** Print the value in each delivery form. */
function emitDelivery($name, $value, $isMaster)
{
    echo "php-fpm pool conf  (REQUIRED for web requests: clear_env defaults to yes,\n";
    echo "                    so a shell export will not reach PHP under fpm)\n";
    echo "  env[" . $name . "] = " . $value . "\n\n";

    echo "crontab  (cron gives almost no environment, so it must be explicit)\n";
    echo "  " . $name . "=" . $value . "\n\n";

    echo "systemd EnvironmentFile  (pair with clear_env = no in the fpm pool)\n";
    echo "  " . $name . "=" . $value . "\n\n";

    echo "shell, for a one-off CLI run\n";
    echo "  export " . $name . "=" . escapeshellarg($value) . "\n\n";

    if ($isMaster) {
        echo "WHERE THIS MAY LIVE\n";
        echo "  Protected channel only: root-owned file (mode 0400) read via systemd\n";
        echo "  EnvironmentFile, or ansible-vault. Do NOT commit it, and do NOT put it\n";
        echo "  in the same file as the enc:v1: payloads - that cancels out the\n";
        echo "  encryption entirely.\n\n";
    } else {
        echo "WHERE THIS MAY LIVE\n";
        echo "  Anywhere the master key is not. The payload alone is useless, so an\n";
        echo "  ansible-managed pool conf or a crontab is acceptable.\n\n";
    }
}

/** Non-reversible tag for comparing values across hosts. */
function fingerprint($s)
{
    return substr(hash('sha256', $s), 0, 8);
}

function resolveMaster($opts)
{
    if (isset($opts['master']) && $opts['master'] !== true) {
        $raw = base64_decode($opts['master'], true);
        if ($raw === false || strlen($raw) !== MsaCrypt::MASTER_LEN) {
            fwrite(STDERR, "ERROR: --master must be base64 of " . MsaCrypt::MASTER_LEN . " bytes\n");
            exit(1);
        }
        return $raw;
    }
    try {
        return MsaCrypt::masterKey();
    } catch (Exception $e) {
        fwrite(STDERR, 'ERROR: ' . $e->getMessage() . "\n");
        fwrite(STDERR, "Hint: export " . MsaCrypt::ENV_MASTER_KEY_NAME
            . "=..., or pass --master=<base64>.\n");
        exit(1);
    }
}

function prompt($label, $hidden)
{
    fwrite(STDERR, $label);
    $restore = '';
    if ($hidden && DIRECTORY_SEPARATOR === '/' && is_executable('/bin/stty')) {
        $restore = trim((string) shell_exec('stty -g 2>/dev/null'));
        shell_exec('stty -echo 2>/dev/null');
    }
    $v = fgets(STDIN);
    if ($restore !== '') {
        shell_exec('stty ' . $restore . ' 2>/dev/null');
        fwrite(STDERR, "\n");
    }
    return $v === false ? '' : rtrim($v, "\r\n");
}

function parseArgs($argv)
{
    $out = array();
    for ($i = 1; $i < count($argv); $i++) {
        $a = $argv[$i];
        if (strpos($a, '--') !== 0) { continue; }
        $a = substr($a, 2);
        $eq = strpos($a, '=');
        if ($eq === false) { $out[$a] = true; }
        else { $out[substr($a, 0, $eq)] = substr($a, $eq + 1); }
    }
    return $out;
}

function usage()
{
    echo "\nencrypt_secret.php - MsaCrypt operator tool (CLI only)\n\n";
    echo "  --genkey [--env=dev|prod]     generate a master key, once per environment\n";
    echo "  --encrypt --name=VAR_NAME     prompt for a secret, print deployment lines\n";
    echo "  --decrypt                     prompt for a payload, print the plaintext\n";
    echo "  --check  [--name=VAR_NAME]    verify THIS host's env decrypts (no secret shown)\n";
    echo "           [--scope=A,B]        ...check whole sets: _ACCESS_KEY, _SECRET_KEY, _REGION each\n";
    echo "           [--strict]           ...and fail if any value is still plaintext\n";
    echo "           [--envfile=PATH]     ...load a key file first, for hosts with no env (cron)\n";
    echo "           [--reveal]           ...print the decrypted values (never redirect to a file)\n";
    echo "\n";
    echo "  --master=<base64>             master key, if not in this environment yet\n";
    echo "  --value=<text>                non-interactive input (leaks to shell history)\n";
    echo "\n";
    echo "Secrets are read from stdin by default so they stay out of `ps` and history.\n\n";
}
