#!/usr/bin/env bash
# onx-fpm-pool-remove — Remove a user's PHP-FPM pool config.
#
# Input (stdin JSON):
#   username     string  Linux username (onx_xxx)
#   php_version  string  "8.1", "8.2", "8.3", etc.
#
# Output (stdout JSON):
#   {"removed":true, "config_path":..., "socket_cleaned":...}
#
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=exec-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-fpm-pool-remove

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)

onx_require_json "${INPUT}"

USERNAME=$(onx_json_get "${INPUT}" "username")
PHP_VERSION=$(onx_json_get "${INPUT}" "php_version")

# ── Input validation ─────────────────────────────────────────────────────────
onx_validate_username "${USERNAME}"
[[ -z "${PHP_VERSION}" ]] && onx_die 1 "php_version is required"
[[ "${PHP_VERSION}" =~ ^[0-9]\.[0-9]$ ]] || onx_die 1 "php_version must be x.y format"

PHP_VERSION_NODOT="${PHP_VERSION//./}"
POOL_PATH="/etc/opt/remi/php${PHP_VERSION_NODOT}/php-fpm.d/${USERNAME}.conf"
SOCKET_PATH="/var/opt/remi/php${PHP_VERSION_NODOT}/run/php-fpm/${USERNAME}.sock"
FPM_SERVICE="php${PHP_VERSION_NODOT}-php-fpm"

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

if [[ ! -f "${POOL_PATH}" ]]; then
  # Idempotent: already gone is OK
  onx_log "Pool config already absent: ${POOL_PATH}"
  onx_json_out "removed" "true" "config_path" "${POOL_PATH}" "note" "already_absent"
  exit 0
fi

# ── Remove pool config ───────────────────────────────────────────────────────
rm -f "${POOL_PATH}"

# ── Reload FPM ───────────────────────────────────────────────────────────────
if systemctl is-active "${FPM_SERVICE}" >/dev/null 2>&1; then
  systemctl reload "${FPM_SERVICE}" 2>/dev/null || \
    systemctl restart "${FPM_SERVICE}" || \
    onx_log "WARNING: could not reload ${FPM_SERVICE} after pool removal"
fi

# ── Clean up leftover socket ─────────────────────────────────────────────────
SOCKET_CLEANED="false"
if [[ -S "${SOCKET_PATH}" ]]; then
  rm -f "${SOCKET_PATH}"
  SOCKET_CLEANED="true"
fi

# ── Success ──────────────────────────────────────────────────────────────────
onx_json_out \
  "removed"        "true" \
  "config_path"    "${POOL_PATH}" \
  "socket_cleaned" "${SOCKET_CLEANED}"
