#!/usr/bin/env bash
# onx-apache-test — Run apachectl configtest 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-apache-test

set -euo pipefail

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

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

# ── Run configtest (capture both stdout + stderr) ────────────────────────────
# apachectl configtest writes to stderr ("Syntax OK" or error messages)
TEST_OUTPUT=$(apachectl configtest 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}"
