#!/usr/bin/env bash
# onx-ols-test — OpenLiteSpeed config syntax test. lswsctl (lsws) -t
#
# Input (stdin JSON): {} (no fields required)
# Output: {"syntax_ok":bool, "output":..., "exit_code":...}
# Exit codes: 0=ok, 2=preflight (lsws not installed)

set -euo pipefail

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

LSWS_BIN="/usr/local/lsws/bin/lswsctrl"
[[ -x "$LSWS_BIN" ]] || onx_die 2 "lswsctrl not found at $LSWS_BIN (OpenLiteSpeed not installed?)"

# lswsctrl validate yapısı: -t veya configtest yok, doğrudan validate komutu yok.
# Pratik yaklaşım: httpd_config.conf'u syntax check için httpd binary'sini -t ile çağır:
#   /usr/local/lsws/bin/openlitespeed -t ?  (no — OLS bunu doğrudan desteklemez)
# Alternatif: lshttpd direct call ile fork edip dry-run yapılabilir. Şu an OLS reload
# kendi parser'ına sahip; reload sonrası error log'a bakılır.
# v75 itibariyle: lswsctrl restart önce config'i parse eder, hata varsa error log basar.
# Şimdilik temel kontrol — config dosyası var mı + syntax basic.

CONFIG_FILE="/usr/local/lsws/conf/httpd_config.conf"
if [[ ! -f "$CONFIG_FILE" ]]; then
    onx_json_out \
        "syntax_ok" "false" \
        "output"    "Config file not found: $CONFIG_FILE" \
        "exit_code" "1"
    exit 0
fi

# Basic syntax: matching braces
BRACE_OPEN=$(grep -c '{' "$CONFIG_FILE" 2>/dev/null || echo 0)
BRACE_CLOSE=$(grep -c '}' "$CONFIG_FILE" 2>/dev/null || echo 0)

if [[ "$BRACE_OPEN" != "$BRACE_CLOSE" ]]; then
    onx_json_out \
        "syntax_ok" "false" \
        "output"    "Brace mismatch: $BRACE_OPEN open vs $BRACE_CLOSE close in $CONFIG_FILE" \
        "exit_code" "1"
    exit 0
fi

# lswsctrl debug status (read-only, validates config availability)
TEST_OUTPUT=$("$LSWS_BIN" status 2>&1) && TEST_EC=0 || TEST_EC=$?
SYNTAX_OK="true"
[[ "${TEST_EC}" -ne 0 ]] && SYNTAX_OK="false"

onx_json_out \
  "syntax_ok" "${SYNTAX_OK}" \
  "output"    "Brace balance OK ($BRACE_OPEN/$BRACE_CLOSE). lswsctrl status: ${TEST_OUTPUT}" \
  "exit_code" "${TEST_EC}"
