#!/bin/bash
# Basé sur un travail de Cédric Abonnel / Cédrix sous licence CC BY-NC 4.0

source "$(dirname "$0")/../common/common_utils.sh"
check_root

GREEN="\e[32m"
YELLOW="\e[33m"
RED="\e[31m"
RESET="\e[0m"

echo -e "${YELLOW}Mise à jour du système...${RESET}"
apt update && apt upgrade -y

VERSION=$(lsb_release -sc)
SUPPORTED_VERSIONS=("trixie")
TIMEZONE=$(timedatectl show --value --property=Timezone)
TIMEZONE=${TIMEZONE:-UTC}

if [[ ! " ${SUPPORTED_VERSIONS[@]} " =~ " ${VERSION} " ]]; then
    echo -e "${RED}Version non supportée : $VERSION${RESET}"
    exit 1
fi

# Dépôt Sury (Format moderne avec signed-by pour Trixie)
if ! grep -q "packages.sury.org" /etc/apt/sources.list.d/php.list 2>/dev/null; then
    apt install -y ca-certificates apt-transport-https curl
    curl -sSLo /usr/share/keyrings/deb.sury.org-php.gpg https://packages.sury.org/php/apt.gpg
    echo "deb [signed-by=/usr/share/keyrings/deb.sury.org-php.gpg] https://packages.sury.org/php/ $VERSION main" > /etc/apt/sources.list.d/php.list
    apt update
fi

PHP_VERSION="8.3"
echo -e "${YELLOW}Installation de PHP $PHP_VERSION...${RESET}"

PHP_MODULES=(
    php${PHP_VERSION} php${PHP_VERSION}-cli php${PHP_VERSION}-fpm php${PHP_VERSION}-common
    php${PHP_VERSION}-curl php${PHP_VERSION}-gd php${PHP_VERSION}-mbstring php${PHP_VERSION}-xml
    php${PHP_VERSION}-zip php${PHP_VERSION}-bcmath php${PHP_VERSION}-soap php${PHP_VERSION}-intl
    php${PHP_VERSION}-readline php${PHP_VERSION}-ldap php${PHP_VERSION}-imagick php${PHP_VERSION}-gmp
    php${PHP_VERSION}-apcu php${PHP_VERSION}-opcache php${PHP_VERSION}-sqlite3
)

dpkg -l | grep -qE 'mysql-server|mariadb-server' && PHP_MODULES+=(php${PHP_VERSION}-mysql)
dpkg -l | grep -q postgresql && PHP_MODULES+=(php${PHP_VERSION}-pgsql)

apt install -y "${PHP_MODULES[@]}"

# 1. Optimisation des fichiers php.ini (CLI, FPM, Apache)
for INI in "/etc/php/${PHP_VERSION}/fpm/php.ini" "/etc/php/${PHP_VERSION}/cli/php.ini" "/etc/php/${PHP_VERSION}/apache2/php.ini"; do
    if [ -f "$INI" ]; then
        sed -i 's/memory_limit = .*/memory_limit = 512M/' "$INI"
        sed -i 's/upload_max_filesize = .*/upload_max_filesize = 100M/' "$INI"
        sed -i 's/post_max_size = .*/post_max_size = 100M/' "$INI"
        sed -i 's/max_execution_time = .*/max_execution_time = 300/' "$INI"
        sed -i "s|^;*date.timezone =.*|date.timezone = ${TIMEZONE}|" "$INI"
    fi
done

# 2. Optimisation OPcache (incluant le JIT pour PHP 8.3)
OPCACHE_INI="/etc/php/${PHP_VERSION}/fpm/conf.d/10-opcache.ini"
cat > "$OPCACHE_INI" <<EOF
opcache.enable=1
opcache.enable_cli=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=20000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
; Optimisation JIT pour PHP 8.3
opcache.jit=tracing
opcache.jit_buffer_size=100M
EOF

# 3. Optimisation APCu
APCU_INI="/etc/php/${PHP_VERSION}/fpm/conf.d/20-apcu.ini"
cat > "$APCU_INI" <<EOF
apc.enabled=1
apc.shm_size=64M
apc.ttl=7200
apc.enable_cli=0
EOF

# 4. Optimisation du Pool PHP-FPM (www.conf)
FPM_POOL="/etc/php/${PHP_VERSION}/fpm/pool.d/www.conf"
if [ -f "$FPM_POOL" ]; then
    echo -e "${YELLOW}Optimisation des processus FPM...${RESET}"
    sed -i 's/^pm = .*/pm = dynamic/' "$FPM_POOL"
    sed -i 's/^pm.max_children = .*/pm.max_children = 80/' "$FPM_POOL"
    sed -i 's/^pm.start_servers = .*/pm.start_servers = 10/' "$FPM_POOL"
    sed -i 's/^pm.min_spare_servers = .*/pm.min_spare_servers = 5/' "$FPM_POOL"
    sed -i 's/^pm.max_spare_servers = .*/pm.max_spare_servers = 20/' "$FPM_POOL"
    sed -i 's/^;pm.max_requests = .*/pm.max_requests = 1000/' "$FPM_POOL"
fi

# Finalisation
systemctl restart php${PHP_VERSION}-fpm
if systemctl list-units --type=service --all | grep -q "apache2.service"; then
    apt install -y libapache2-mod-php${PHP_VERSION}
    systemctl restart apache2
fi

echo -e "${GREEN}Installation et optimisations PHP $PHP_VERSION terminées ! 🚀${RESET}"