#!/bin/bash
# Abilita redirect HTTP→HTTPS e allinea config VTE (vtemessiniegori).
# Rimuove il VirtualHost :80 duplicato in le-ssl.conf (blocca il redirect).
#
#   sudo bash /var/www/html/server-ops/mypantarei/enable-vtemessiniegori-https.sh

set -euo pipefail

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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VTE=/var/www/html/vtemessiniegori
HTTP_CONF=/etc/apache2/sites-available/vtemessiniegori.conf
SSL_CONF=/etc/apache2/sites-available/vtemessiniegori-le-ssl.conf
APACHE_SRC=/var/www/html/vte2472/scripts

REDIRECT_BLOCK='RewriteEngine on
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/
RewriteCond %{SERVER_NAME} =vte-massiniegori.mypantarei.net [OR]
RewriteCond %{SERVER_NAME} =vte-messiniegori.mypantarei.net [OR]
RewriteCond %{SERVER_NAME} =www.vte-massiniegori.mypantarei.net [OR]
RewriteCond %{SERVER_NAME} =www.vte-messiniegori.mypantarei.net
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]'

echo "=== Apache: copia template aggiornati ==="
cp -a "${APACHE_SRC}/apache_vtemessiniegori.conf" "$HTTP_CONF"
cp -a "${APACHE_SRC}/apache_vtemessiniegori-le-ssl.conf" "$SSL_CONF"

echo "=== Apache: PHP 8.3 FPM su entrambi i vhost ==="
bash "${SCRIPT_DIR}/apply-vtemessiniegori-php83-apache.sh"

echo "=== Apache: abilita SSL ==="
a2enmod ssl rewrite headers 2>/dev/null || true
a2ensite vtemessiniegori.conf vtemessiniegori-le-ssl.conf

echo "=== config.inc.php: site_URL https ==="
php8.3 <<'PHP'
<?php
$f = '/var/www/html/vtemessiniegori/config.inc.php';
$c = file_get_contents($f);
$c = preg_replace(
    "/\\\$site_URL = 'https?:\\/\\/vte-massiniegori\\.mypantarei\\.net';/",
    "\$site_URL = 'https://vte-massiniegori.mypantarei.net';",
    $c,
    1
);
file_put_contents($f, $c);
echo "site_URL aggiornato.\n";
PHP

apache2ctl configtest
systemctl reload apache2

echo ""
echo "[OK] Redirect HTTP→HTTPS attivo."
echo "Verifica:"
echo "  curl -sI http://vte-massiniegori.mypantarei.net/ | grep -i location"
echo "  curl -sIk https://vte-massiniegori.mypantarei.net/ | head -3"
