#!/usr/bin/env bash
# onx-fpm-reload — Reload one specific or all installed PHP-FPM versions.
#
# Input (stdin JSON):
#   php_version  string|null  Reload only this version (e.g. "8.2").
#                             Omit or set to "" to reload all detected versions.
#
# Output (stdout JSON):
#   {"reloaded":["8.1","8.2"], "failed":[], "skipped":[]}
#
# Exit codes: 0=ok 2=preflight-fail 3=exec-fail (at least one version failed)
#
# Deployed to: /usr/local/onoxsoft/bin/onx-fpm-reload

set -euo pipefail

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

# ── Read & parse stdin ───────────────────────────────────────────────────────
INPUT=$(cat)

SPECIFIC_VERSION=$(onx_json_get "${INPUT}" "php_version" "" 2>/dev/null || echo "")

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

# ── Determine which versions to reload ──────────────────────────────────────
if [[ -n "${SPECIFIC_VERSION}" ]]; then
  NODOT="${SPECIFIC_VERSION//./}"
  VERSIONS_TO_RELOAD=("${SPECIFIC_VERSION}")
else
  # Auto-detect installed PHP-FPM services from systemd
  VERSIONS_TO_RELOAD=()
  while IFS= read -r svc; do
    # Extract version from "php82-php-fpm.service" → "8.2"
    if [[ "${svc}" =~ php([0-9])([0-9])-php-fpm ]]; then
      MAJOR="${BASH_REMATCH[1]}"
      MINOR="${BASH_REMATCH[2]}"
      VERSIONS_TO_RELOAD+=("${MAJOR}.${MINOR}")
    fi
  done < <(systemctl list-units --type=service --all --no-legend 2>/dev/null | \
             grep -oE 'php[0-9]+-php-fpm\.service' | sort -u)
fi

if [[ "${#VERSIONS_TO_RELOAD[@]}" -eq 0 ]]; then
  onx_log "No PHP-FPM services found to reload"
  onx_json_out "reloaded" "[]" "failed" "[]" "skipped" "[]"
  exit 0
fi

# ── Reload each version ───────────────────────────────────────────────────────
RELOADED=()
FAILED=()
SKIPPED=()

for VER in "${VERSIONS_TO_RELOAD[@]}"; do
  NODOT="${VER//./}"
  SVC="php${NODOT}-php-fpm"

  if ! systemctl is-active "${SVC}" >/dev/null 2>&1; then
    onx_log "Skipping inactive service: ${SVC}"
    SKIPPED+=("${VER}")
    continue
  fi

  if systemctl reload "${SVC}" 2>/dev/null; then
    onx_log "Reloaded: ${SVC}"
    RELOADED+=("${VER}")
  else
    onx_log "WARNING: reload failed for ${SVC}"
    FAILED+=("${VER}")
  fi
done

# ── Build JSON arrays ────────────────────────────────────────────────────────
# Helper: convert bash array to JSON array string ["a","b"]
make_json_array() {
  local arr=("$@")
  if [[ "${#arr[@]}" -eq 0 ]]; then
    echo "[]"
    return
  fi
  local out='['
  for i in "${!arr[@]}"; do
    [[ "${i}" -gt 0 ]] && out+=','
    out+="\"${arr[${i}]}\""
  done
  out+=']'
  echo "${out}"
}

RELOADED_JSON=$(make_json_array "${RELOADED[@]+"${RELOADED[@]}"}")
FAILED_JSON=$(make_json_array "${FAILED[@]+"${FAILED[@]}"}")
SKIPPED_JSON=$(make_json_array "${SKIPPED[@]+"${SKIPPED[@]}"}")

[[ "${#FAILED[@]}" -gt 0 ]] && EXIT_CODE=3 || EXIT_CODE=0

# Emit JSON (custom — reloaded/failed/skipped are arrays not strings)
printf '{"reloaded":%s,"failed":%s,"skipped":%s}\n' \
  "${RELOADED_JSON}" "${FAILED_JSON}" "${SKIPPED_JSON}"

exit "${EXIT_CODE}"
