#!/bin/bash
# Handler PHP 8.3 FPM solo per vtemessiniegori (vhost dedicati).
#   sudo bash /var/www/html/server-ops/mypantarei/apply-vtemessiniegori-php83-apache.sh

set -euo pipefail

[[ "${EUID:-0}" -ne 0 ]] && { echo "Serve root: sudo bash $0"; exit 1; }

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 'vtemessiniegori' "$f" 2>/dev/null; then
		echo "[OK] Già patchato: $f"
		return 0
	fi
	python3 - "$f" <<'PY'
import sys
path = sys.argv[1]
needle = '<Directory "/var/www/html/vtemessiniegori/">'
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] </Directory> non trovato in {path}")
insert_at = start + rel
open(path, "w", encoding="utf-8").write(text[:insert_at] + block + text[insert_at:])
print(f"[OK] Patch PHP 8.3: {path}")
PY
}

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

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