#!/usr/bin/env bash
# onx-phpmyadmin-install — phpMyAdmin post-deploy kurulumu (RHEL + Debian).
#
# install.sh'in kurmadığı durumlarda elle tetiklenebilir. Idempotent:
# zaten kuruluysa sadece config'i kontrol eder.
#
# Input (stdin JSON):
#   force  bool  (optional) Yeniden install (paket varsa atla yerine reinstall)
#
# Output (stdout JSON):
#   {
#     "installed": true,
#     "version": "5.2.1",
#     "url": "http://<host>/phpmyadmin/",
#     "config_path": "/etc/phpMyAdmin/config.inc.php"
#   }
#
# Exit codes: 0=ok 2=preflight-fail 3=exec-fail

set -euo pipefail

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

INPUT=$(cat 2>/dev/null || echo '{}')
FORCE=$(onx_json_get_bool "${INPUT}" "force" "false" 2>/dev/null || echo "false")

require_root

# ── OS detect ──────────────────────────────────────────────────────────────
OS_FAMILY=""
if [[ -f /etc/redhat-release ]] || [[ -f /etc/rocky-release ]] || [[ -f /etc/almalinux-release ]]; then
    OS_FAMILY="rhel"
elif [[ -f /etc/debian_version ]]; then
    OS_FAMILY="debian"
else
    onx_die 2 "Desteklenmeyen OS — sadece RHEL/Rocky/Alma ve Debian/Ubuntu"
fi

onx_log "phpmyadmin-install: OS=${OS_FAMILY} force=${FORCE}"

# ── Kurulum ────────────────────────────────────────────────────────────────
INSTALLED=false
CONFIG_PATH=""
PMA_DIR=""

if [[ "${OS_FAMILY}" == "rhel" ]]; then
    PMA_DIR="/usr/share/phpMyAdmin"
    CONFIG_PATH="/etc/phpMyAdmin/config.inc.php"
    APACHE_CONF="/etc/httpd/conf.d/phpMyAdmin.conf"

    if rpm -q phpMyAdmin >/dev/null 2>&1 && [[ "${FORCE}" != "true" ]]; then
        onx_log "phpMyAdmin RPM zaten kurulu, sadece config check"
    else
        # EPEL etkin mi?
        if ! dnf repolist enabled 2>/dev/null | grep -qi epel; then
            dnf install -y epel-release >> /var/log/onoxsoft/install.log 2>&1 || \
                onx_die 3 "EPEL kurulamadı (phpMyAdmin EPEL'den gelir)"
        fi
        dnf install -y phpMyAdmin >> /var/log/onoxsoft/install.log 2>&1 || \
            onx_die 3 "phpMyAdmin install başarısız"
        INSTALLED=true
    fi

    # Apache config — erişimi aç (default 127.0.0.1)
    if [[ -f "${APACHE_CONF}" ]]; then
        sed -i 's|Require ip 127.0.0.1|Require all granted|g' "${APACHE_CONF}"
        sed -i 's|Require ip ::1|# Require ip ::1|g' "${APACHE_CONF}"
        systemctl reload httpd 2>/dev/null || true
    fi

elif [[ "${OS_FAMILY}" == "debian" ]]; then
    PMA_DIR="/usr/share/phpmyadmin"
    CONFIG_PATH="/etc/phpmyadmin/config.inc.php"

    if dpkg -l phpmyadmin 2>/dev/null | grep -q '^ii' && [[ "${FORCE}" != "true" ]]; then
        onx_log "phpmyadmin paketi zaten kurulu, sadece config check"
    else
        # Non-interactive
        export DEBIAN_FRONTEND=noninteractive
        echo "phpmyadmin phpmyadmin/dbconfig-install boolean false" | debconf-set-selections
        echo "phpmyadmin phpmyadmin/reconfigure-webserver multiselect" | debconf-set-selections
        apt-get update >> /var/log/onoxsoft/install.log 2>&1 || true
        apt-get install -y phpmyadmin >> /var/log/onoxsoft/install.log 2>&1 || \
            onx_die 3 "phpmyadmin install başarısız"
        INSTALLED=true
    fi

    # Apache conf etkinleştir
    if [[ -f /etc/apache2/conf-available/phpmyadmin.conf ]]; then
        a2enconf phpmyadmin 2>/dev/null || true
        systemctl reload apache2 2>/dev/null || true
    fi
fi

# ── blowfish_secret ────────────────────────────────────────────────────────
if [[ -f "${CONFIG_PATH}" ]] && grep -q "cfg\['blowfish_secret'\] = ''" "${CONFIG_PATH}" 2>/dev/null; then
    SECRET="$(openssl rand -base64 32 | tr -d '/\n=' | head -c 32)"
    sed -i "s|cfg\['blowfish_secret'\] = '';|cfg['blowfish_secret'] = '${SECRET}';|" "${CONFIG_PATH}"
    onx_log "blowfish_secret üretildi"
fi

# ── Version detect ─────────────────────────────────────────────────────────
VERSION="unknown"
if [[ -f "${PMA_DIR}/libraries/classes/Version.php" ]]; then
    VERSION=$(grep -oE "VERSION = '[0-9.]+'" "${PMA_DIR}/libraries/classes/Version.php" 2>/dev/null | head -1 | sed "s/VERSION = '//;s/'//" || echo "unknown")
elif [[ -f "${PMA_DIR}/RELEASE-DATE-"* ]]; then
    VERSION=$(ls "${PMA_DIR}"/RELEASE-DATE-* 2>/dev/null | head -1 | sed 's|.*RELEASE-DATE-||')
fi

# ── Output ─────────────────────────────────────────────────────────────────
HOSTNAME=$(hostname -f 2>/dev/null || hostname)
URL="http://${HOSTNAME}/phpmyadmin/"

jq -n \
    --argjson installed "${INSTALLED}" \
    --arg version "${VERSION}" \
    --arg url "${URL}" \
    --arg config_path "${CONFIG_PATH}" \
    '{installed: $installed, version: $version, url: $url, config_path: $config_path}'

onx_log "phpmyadmin-install: complete, version=${VERSION}"
