#!/usr/bin/env bash
# onx-vhost-reload — Run apachectl configtest then reload httpd.
# Useful after manual vhost edits or bulk operations.
#
# Input (stdin JSON): {} (empty, no fields required)
#
# Output (stdout JSON):
#   {"reloaded":true, "uptime":..., "active_vhosts":...}
#
# Exit codes: 0=ok 2=preflight-fail 3=exec-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-vhost-reload

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"

# ── Configtest ───────────────────────────────────────────────────────────────
if ! apachectl configtest 2>/dev/null; then
  onx_die 3 "apachectl configtest failed; not reloading"
fi

# ── Reload ───────────────────────────────────────────────────────────────────
if ! systemctl reload httpd; then
  onx_die 3 "systemctl reload httpd failed"
fi

# ── Gather uptime ────────────────────────────────────────────────────────────
UPTIME=$(systemctl show httpd --property=ActiveEnterTimestamp --value 2>/dev/null || echo "unknown")

# Count active vhost configs
ACTIVE_VHOSTS=$(find /etc/httpd/conf.d/sites -name "*.conf" 2>/dev/null | wc -l | tr -d ' ')

# ── Success ──────────────────────────────────────────────────────────────────
onx_json_out \
  "reloaded"      "true" \
  "uptime"        "${UPTIME}" \
  "active_vhosts" "${ACTIVE_VHOSTS}"
