#!/usr/bin/env bash
set -euo pipefail

PHP_VERSION="${1:-}"
TEST_IP="__SERVER_IP__"
ROOT_DIR="/home/sone/htdocs/default/public"
CONF_FILE="/etc/nginx/conf.d/00-sone-test-ip.conf"
SOCKET="/run/sone-php/php${PHP_VERSION}-fpm.sock"

if [ -z "${PHP_VERSION}" ]; then
  echo "Использование: sone-switch-php <version>"
  echo "Пример: sone-switch-php 8.5"
  exit 1
fi

if [ ! -S "${SOCKET}" ]; then
  echo "Ошибка: сокет не найден: ${SOCKET}"
  exit 1
fi

if [ -x "/opt/php/${PHP_VERSION}/bin/php" ]; then
  update-alternatives --set php "/opt/php/${PHP_VERSION}/bin/php" || true
fi

if [ -x "/opt/php/${PHP_VERSION}/bin/phpize" ]; then
  update-alternatives --set phpize "/opt/php/${PHP_VERSION}/bin/phpize" || true
fi

if [ -x "/opt/php/${PHP_VERSION}/bin/php-config" ]; then
  update-alternatives --set php-config "/opt/php/${PHP_VERSION}/bin/php-config" || true
fi

cat > "${CONF_FILE}" <<EOF2
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name ${TEST_IP} _;

    root ${ROOT_DIR};
    index index.php index.html index.htm;

    access_log /var/log/nginx/sone-test.access.log;
    error_log /var/log/nginx/sone-test.error.log warn;

    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT \$document_root;
        fastcgi_index index.php;
        fastcgi_pass unix:${SOCKET};
    }
}
EOF2

nginx -t
systemctl reload nginx

echo "Переключено на PHP ${PHP_VERSION}"
php -v