#!/usr/bin/env bash
# onx-apache-restart — Full restart of httpd (not just reload).
# Use when modules are added/removed or major config changes.
# Prefer onx-apache-reload for routine config changes (no downtime).
#
# Input (stdin JSON): {} (no fields required)
#
# Output (stdout JSON):
#   {"restarted":true, "started_at":...}
#
# Exit codes: 0=ok 2=preflight-fail 3=exec-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-apache-restart

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"
command -v systemctl >/dev/null 2>&1 || onx_die 2 "systemctl not found"

# ── Safety: configtest before restart ───────────────────────────────────────
if ! apachectl configtest 2>/dev/null; then
  onx_die 2 "apachectl configtest failed; aborting restart to avoid downtime"
fi

# ── Restart ──────────────────────────────────────────────────────────────────
if ! systemctl restart httpd; then
  onx_die 3 "systemctl restart httpd failed"
fi

STARTED_AT=$(systemctl show httpd --property=ActiveEnterTimestamp --value 2>/dev/null || echo "unknown")

# ── Success ──────────────────────────────────────────────────────────────────
onx_json_out "restarted" "true" "started_at" "${STARTED_AT}"
