#!/usr/bin/env bash
# onx-php-uninstall — Remove a PHP version from the system.
#
# Önce vhost guard: o versiyonu kullanan vhost varsa reddeder.
# Sonra FPM unit stop+disable, sonra dnf/apt remove.
#
# Input (stdin JSON):
#   version  string   PHP majör.minör (örn "7.4")
#   force    bool?    true ise vhost guard'ı atlar (DANGEROUS — admin double-confirm)
#
# Output (stdout JSON):
#   {"uninstalled":true, "version":"7.4", "packages_removed":N, "vhosts_using":0}
#
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=exec-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-php-uninstall

set -euo pipefail

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

INPUT=$(cat)
onx_require_json "${INPUT}"

VERSION=$(onx_json_get "${INPUT}" "version")
FORCE=$(onx_json_get_bool "${INPUT}" "force" "false")

[[ -z "${VERSION}" ]] && onx_die 1 "version is required"
[[ "${VERSION}" =~ ^[78]\.[0-9]$ ]] || onx_die 1 "version must be x.y format, got: ${VERSION}"

VERSION_NODOT="${VERSION//./}"
FPM_UNIT="php${VERSION_NODOT}-php-fpm"

[[ $EUID -eq 0 ]] || onx_die 2 "must be run as root"

# ── vhost guard: kim kullanıyor? ─────────────────────────────────────────────
USING_COUNT=0
USING_LIST=()

if [[ -d /etc/httpd/conf.d/sites ]]; then
    while IFS= read -r -d '' vhost; do
        if grep -qE "php${VERSION_NODOT}-php-fpm|php-fpm/php${VERSION_NODOT}" "${vhost}" 2>/dev/null; then
            USING_LIST+=("$(basename "${vhost}")")
            USING_COUNT=$(( USING_COUNT + 1 ))
        fi
    done < <(find /etc/httpd/conf.d/sites -maxdepth 1 -name '*.conf' -type f -print0 2>/dev/null)
fi

if [[ ${USING_COUNT} -gt 0 && "${FORCE}" != "true" ]]; then
    USING_JSON=$(printf '%s\n' "${USING_LIST[@]}" | jq -Rsn '[inputs | select(length > 0)]')
    ERR=$(jq -n --arg version "${VERSION}" --argjson count "${USING_COUNT}" \
                --argjson vhosts "${USING_JSON}" \
        '{error: "in_use", version: $version, vhost_count: $count, vhosts: $vhosts,
          message: "PHP \($version) hâlâ \($count) vhost tarafından kullanılıyor. Önce başka versiyona geçir."}')
    printf '%s\n' "${ERR}" >&2
    exit 2
fi

# ── Stop + disable FPM ───────────────────────────────────────────────────────
onx_log "Stopping ${FPM_UNIT}"
systemctl stop "${FPM_UNIT}" 2>/dev/null || true
systemctl disable "${FPM_UNIT}" 2>/dev/null || true

# ── Package removal ──────────────────────────────────────────────────────────
PKG_COUNT=0

if command -v dnf >/dev/null 2>&1; then
    # Remi format: php83-* packages
    BEFORE=$(rpm -qa "php${VERSION_NODOT}*" 2>/dev/null | wc -l)
    onx_log "Removing php${VERSION_NODOT}* packages (count=${BEFORE})"
    dnf remove -y "php${VERSION_NODOT}*" 2>/dev/null || onx_die 3 "dnf remove failed"
    PKG_COUNT=${BEFORE}
elif command -v apt >/dev/null 2>&1; then
    BEFORE=$(dpkg -l "php${VERSION}*" 2>/dev/null | grep -c '^ii' || true)
    onx_log "Removing php${VERSION}* packages (count=${BEFORE})"
    apt remove --purge -y "php${VERSION}*" 2>/dev/null || onx_die 3 "apt remove failed"
    apt autoremove -y >/dev/null 2>&1 || true
    PKG_COUNT=${BEFORE}
else
    onx_die 2 "neither dnf nor apt available"
fi

# ── Cleanup pool dir if empty ────────────────────────────────────────────────
POOL_DIR="/etc/opt/remi/php${VERSION_NODOT}/php-fpm.d"
[[ -d "${POOL_DIR}" ]] && rmdir "${POOL_DIR}" 2>/dev/null || true

onx_json_out \
    "uninstalled"      "true" \
    "version"          "${VERSION}" \
    "packages_removed" "${PKG_COUNT}" \
    "vhosts_using"     "${USING_COUNT}" \
    "fpm_unit"         "${FPM_UNIT}"

onx_log "PHP ${VERSION} uninstalled (${PKG_COUNT} pkg removed)"
