#!/usr/bin/env bash
# onx-nginx-test — Run nginx -t (config syntax test) and return JSON result.
# Safe read-only operation; does not modify system state.
#
# Input (stdin JSON): {} (no fields required)
#
# Output (stdout JSON):
#   {"syntax_ok":true|false, "output":..., "exit_code":...}
#
# Exit codes: 0=ok (even when syntax fails — caller checks syntax_ok field)
#             2=preflight-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-nginx-test

set -euo pipefail

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=_lib/common.sh
source "${SCRIPT_DIR}/_lib/common.sh"

# ── Preflight ────────────────────────────────────────────────────────────────
command -v nginx >/dev/null 2>&1 || onx_die 2 "nginx not found"

# ── Run nginx -t (capture both stdout + stderr) ──────────────────────────────
# nginx -t writes "syntax is ok" + "test is successful" to stderr.
TEST_OUTPUT=$(nginx -t 2>&1) && TEST_EC=0 || TEST_EC=$?

SYNTAX_OK="false"
[[ "${TEST_EC}" -eq 0 ]] && SYNTAX_OK="true"

# ── Output ───────────────────────────────────────────────────────────────────
onx_json_out \
  "syntax_ok" "${SYNTAX_OK}" \
  "output"    "${TEST_OUTPUT}" \
  "exit_code" "${TEST_EC}"
