#!/bin/bash
# nginx-config.sh - Configurazione automatica Nginx per NetGescon

set -e

# Colori per output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_step() { echo -e "${BLUE}[STEP]${NC} $1"; }

echo "🌐 Configurazione Nginx per NetGescon"
echo "======================================"

# Verifica che Nginx sia installato
if ! command -v nginx &> /dev/null; then
    log_error "Nginx non installato. Esegui prima setup-netgescon.sh"
    exit 1
fi

# Verifica che il progetto Laravel esista
if [ ! -d "/var/www/netgescon/netgescon-laravel" ]; then
    log_error "Progetto Laravel non trovato in /var/www/netgescon/netgescon-laravel"
    exit 1
fi

log_step "1/5 Creazione virtual host Nginx..."

# Crea configurazione Nginx
sudo tee /etc/nginx/sites-available/netgescon > /dev/null <<EOF
server {
    listen 80;
    listen [::]:80;
    server_name localhost netgescon.local $(hostname -I | awk '{print $1}');
    root /var/www/netgescon/netgescon-laravel/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

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

    location = /favicon.ico { 
        access_log off; 
        log_not_found off; 
    }
    
    location = /robots.txt  { 
        access_log off; 
        log_not_found off; 
    }

    error_page 404 /index.php;

    location ~ \.php\$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$realpath_root\$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }

    # Security headers
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy "strict-origin-when-cross-origin";

    # Asset caching
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)\$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # Gzip compression
    gzip on;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
EOF

log_info "Virtual host creato: /etc/nginx/sites-available/netgescon"

log_step "2/5 Attivazione sito..."
sudo ln -sf /etc/nginx/sites-available/netgescon /etc/nginx/sites-enabled/

log_step "3/5 Disattivazione sito default..."
sudo rm -f /etc/nginx/sites-enabled/default

log_step "4/5 Test configurazione Nginx..."
if sudo nginx -t; then
    log_info "Configurazione Nginx OK"
else
    log_error "Errori nella configurazione Nginx"
    exit 1
fi

log_step "5/5 Riavvio servizi..."
sudo systemctl restart nginx
sudo systemctl restart php8.2-fpm

# Verifica stato servizi
if systemctl is-active --quiet nginx && systemctl is-active --quiet php8.2-fpm; then
    log_info "Servizi riavviati correttamente"
else
    log_error "Problemi con i servizi"
    echo "Verifica stato con: sudo systemctl status nginx php8.2-fpm"
    exit 1
fi

# Test HTTP response
SERVER_IP=$(hostname -I | awk '{print $1}')
if curl -s -o /dev/null -w "%{http_code}" "http://$SERVER_IP" | grep -q "200\|302"; then
    HTTP_STATUS="OK"
else
    HTTP_STATUS="FAILED"
fi

echo ""
echo "═══════════════════════════════════════════════════════"
echo "✅ CONFIGURAZIONE NGINX COMPLETATA!"
echo "═══════════════════════════════════════════════════════"
echo ""
echo "🌐 ACCESSO APPLICAZIONE:"
echo "   http://$SERVER_IP"
echo "   http://localhost (se locale)"
echo "   http://netgescon.local (aggiungi al file hosts)"
echo ""
echo "📁 CONFIGURAZIONE:"
echo "   Virtual host: /etc/nginx/sites-available/netgescon"
echo "   Document root: /var/www/netgescon/netgescon-laravel/public"
echo ""
echo "🔍 STATUS SERVIZI:"
echo "   Nginx: $(systemctl is-active nginx)"
echo "   PHP-FPM: $(systemctl is-active php8.2-fpm)"
echo "   HTTP Response: $HTTP_STATUS"
echo ""
echo "═══════════════════════════════════════════════════════"
echo ""
echo "🔧 COMANDI UTILI:"
echo ""
echo "📊 STATUS SERVIZI:"
echo "   sudo systemctl status nginx php8.2-fpm mysql"
echo ""
echo "🔄 RIAVVIO SERVIZI:"
echo "   sudo systemctl restart nginx php8.2-fpm"
echo ""
echo "📝 LOG NGINX:"
echo "   sudo tail -f /var/log/nginx/error.log"
echo "   sudo tail -f /var/log/nginx/access.log"
echo ""
echo "🧪 TEST CONFIGURAZIONE:"
echo "   sudo nginx -t"
echo ""

# Aggiungi entry al file hosts locale (opzionale)
if ! grep -q "netgescon.local" /etc/hosts; then
    log_info "Aggiunta entry hosts locale..."
    echo "127.0.0.1 netgescon.local" | sudo tee -a /etc/hosts
fi

# Salva info configurazione
echo "=== Nginx Configuration Info ===" >> ~/netgescon-setup-info.txt
echo "Data configurazione Nginx: $(date)" >> ~/netgescon-setup-info.txt
echo "Server IP: $SERVER_IP" >> ~/netgescon-setup-info.txt
echo "Virtual host: /etc/nginx/sites-available/netgescon" >> ~/netgescon-setup-info.txt
echo "HTTP Status: $HTTP_STATUS" >> ~/netgescon-setup-info.txt
echo "" >> ~/netgescon-setup-info.txt

log_info "Configurazione salvata in: ~/netgescon-setup-info.txt"
log_info "🎉 NetGescon dovrebbe essere accessibile via browser!"
