#!/bin/bash
# Alza il limite di richieste PHP/AJAX contemporanee (pool www PHP 8.3 FPM).
# Da 5 → 20 (pm.max_children) e aggiorna i spare servers per mode dynamic.
# Esecuzione: sudo bash /var/www/html/server-ops/fibbi/tune-php-fpm-max-children.sh
#
# Opzionale: MAX_CHILDREN=20 START=5 MIN_SPARE=2 MAX_SPARE=8 sudo -E bash ...

set -euo pipefail

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

PHP_VER="${PHP_VER:-8.3}"
POOL="/etc/php/${PHP_VER}/fpm/pool.d/www.conf"
MAX_CHILDREN="${MAX_CHILDREN:-20}"
START="${START:-5}"
MIN_SPARE="${MIN_SPARE:-2}"
MAX_SPARE="${MAX_SPARE:-8}"

if [[ ! -f "$POOL" ]]; then
	echo "[ERR] Pool non trovato: $POOL" >&2
	exit 1
fi

if ! [[ "$MAX_CHILDREN" =~ ^[0-9]+$ ]] || (( MAX_CHILDREN < 1 )); then
	echo "[ERR] MAX_CHILDREN non valido: $MAX_CHILDREN" >&2
	exit 1
fi
if (( START > MAX_CHILDREN || MIN_SPARE > MAX_SPARE || MAX_SPARE > MAX_CHILDREN || MIN_SPARE < 1 )); then
	echo "[ERR] Combinazione start/spare incoerente rispetto a max_children=$MAX_CHILDREN" >&2
	exit 1
fi

cp -a "$POOL" "${POOL}.bak.$(date +%Y%m%d%H%M%S)"

# Sostituisce solo le direttive attive (righe non commentate) del pool www
sed -i -E \
	-e "s/^pm\.max_children\s*=.*/pm.max_children = ${MAX_CHILDREN}/" \
	-e "s/^pm\.start_servers\s*=.*/pm.start_servers = ${START}/" \
	-e "s/^pm\.min_spare_servers\s*=.*/pm.min_spare_servers = ${MIN_SPARE}/" \
	-e "s/^pm\.max_spare_servers\s*=.*/pm.max_spare_servers = ${MAX_SPARE}/" \
	"$POOL"

echo "[INFO] Valori applicati in $POOL:"
grep -E '^pm\.|^pm =' "$POOL" | head -20

php-fpm${PHP_VER} -t
systemctl reload "php${PHP_VER}-fpm"

echo "[OK] php${PHP_VER}-fpm ricaricato. max_children=${MAX_CHILDREN}"
# Snapshot processi
ps -C "php-fpm${PHP_VER}" --no-headers 2>/dev/null | wc -l | xargs -I{} echo "[INFO] processi php-fpm: {}"
