#!/bin/bash
# 🚀 NETGESCON - SETUP CORRETTO VM MASTER CON NGINX
# Creato: 19/07/2025 - Setup definitivo Michele + AI

set -e

echo "🚀 === NETGESCON - SETUP DEFINITIVO VM MASTER ==="
echo "📅 $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

# === CONFIGURAZIONI ===
PROJECT_PATH="/home/michele/netgescon"
WEB_ROOT="/var/www"
DOMAIN="netgescon.local"
VM_IP="192.168.0.200"

echo "📋 Configurazione:"
echo "   Progetto: $PROJECT_PATH"
echo "   Web Server: Nginx (invece di Apache)"
echo "   Dominio: $DOMAIN"
echo "   IP VM: $VM_IP"
echo ""

# === 1. PULIZIA INIZIALE ===
echo "🧹 1. Pulizia /var/www/ e rimozione Apache..."

# Rimuove Apache se presente
if systemctl is-active apache2 >/dev/null 2>&1; then
    sudo systemctl stop apache2
    sudo systemctl disable apache2
    sudo apt remove -y apache2
    echo "   ✅ Apache rimosso"
fi

# Pulizia /var/www/
sudo rm -rf /var/www/html
sudo rm -rf /var/www/netgescon*
sudo mkdir -p /var/www
echo "   ✅ Directory /var/www/ pulita"

# === 2. AGGIORNAMENTO SISTEMA ===
echo ""
echo "🔄 2. Aggiornamento sistema..."
sudo apt update && sudo apt upgrade -y

# === 3. INSTALLAZIONE STACK NGINX ===
echo ""
echo "📦 3. Installazione stack con Nginx..."

# Nginx
sudo apt install -y nginx
sudo systemctl enable nginx
sudo systemctl start nginx

# MySQL
sudo apt install -y mysql-server
sudo systemctl enable mysql
sudo systemctl start mysql

# PHP-FPM (migliore per Nginx)
sudo apt install -y php8.1-fpm php8.1-mysql php8.1-xml php8.1-mbstring \
    php8.1-zip php8.1-gd php8.1-curl php8.1-dom php8.1-common php8.1-cli \
    php8.1-bcmath php8.1-opcache

# Composer
if ! command -v composer &> /dev/null; then
    curl -sS https://getcomposer.org/installer | php
    sudo mv composer.phar /usr/local/bin/composer
    sudo chmod +x /usr/local/bin/composer
fi

# Node.js
if ! command -v node &> /dev/null; then
    curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
    sudo apt install -y nodejs
fi

# Git (se non presente)
sudo apt install -y git curl wget rsync

echo "   ✅ Stack Nginx installato"

# === 4. CONFIGURAZIONE NGINX PER LARAVEL ===
echo ""
echo "🌐 4. Configurazione Nginx per Laravel..."

# Backup configurazione default
sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/default.backup

# Crea configurazione NetGescon ottimizzata
sudo tee /etc/nginx/sites-available/netgescon << EOF
server {
    listen 80;
    listen [::]:80;
    
    server_name $DOMAIN $VM_IP localhost;
    root $PROJECT_PATH/netgescon-laravel/public;
    index index.php index.html index.htm;

    # Logs
    access_log /var/log/nginx/netgescon-access.log;
    error_log /var/log/nginx/netgescon-error.log;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

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

    # PHP-FPM
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$realpath_root\$fastcgi_script_name;
        include fastcgi_params;
        
        # Timeout ottimizzati per Laravel
        fastcgi_read_timeout 300;
        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
    }

    # Static files caching
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        try_files \$uri =404;
    }

    # Deny access to sensitive files
    location ~ /\.(?!well-known).* {
        deny all;
    }
    
    location ~ /\.env {
        deny all;
    }

    # Prevent access to Laravel directories
    location ~ ^/(storage|bootstrap/cache)/ {
        deny all;
    }
}
EOF

# Abilita sito e disabilita default
sudo ln -sf /etc/nginx/sites-available/netgescon /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default

# Test configurazione
sudo nginx -t
sudo systemctl reload nginx

echo "   ✅ Nginx configurato per Laravel"

# === 5. CONFIGURAZIONE DATABASE ===
echo ""
echo "🗄️ 5. Configurazione database MySQL..."

sudo mysql << 'MYSQL_SCRIPT'
CREATE DATABASE IF NOT EXISTS netgescon;
CREATE USER IF NOT EXISTS 'netgescon'@'localhost' IDENTIFIED BY 'netgescon2025';
GRANT ALL PRIVILEGES ON netgescon.* TO 'netgescon'@'localhost';
FLUSH PRIVILEGES;
MYSQL_SCRIPT

echo "   ✅ Database MySQL configurato"

# === 6. CONFIGURAZIONE LARAVEL ===
echo ""
echo "🔧 6. Configurazione Laravel..."

cd $PROJECT_PATH/netgescon-laravel

# Installa dipendenze se composer.json esiste
if [ -f "composer.json" ]; then
    composer install --no-dev --optimize-autoloader
    echo "   ✅ Dipendenze Composer installate"
fi

# Configura .env per produzione
if [ ! -f ".env" ] && [ -f ".env.example" ]; then
    cp .env.example .env
fi

# Aggiorna configurazione .env
cat > .env << 'ENV_CONFIG'
APP_NAME="NetGescon Master"
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=http://192.168.0.200

LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=error

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=netgescon
DB_USERNAME=netgescon
DB_PASSWORD=netgescon2025

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

MEMCACHED_HOST=127.0.0.1

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1

VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
ENV_CONFIG

# Genera chiave app
php artisan key:generate --force

# Ottimizza per produzione
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Permessi corretti
sudo chown -R www-data:www-data $PROJECT_PATH/netgescon-laravel/storage
sudo chown -R www-data:www-data $PROJECT_PATH/netgescon-laravel/bootstrap/cache
sudo chmod -R 775 $PROJECT_PATH/netgescon-laravel/storage
sudo chmod -R 775 $PROJECT_PATH/netgescon-laravel/bootstrap/cache

echo "   ✅ Laravel configurato per produzione"

# Esegui migrazioni
if [ -f "artisan" ]; then
    php artisan migrate --force
    echo "   ✅ Migrazioni database eseguite"
fi

# === 7. INSTALLAZIONE DOCKER E GITEA ===
echo ""
echo "🐳 7. Installazione Docker e Gitea..."

# Installa Docker
if ! command -v docker &> /dev/null; then
    curl -fsSL https://get.docker.com -o get-docker.sh
    sudo sh get-docker.sh
    sudo systemctl enable docker
    sudo systemctl start docker
    sudo usermod -aG docker michele
    rm get-docker.sh
fi

# Crea directory per Gitea
sudo mkdir -p /var/lib/gitea
sudo chown -R 1000:1000 /var/lib/gitea

# Avvia Gitea
sudo docker run -d \
  --name=gitea \
  --restart=unless-stopped \
  -p 3000:3000 \
  -p 2222:22 \
  -v /var/lib/gitea:/data \
  -e USER_UID=1000 \
  -e USER_GID=1000 \
  -e GITEA__database__DB_TYPE=sqlite3 \
  -e GITEA__database__PATH=/data/gitea/gitea.db \
  -e GITEA__server__DOMAIN=git.netgescon.local \
  -e GITEA__server__SSH_DOMAIN=git.netgescon.local \
  -e GITEA__server__ROOT_URL=http://$VM_IP:3000/ \
  gitea/gitea:1.21.0

echo "   ✅ Gitea installato e avviato"

# === 8. CONFIGURAZIONE FIREWALL ===
echo ""
echo "🔥 8. Configurazione firewall..."

sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 3000/tcp
sudo ufw allow 2222/tcp
sudo ufw --force enable

echo "   ✅ Firewall configurato"

# === 9. CONFIGURAZIONE GIT ===
echo ""
echo "🔧 9. Configurazione Git repository..."

cd $PROJECT_PATH

# Configura Git
git config --global user.name "NetGescon VM Master"
git config --global user.email "master@netgescon.local"

# Se non è un repository, inizializza
if [ ! -d ".git" ]; then
    git init
    git add .
    git commit -m "🚀 NetGescon Master VM - Setup completo con Nginx

📋 Configurazione definitiva:
✅ Nginx + PHP-FPM ottimizzato per Laravel
✅ MySQL database configurato
✅ Gitea server pronto
✅ Firewall e sicurezza
✅ Struttura progetto: $(du -sh . | cut -f1)

📅 $(date '+%Y-%m-%d %H:%M:%S')
🎯 Sistema pronto per sviluppo enterprise"
    echo "   ✅ Repository Git inizializzato"
fi

# === 10. RIEPILOGO FINALE ===
echo ""
echo "📊 === RIEPILOGO SETUP VM MASTER ==="
echo "✅ Sistema aggiornato"
echo "✅ Nginx + PHP-FPM installato (performance ottimali)"  
echo "✅ MySQL database configurato"
echo "✅ Laravel ottimizzato per produzione"
echo "✅ Gitea server operativo"
echo "✅ Firewall configurato"
echo "✅ Git repository pronto"
echo ""

echo "📋 === INFORMAZIONI ACCESSO ==="
echo "🌐 NetGescon: http://$VM_IP"
echo "🏢 Gitea: http://$VM_IP:3000"
echo "📂 Progetto: $PROJECT_PATH"
echo "💾 Spazio occupato: $(du -sh $PROJECT_PATH | cut -f1)"
echo "💽 Spazio disponibile: $(df -h / | tail -1 | awk '{print $4}')"
echo ""

echo "🔄 === STATUS SERVIZI ==="
echo "Nginx: $(systemctl is-active nginx)"
echo "MySQL: $(systemctl is-active mysql)"
echo "PHP-FPM: $(systemctl is-active php8.1-fpm)"
echo "Docker: $(systemctl is-active docker)"
echo "Gitea: $(docker ps --filter name=gitea --format "{{.Status}}" | head -1 || echo 'Starting...')"
echo ""

echo "📋 === PROSSIMI PASSI ==="
echo "1. 🌐 Testare NetGescon: http://$VM_IP"
echo "2. 🏢 Configurare Gitea: http://$VM_IP:3000"
echo "3. 📦 Creare repository in Gitea"
echo "4. 🔄 Push codice da locale a Gitea"
echo "5. 🚀 Iniziare sviluppo su VM Linux nativa"
echo ""

echo "🎯 Setup VM Master completato con successo!"
echo "📅 $(date '+%Y-%m-%d %H:%M:%S')"
