#!/usr/bin/env bash
# =============================================================================
# onx-apache-vhost-cert-link (v89) — Apache vhost SSL config patch
#
# Apache vhost dosyasındaki SSLCertificateFile + SSLCertificateKeyFile
# direktiflerini yeni cert path'iyle in-place günceller. Idempotent —
# zaten doğru cert gösteriyorsa no-op.
#
# Input (stdin JSON):
#   domain     string  Domain (ServerName matched in vhost file)
#   cert_path  string  Yeni fullchain.pem path
#   key_path   string  Yeni privkey.pem path
#
# Output (stdout JSON):
#   {"success":true, "vhost":"/etc/httpd/conf.d/...", "reloaded":true, "changed":true|false}
#
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=exec-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-apache-vhost-cert-link
# =============================================================================

set -euo pipefail

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

# ── Read stdin ───────────────────────────────────────────────────────────────
onx_json_input
DOMAIN=$(onx_json_field "domain")
CERT=$(onx_json_field "cert_path")
KEY=$(onx_json_field "key_path")

# ── Validation ───────────────────────────────────────────────────────────────
[[ -z "${DOMAIN}" ]] && onx_die 1 "domain required"
onx_validate_domain "${DOMAIN}"
[[ -f "${CERT}" ]]   || onx_die 1 "cert file missing: ${CERT}"
[[ -f "${KEY}" ]]    || onx_die 1 "key file missing: ${KEY}"

# ── Preflight: Apache installed? ─────────────────────────────────────────────
[[ -x /usr/sbin/httpd || -x /usr/sbin/apache2 ]] || \
    onx_die 2 "Apache (httpd/apache2) not installed"

# ── Locate vhost ─────────────────────────────────────────────────────────────
# RHEL: /etc/httpd/conf.d/, Debian: /etc/apache2/sites-enabled/
declare -a SEARCH_DIRS=()
[[ -d /etc/httpd/conf.d ]] && SEARCH_DIRS+=(/etc/httpd/conf.d)
[[ -d /etc/apache2/sites-enabled ]] && SEARCH_DIRS+=(/etc/apache2/sites-enabled)
[[ -d /etc/apache2/sites-available ]] && SEARCH_DIRS+=(/etc/apache2/sites-available)

[[ "${#SEARCH_DIRS[@]}" -gt 0 ]] || onx_die 2 "no Apache vhost directory found"

VHOST_FILE=""
for dir in "${SEARCH_DIRS[@]}"; do
    # Domain match — ServerName regex (whitespace robust)
    match=$(grep -rEl "^[[:space:]]*ServerName[[:space:]]+${DOMAIN//./\\.}[[:space:]]*\$" "${dir}" 2>/dev/null | head -1 || true)
    if [[ -n "${match}" ]]; then
        VHOST_FILE="${match}"
        break
    fi
done

[[ -z "${VHOST_FILE}" ]] && onx_die 3 "Apache vhost not found for ServerName ${DOMAIN}"

# ── Check current cert paths (idempotent — already-correct = no-op) ─────────
CUR_CERT=$(awk '/<VirtualHost[^>]*:443/,/<\/VirtualHost>/' "${VHOST_FILE}" | \
           awk '/^[[:space:]]*SSLCertificateFile[[:space:]]+/ {print $2; exit}' || true)
CUR_KEY=$(awk '/<VirtualHost[^>]*:443/,/<\/VirtualHost>/' "${VHOST_FILE}" | \
          awk '/^[[:space:]]*SSLCertificateKeyFile[[:space:]]+/ {print $2; exit}' || true)

CHANGED="true"
if [[ "${CUR_CERT}" == "${CERT}" && "${CUR_KEY}" == "${KEY}" ]]; then
    CHANGED="false"
    onx_log "vhost ${VHOST_FILE} cert paths already up-to-date for ${DOMAIN}"
fi

if [[ "${CHANGED}" == "true" ]]; then
    # Backup + atomic sed
    BACKUP="${VHOST_FILE}.bak.cert-link.$$"
    cp -p "${VHOST_FILE}" "${BACKUP}"

    # sed in-place rewrite — leading whitespace korunur via [[:space:]]
    sed -i -E "s|^([[:space:]]*)SSLCertificateFile[[:space:]]+.*\$|\1SSLCertificateFile ${CERT}|" "${VHOST_FILE}"
    sed -i -E "s|^([[:space:]]*)SSLCertificateKeyFile[[:space:]]+.*\$|\1SSLCertificateKeyFile ${KEY}|" "${VHOST_FILE}"

    # apachectl configtest — bozulduysa rollback
    if command -v apachectl >/dev/null 2>&1; then
        if ! apachectl configtest 2>/tmp/onx-apache-cert-link-test.log; then
            mv "${BACKUP}" "${VHOST_FILE}"
            ERR=$(head -3 /tmp/onx-apache-cert-link-test.log 2>/dev/null | tr -d '\000' || echo "")
            onx_die 3 "apachectl configtest failed after cert rewrite; rolled back: ${ERR}"
        fi
    fi

    onx_log "rewrote cert paths in ${VHOST_FILE} for ${DOMAIN}"
fi

# ── Reload ───────────────────────────────────────────────────────────────────
RELOAD_ERR=""
if systemctl reload-or-restart httpd 2>/tmp/onx-apache-cert-link-reload.log; then
    RELOADED="true"
elif systemctl reload-or-restart apache2 2>>/tmp/onx-apache-cert-link-reload.log; then
    RELOADED="true"
else
    RELOAD_ERR=$(head -3 /tmp/onx-apache-cert-link-reload.log 2>/dev/null | tr -d '\000' || echo "")
    onx_die 3 "Apache reload failed: ${RELOAD_ERR}"
fi

# ── Output ───────────────────────────────────────────────────────────────────
onx_json_out \
    "success"  "true" \
    "vhost"    "${VHOST_FILE}" \
    "reloaded" "${RELOADED}" \
    "changed"  "${CHANGED}"
