#!/usr/bin/env bash
# =============================================================================
# onx-nginx-vhost-cert-link (v89) — Nginx vhost SSL config patch
#
# Nginx vhost dosyasındaki ssl_certificate + ssl_certificate_key direktiflerini
# yeni cert path'iyle in-place günceller. Idempotent.
#
# NOT: Reload yetersiz — TLS context'i tam yenilemek için RESTART şart
# (per feedback_onoxsoft_nginx_sni_cache_restart).
#
# Input (stdin JSON):
#   domain     string  Domain (server_name matched)
#   cert_path  string  Yeni fullchain.pem path
#   key_path   string  Yeni privkey.pem path
#
# Output (stdout JSON):
#   {"success":true, "vhost":..., "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-nginx-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: Nginx installed? ──────────────────────────────────────────────
command -v nginx >/dev/null 2>&1 || onx_die 2 "nginx binary not found in PATH"

# ── Locate vhost ─────────────────────────────────────────────────────────────
declare -a SEARCH_DIRS=()
[[ -d /etc/nginx/conf.d ]]        && SEARCH_DIRS+=(/etc/nginx/conf.d)
[[ -d /etc/nginx/sites-enabled ]] && SEARCH_DIRS+=(/etc/nginx/sites-enabled)
[[ -d /etc/nginx/sites-available ]] && SEARCH_DIRS+=(/etc/nginx/sites-available)

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

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

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

# ── Check current cert paths (idempotent) ────────────────────────────────────
CUR_CERT=$(grep -E "^[[:space:]]*ssl_certificate[[:space:]]+" "${VHOST_FILE}" | \
           grep -v ssl_certificate_key | head -1 | awk '{print $2}' | sed 's/;$//' || true)
CUR_KEY=$(grep -E "^[[:space:]]*ssl_certificate_key[[:space:]]+" "${VHOST_FILE}" | \
          head -1 | awk '{print $2}' | sed 's/;$//' || 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 — `ssl_certificate_key` ile çakışmayı önlemek için
    # önce key, sonra cert (order önemli, key satırı bittiğinde cert match etmez).
    sed -i -E "s|^([[:space:]]*)ssl_certificate_key[[:space:]]+[^;]+;|\1ssl_certificate_key ${KEY};|" "${VHOST_FILE}"
    sed -i -E "s|^([[:space:]]*)ssl_certificate[[:space:]]+[^;]+;|\1ssl_certificate ${CERT};|" "${VHOST_FILE}"

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

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

# ── Restart (RELOAD YETERSIZ — TLS context cache restart şart) ──────────────
RELOAD_ERR=""
if systemctl restart nginx 2>/tmp/onx-nginx-cert-link-reload.log; then
    RELOADED="true"
else
    RELOAD_ERR=$(head -3 /tmp/onx-nginx-cert-link-reload.log 2>/dev/null | tr -d '\000' || echo "")
    onx_die 3 "Nginx restart failed: ${RELOAD_ERR}"
fi

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