#!/bin/bash
# Handler PHP 8.3 FPM solo per /var/www/html/vteguzzini/ (vhost in vtesmau.conf / vtesmau-le-ssl.conf).
# Richiede root. Idempotente.
#
#   sudo bash /var/www/html/server-ops/mypantarei/apply-vteguzzini-php83-apache.sh
#   sudo apache2ctl configtest && sudo systemctl reload apache2

set -euo pipefail

if [[ "${EUID:-0}" -ne 0 ]]; then
	echo "Esegui come root: sudo bash $0" >&2
	exit 1
fi

patch_file() {
	local f="$1"
	[[ -f "$f" ]] || { echo "[WARN] Manca $f"; return 0; }
	if grep -q 'php8.3-fpm.sock' "$f" 2>/dev/null && grep -q 'vteguzzini' "$f" 2>/dev/null; then
		echo "[OK] Già patchato (php8.3 + vteguzzini): $f"
		return 0
	fi
	python3 - "$f" <<'PY'
import sys
path = sys.argv[1]
needle = '<Directory "/var/www/html/vteguzzini/">'
insert_before = "</Directory>"
block = """    <FilesMatch \\.php$>
        SetHandler \"proxy:unix:/run/php/php8.3-fpm.sock|fcgi://localhost/\"
    </FilesMatch>

"""
text = open(path, encoding="utf-8").read()
if needle not in text:
    sys.exit(f"[ERRORE] {needle!r} non trovato in {path}")
if "php8.3-fpm.sock" in text[text.find(needle):text.find(needle) + 800]:
    print(f"[OK] Già patchato: {path}")
    sys.exit(0)
start = text.find(needle)
rel = text[start:].find(insert_before)
if rel == -1:
    sys.exit(f"[ERRORE] {insert_before!r} non trovato dopo Directory vteguzzini in {path}")
insert_at = start + rel
new_text = text[:insert_at] + block + text[insert_at:]
open(path, "w", encoding="utf-8").write(new_text)
print(f"[OK] Patch PHP 8.3: {path}")
PY
}

patch_file /etc/apache2/sites-available/vtesmau.conf
patch_file /etc/apache2/sites-available/vtesmau-le-ssl.conf

echo ""
echo "Prossimo: sudo apache2ctl configtest && sudo systemctl reload apache2"
