#!/bin/bash
# Fibbi / vte.fibbielio.it — PHP 7.4 FPM + PHP 8.x FPM (Apache), migrazione da mod_php.
# Su Ubuntu 20.04 il PPA Ondrej potrebbe non offrire php8.3-*: si installa la massima 8.x disponibile (es. 8.2).
# Dopo upgrade a 22.04/24.04 rieseguire lo script o installare manualmente php8.3-* per allineo a VTE 26.
# Esecuzione: sudo bash /var/www/html/server-ops/fibbi/install-dual-php-fpm-apache.sh

set -euo pipefail

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

. /etc/os-release
echo "[INFO] OS: ${PRETTY_NAME:-unknown}"

export DEBIAN_FRONTEND=noninteractive

apt-get update -qq
apt-get install -y software-properties-common ca-certificates lsb-release python3

if ! grep -qr 'ondrej/php' /etc/apt/sources.list /etc/apt/sources.list.d/ 2>/dev/null; then
	add-apt-repository -y ppa:ondrej/php
fi
apt-get update -qq

# Pacchetto phpX.Y-fpm presente in apt per questa distro?
php_fpm_available() {
	local pkg="php${1}-fpm"
	local cand
	cand=$(apt-cache policy "$pkg" 2>/dev/null | awk '/Candidate:/ {print $2}')
	[[ -n "${cand:-}" && "$cand" != "(none)" ]]
}

PHP8_VER=""
for try in 8.4 8.3 8.2 8.1 8.0; do
	if php_fpm_available "$try"; then
		PHP8_VER="$try"
		break
	fi
done

if [[ -z "$PHP8_VER" ]]; then
	echo "[WARN] Nessun PHP 8.x FPM trovato in apt. Installo solo PHP 7.4 FPM + Apache."
fi

echo "[INFO] PHP secondario (test / futuro VTE 26): ${PHP8_VER:-nessuno}"

PHP_PKGS=(php7.4-fpm php7.4-cli php7.4-common php7.4-mysql php7.4-xml php7.4-curl php7.4-gd php7.4-mbstring php7.4-zip php7.4-bcmath php7.4-imap php7.4-ldap php7.4-intl php7.4-readline php7.4-opcache php7.4-soap)
if [[ -n "$PHP8_VER" ]]; then
	PHP_PKGS+=(
		"php${PHP8_VER}-fpm" "php${PHP8_VER}-cli" "php${PHP8_VER}-common" "php${PHP8_VER}-mysql" "php${PHP8_VER}-xml"
		"php${PHP8_VER}-curl" "php${PHP8_VER}-gd" "php${PHP8_VER}-mbstring" "php${PHP8_VER}-zip" "php${PHP8_VER}-bcmath"
		"php${PHP8_VER}-imap" "php${PHP8_VER}-ldap" "php${PHP8_VER}-intl" "php${PHP8_VER}-readline" "php${PHP8_VER}-opcache" "php${PHP8_VER}-soap"
	)
fi

apt-get install -y --no-install-recommends "${PHP_PKGS[@]}"
apt-get install -y --no-install-recommends php7.4-apcu 2>/dev/null || true
if [[ -n "$PHP8_VER" ]]; then
	apt-get install -y --no-install-recommends "php${PHP8_VER}-apcu" 2>/dev/null || true
fi
apt-get install -y --no-install-recommends php7.4-pcntl 2>/dev/null || true
if [[ -n "$PHP8_VER" ]]; then
	apt-get install -y --no-install-recommends "php${PHP8_VER}-pcntl" 2>/dev/null || true
fi

if a2query -m php7.4 &>/dev/null; then
	a2dismod -f php7.4 || true
fi
if dpkg -l libapache2-mod-php7.4 &>/dev/null; then
	apt-get remove -y libapache2-mod-php7.4 || true
fi

a2enmod proxy proxy_fcgi setenvif ssl rewrite headers || true
a2dismod -f mpm_prefork 2>/dev/null || true
a2enmod mpm_event

install -m0644 /dev/stdin /etc/php/7.4/fpm/pool.d/zz-phpmyadmin-fibbi.conf <<'EOFPM'
; Pool dedicato phpMyAdmin (open_basedir)
[phpmyadmin]
user = www-data
group = www-data
listen = /run/php/php7.4-fpm-phpmyadmin.sock
listen.owner = www-data
listen.group = www-data
pm = ondemand
pm.max_children = 8
chdir = /usr/share/phpmyadmin
php_admin_value[upload_tmp_dir] = /var/lib/phpmyadmin/tmp
php_admin_value[open_basedir] = /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/:/usr/share/php/php-gettext/:/usr/share/php/php-php-gettext/:/usr/share/javascript/:/usr/share/php/tcpdf/:/usr/share/doc/phpmyadmin/:/usr/share/php/phpseclib/:/usr/share/php/PhpMyAdmin/:/usr/share/php/Symfony/:/usr/share/php/Twig/:/usr/share/php/Twig-Extensions/:/usr/share/php/ReCaptcha/:/usr/share/php/Psr/Container/:/usr/share/php/Psr/Cache/:/usr/share/php/Psr/Log/:/usr/share/php/Psr/SimpleCache/
EOFPM

for VER in 7.4 ${PHP8_VER:-}; do
	[[ -n "$VER" ]] || continue
	install -m0644 /dev/stdin "/etc/php/${VER}/fpm/conf.d/99-vte-fibbi.ini" <<EOFINI
memory_limit = 512M
max_execution_time = 300
max_input_vars = 5000
post_max_size = 64M
upload_max_filesize = 64M
date.timezone = Europe/Rome
EOFINI
done

install -m0644 /dev/stdin /etc/apache2/conf-available/phpmyadmin-php74-fpm-fibbi.conf <<'EOFA'
<Directory /usr/share/phpmyadmin>
	<FilesMatch "\.php$">
		SetHandler "proxy:unix:/run/php/php7.4-fpm-phpmyadmin.sock|fcgi://localhost/"
	</FilesMatch>
</Directory>
EOFA
a2enconf phpmyadmin-php74-fpm-fibbi

if [[ -n "$PHP8_VER" ]]; then
	a2dissite vte-fibbi-php83-localhost.conf 2>/dev/null || true
	install -m0644 /dev/stdin /etc/apache2/conf-available/fibbi-listen-8083.conf <<'EOFL'
Listen 8083
EOFL
	a2enconf fibbi-listen-8083

	AUX_SITE=/etc/apache2/sites-available/vte-fibbi-php8-aux-localhost.conf
	cat >"$AUX_SITE" <<EOF83
<VirtualHost 127.0.0.1:8083>
	ServerAdmin admin@mypantarei.net
	DocumentRoot /var/www/html/vte23083_2711/
	ErrorLog \${APACHE_LOG_DIR}/fibbi-php8-aux-error.log
	CustomLog \${APACHE_LOG_DIR}/fibbi-php8-aux-access.log combined
	<Directory "/var/www/html/vte23083_2711/">
		Options +ExecCGI -Indexes +FollowSymLinks +MultiViews
		AllowOverride All
		Require all granted
		<FilesMatch "\\.php\$">
			SetHandler "proxy:unix:/run/php/php${PHP8_VER}-fpm.sock|fcgi://localhost/"
		</FilesMatch>
	</Directory>
</VirtualHost>
EOF83
	chmod 0644 "$AUX_SITE"
	a2ensite "$(basename "$AUX_SITE")"
fi

patch_vhost_fpm() {
	local f="$1"
	[[ -f "$f" ]] || return 0
	if grep -q 'php7.4-fpm.sock' "$f" 2>/dev/null; then
		echo "[INFO] Già patchato: $f"
		return 0
	fi
	python3 - "$f" <<'PY'
import sys
path = sys.argv[1]
block = """    <FilesMatch \"\\.php$\">
        SetHandler \"proxy:unix:/run/php/php7.4-fpm.sock|fcgi://localhost/\"
    </FilesMatch>
"""
text = open(path, encoding="utf-8").read()
if "php7.4-fpm.sock" in text:
    sys.exit(0)
marker = '<Directory "/var/www/html/vte23083_2711/">'
start = text.find(marker)
if start == -1:
    sys.exit(f"Directory VTE non trovata in {path}")
needle = "</Directory>"
sub = text[start:]
pos_rel = sub.find(needle)
if pos_rel == -1:
    sys.exit(f"Chiusura Directory VTE non trovata in {path}")
insert_at = start + pos_rel
new_text = text[:insert_at] + block + text[insert_at:]
open(path, "w", encoding="utf-8").write(new_text)
print(f"[OK] Patch FPM 7.4: {path}")
PY
}

patch_vhost_fpm /etc/apache2/sites-available/vte.fibbielio.it.conf
patch_vhost_fpm /etc/apache2/sites-available/vte.fibbielio.it-le-ssl.conf

systemctl restart php7.4-fpm
if [[ -n "$PHP8_VER" ]]; then
	systemctl restart "php${PHP8_VER}-fpm"
fi
apache2ctl configtest
systemctl restart apache2

echo ""
echo "[OK] PHP 7.4 FPM (produzione) attivo."
if [[ -n "$PHP8_VER" ]]; then
	echo "     PHP ${PHP8_VER} FPM installato — test: curl -sS -D- http://127.0.0.1:8083/ -o /dev/null"
	echo "     Dopo Ubuntu 24.04: apt install php8.3-* e aggiornare questo vhost al socket php8.3-fpm per VTE 26."
else
	echo "     Nessun PHP 8.x da PPA su questa release: aggiungi dopo upgrade distro."
fi
if [[ -n "$PHP8_VER" ]]; then
	echo "     Cron VTE: /usr/bin/php7.4 ... fino a VTE 26; poi preferire /usr/bin/php8.3 su Ubuntu 24+ (ora hai php${PHP8_VER})."
else
	echo "     Cron VTE: /usr/bin/php7.4 ... fino a VTE 26, poi /usr/bin/php8.3 dopo upgrade distro."
fi
if [[ "${VERSION_ID:-}" != "24.04" ]]; then
	echo ""
	echo "[NOTA] VERSION_ID=${VERSION_ID:-?} — per Ubuntu 24.04: sudo do-release-upgrade (LTS→LTS)"
fi
