#!/usr/bin/env bash
# onx-php-ext-install — Install a PHP extension for a specific PHP version.
#
# WHM "MultiPHP INI Editor → Extensions" muadili. dnf/apt'tan ekstra modülü
# yükler ve FPM'i reload eder.
#
# Input (stdin JSON):
#   version    string   PHP majör.minör (örn "8.3")
#   extension  string   "imagick" | "redis" | "memcached" | "mongodb" vb.
#
# Output (stdout JSON):
#   {"installed":true, "version":"8.3", "extension":"imagick",
#    "package":"php83-php-imagick", "runtime_active":true}
#
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=exec-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-php-ext-install

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")
EXT=$(onx_json_get "${INPUT}" "extension")

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

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

[[ $EUID -eq 0 ]] || onx_die 2 "must be run as root"
[[ -x "${BINARY}" ]] || onx_die 2 "PHP ${VERSION} not installed (binary missing: ${BINARY})"

# ── Install package ──────────────────────────────────────────────────────────
PKG_NAME=""
if command -v dnf >/dev/null 2>&1; then
    PKG_NAME="php${VERSION_NODOT}-php-${EXT}"
    onx_log "Installing ${PKG_NAME}"
    if ! dnf install -y "${PKG_NAME}" 2>/dev/null; then
        onx_die 3 "package not found or install failed: ${PKG_NAME}"
    fi
elif command -v apt >/dev/null 2>&1; then
    PKG_NAME="php${VERSION}-${EXT}"
    onx_log "Installing ${PKG_NAME}"
    if ! apt install -y "${PKG_NAME}" 2>/dev/null; then
        onx_die 3 "package not found or install failed: ${PKG_NAME}"
    fi
else
    onx_die 2 "neither dnf nor apt available"
fi

# ── Reload FPM ───────────────────────────────────────────────────────────────
systemctl reload "${FPM_UNIT}" 2>/dev/null \
    || systemctl restart "${FPM_UNIT}" 2>/dev/null \
    || onx_log "WARN: failed to reload ${FPM_UNIT}"

# ── Verify with php -m ───────────────────────────────────────────────────────
RUNTIME_ACTIVE="false"
if "${BINARY}" -m 2>/dev/null | grep -iqE "^${EXT}$"; then
    RUNTIME_ACTIVE="true"
fi

onx_json_out \
    "installed"      "true" \
    "version"        "${VERSION}" \
    "extension"      "${EXT}" \
    "package"        "${PKG_NAME}" \
    "runtime_active" "${RUNTIME_ACTIVE}" \
    "fpm_unit"       "${FPM_UNIT}"

onx_log "Extension ${EXT} installed for PHP ${VERSION} (active=${RUNTIME_ACTIVE})"
