#!/bin/bash
# setup-netgescon-ubuntu2404.sh - Setup ottimizzato per Ubuntu 24.04 LTS

set -e

echo "🚀 NetGescon Setup Script - Ubuntu 24.04 LTS"
echo "=============================================="

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

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"; }

# Verifica versione Ubuntu
if ! grep -q "24.04" /etc/os-release; then
    log_error "Questo script è ottimizzato per Ubuntu 24.04 LTS"
    exit 1
fi

log_step "1/12 Aggiornamento sistema Ubuntu 24.04..."
sudo apt update && sudo apt upgrade -y

log_step "2/12 Installazione pacchetti base..."
sudo apt install -y curl wget git unzip vim htop tree net-tools openssh-server ufw \
software-properties-common apt-transport-https ca-certificates gnupg lsb-release

log_step "3/12 Configurazione firewall UFW..."
sudo ufw --force enable
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 8000/tcp
log_info "Firewall configurato per NetGescon"

log_step "4/12 Installazione PHP 8.3 (Ubuntu 24.04 native)..."
sudo apt install -y php8.3 php8.3-fpm php8.3-cli php8.3-common php8.3-mysql \
php8.3-zip php8.3-gd php8.3-mbstring php8.3-curl php8.3-xml php8.3-bcmath \
php8.3-intl php8.3-sqlite3 php8.3-redis php8.3-imagick php8.3-opcache

# Configurazione PHP ottimizzata
sudo tee /etc/php/8.3/fpm/conf.d/99-netgescon.ini > /dev/null <<EOF
; NetGescon PHP Configuration
memory_limit = 512M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300
max_input_vars = 3000
opcache.enable = 1
opcache.memory_consumption = 128
opcache.interned_strings_buffer = 8
opcache.max_accelerated_files = 4000
opcache.revalidate_freq = 2
opcache.fast_shutdown = 1
EOF

PHP_VERSION=$(php -v | head -1 | cut -d' ' -f2)
log_info "PHP installato: $PHP_VERSION"

log_step "5/12 Installazione Composer..."
cd /tmp
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo chmod +x /usr/local/bin/composer

COMPOSER_VERSION=$(composer --version 2>/dev/null | cut -d' ' -f3)
log_info "Composer installato: $COMPOSER_VERSION"

log_step "6/12 Installazione Node.js 20 LTS..."
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

NODE_VERSION=$(node --version)
NPM_VERSION=$(npm --version)
log_info "Node.js: $NODE_VERSION, npm: $NPM_VERSION"

log_step "7/12 Installazione MySQL 8.0..."
sudo apt install -y mysql-server mysql-client

# Configurazione MySQL ottimizzata per NetGescon
sudo tee /etc/mysql/mysql.conf.d/99-netgescon.cnf > /dev/null <<EOF
[mysqld]
# NetGescon MySQL Configuration
innodb_buffer_pool_size = 2G
innodb_log_file_size = 256M
max_connections = 200
query_cache_size = 0
query_cache_type = 0
tmp_table_size = 64M
max_heap_table_size = 64M
innodb_file_per_table = 1
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
EOF

sudo systemctl restart mysql
log_info "MySQL configurato per NetGescon"

log_step "8/12 Installazione Nginx..."
sudo apt install -y nginx

# Configurazione Nginx base
sudo tee /etc/nginx/conf.d/netgescon-global.conf > /dev/null <<EOF
# NetGescon Global Nginx Configuration
client_max_body_size 64M;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
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

sudo systemctl enable nginx
sudo systemctl start nginx
log_info "Nginx installato e configurato"

log_step "9/12 Installazione Redis (caching)..."
sudo apt install -y redis-server
sudo systemctl enable redis-server
sudo systemctl start redis-server
log_info "Redis installato per caching Laravel"

log_step "10/12 Creazione directory progetto..."
sudo mkdir -p /var/www/netgescon
sudo chown -R $USER:www-data /var/www/netgescon
sudo chmod -R 755 /var/www/netgescon
log_info "Directory NetGescon: /var/www/netgescon"

log_step "11/12 Configurazione servizi..."
sudo systemctl enable php8.3-fpm
sudo systemctl start php8.3-fpm
sudo systemctl enable mysql
sudo systemctl enable nginx

log_step "12/12 Installazione strumenti di monitoraggio..."
sudo apt install -y htop iotop netstat-nat
log_info "Strumenti di sistema installati"

# Informazioni di sistema
echo "=== NetGescon Ubuntu 24.04 Setup Info ===" > ~/netgescon-setup-info.txt
echo "Data installazione: $(date)" >> ~/netgescon-setup-info.txt
echo "Sistema: $(lsb_release -d | cut -f2)" >> ~/netgescon-setup-info.txt
echo "Kernel: $(uname -r)" >> ~/netgescon-setup-info.txt
echo "PHP: $PHP_VERSION" >> ~/netgescon-setup-info.txt
echo "Composer: $COMPOSER_VERSION" >> ~/netgescon-setup-info.txt
echo "Node.js: $NODE_VERSION" >> ~/netgescon-setup-info.txt
echo "NPM: $NPM_VERSION" >> ~/netgescon-setup-info.txt
echo "MySQL: $(mysql --version)" >> ~/netgescon-setup-info.txt
echo "Nginx: $(nginx -v 2>&1)" >> ~/netgescon-setup-info.txt
echo "Redis: $(redis-server --version)" >> ~/netgescon-setup-info.txt

log_info "Setup Ubuntu 24.04 completato! 🎉"
echo ""
echo "═══════════════════════════════════════════════════════"
echo "✅ UBUNTU 24.04 LTS PRONTO PER NETGESCON"
echo "═══════════════════════════════════════════════════════"
echo ""
echo "🔧 SERVIZI INSTALLATI:"
echo "   PHP 8.3 + FPM + OPcache"
echo "   MySQL 8.0 ottimizzato"
echo "   Nginx con configurazione NetGescon"
echo "   Redis per caching"
echo "   Node.js 20 LTS"
echo "   Composer latest"
echo ""
echo "🌐 IP MACCHINA: $(hostname -I | awk '{print $1}')"
echo "📁 DIRECTORY PROGETTO: /var/www/netgescon/"
echo "💾 INFO SISTEMA: ~/netgescon-setup-info.txt"
echo ""
echo "═══════════════════════════════════════════════════════"
echo ""
echo "🔧 NEXT STEPS OBBLIGATORI:"
echo ""
echo "1️⃣  CONFIGURA MYSQL (password sicura):"
echo "    sudo mysql_secure_installation"
echo ""
echo "2️⃣  CREA DATABASE NETGESCON:"
echo "    sudo mysql -u root -p"
echo "    CREATE DATABASE netgescon CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
echo "    CREATE USER 'netgescon_user'@'localhost' IDENTIFIED BY 'NetGescon2024!';"
echo "    GRANT ALL PRIVILEGES ON netgescon.* TO 'netgescon_user'@'localhost';"
echo "    FLUSH PRIVILEGES;"
echo "    EXIT;"
echo ""
echo "3️⃣  TRASFERISCI PROGETTO LARAVEL:"
echo "    Copia netgescon-laravel/ in /var/www/netgescon/"
echo ""
echo "4️⃣  ESEGUI SETUP LARAVEL:"
echo "    ./setup-laravel-ubuntu2404.sh"
echo ""
echo "5️⃣  CONFIGURA NGINX VIRTUAL HOST:"
echo "    ./nginx-config-ubuntu2404.sh"
echo ""

echo "$(date): NetGescon Ubuntu 24.04 setup completato" >> ~/netgescon-setup.log
log_info "Ready per il prossimo step! 🚀"
