#!/usr/bin/env bash
# cmdmail — Hardened command receiver with strict whitelist
set -euo pipefail
shopt -s inherit_errexit 2>/dev/null || true

SDIR="$(cd "$(dirname "$0")" && pwd)"
source "${SDIR}/se_client.sh"

# ── Configuration ──────────────────────────────────────────────────────────
readonly ALLOWED_CMDS=(status restart reload ping update sync backup cleanup)
readonly INTERVAL=10

# ── Fetch command queue ────────────────────────────────────────────────────
TS="$(date -u +%s)"
NONCE="$(openssl rand -hex 16)"
readonly PAYLOAD="GET/a/cmd/queue/${NODE_ID}"
SIG="$(printf '%s' "${TS}:${NONCE}:${PAYLOAD}" | openssl dgst -sha256 -hmac "${VAULT_KEY}" | awk '{print $2}')"

RESP="$(curl -sS --connect-timeout 5 -m 15 \
    "${ENGINE_URL}/a/cmd/queue/${NODE_ID}" \
    -H "x-engine-ts: ${TS}" \
    -H "x-engine-nonce: ${NONCE}" \
    -H "x-engine-sig: ${SIG}" \
    -H "x-engine-node: ${NODE_ID}" \
    2>/dev/null || printf '%s' '')"

if [[ -z "${RESP}" ]]; then
    exit 0
fi

CMD="$(printf '%s' "${RESP}" | jq -r '.command // empty' 2>/dev/null || printf '%s' '')"
if [[ -z "${CMD}" ]]; then
    exit 0
fi

se_log "info" "cmd_recv: received=${CMD}"

# ── Whitelist check — exact match ──────────────────────────────────────────
CMD_BASE="${CMD%% *}"
readonly CMD_BASE
found=0
for allowed in "${ALLOWED_CMDS[@]}"; do
    if [[ "${CMD_BASE}" == "${allowed}" ]]; then
        found=1
        break
    fi
done

if [[ "${found}" -eq 1 ]]; then
    printf '%s\n' "${CMD}"
else
    se_log "warning" "cmd_recv: rejected=${CMD} not in whitelist"
    exit 1
fi
