#!/bin/bash
# 📦 NETGESCON - SISTEMA DISTRIBUZIONE E PACKAGING
# Creato: 19/07/2025 - Sistema Distribuzione Michele + AI

set -e

echo "📦 === NETGESCON - SISTEMA DISTRIBUZIONE ==="
echo "📅 $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

# === CONFIGURAZIONI ===
PROJECT_ROOT="/home/michele/netgescon"
BUILD_DIR="/tmp/netgescon-build"
DIST_DIR="/var/www/netgescon-dist"
VERSION_FILE="$PROJECT_ROOT/docs/versione/VERSION.txt"

# === FUNZIONI ===

# Crea directory di build
prepare_build_env() {
    echo "🏗️ Preparazione ambiente build..."
    
    rm -rf "$BUILD_DIR"
    mkdir -p "$BUILD_DIR"
    mkdir -p "$DIST_DIR"/{packages,docker,vm-templates,updates}
    
    echo "   ✅ Ambiente build preparato"
}

# Build pacchetto DEB
build_deb_package() {
    local version=$1
    echo ""
    echo "📦 Build pacchetto DEB..."
    
    local deb_dir="$BUILD_DIR/netgescon-deb"
    mkdir -p "$deb_dir"/{DEBIAN,usr/share/netgescon,etc/netgescon,var/log/netgescon}
    
    # Control file
    cat > "$deb_dir/DEBIAN/control" << EOF
Package: netgescon
Version: $version
Section: web
Priority: optional
Architecture: amd64
Depends: php8.1, nginx, mysql-server
Maintainer: NetGescon Team <info@netgescon.it>
Description: NetGescon - Sistema Gestionale Condomini
 Sistema completo per la gestione di condomini con interfaccia web
 moderna e funzionalità avanzate per amministratori immobiliari.
EOF

    # Scripts di installazione
    cat > "$deb_dir/DEBIAN/postinst" << 'EOF'
#!/bin/bash
set -e

# Configurazione database
systemctl start mysql
mysql -e "CREATE DATABASE IF NOT EXISTS netgescon;"
mysql -e "CREATE USER IF NOT EXISTS 'netgescon'@'localhost' IDENTIFIED BY 'netgescon2025';"
mysql -e "GRANT ALL PRIVILEGES ON netgescon.* TO 'netgescon'@'localhost';"

# Configurazione nginx
systemctl enable nginx
systemctl start nginx

# Permessi
chown -R www-data:www-data /usr/share/netgescon
chmod -R 755 /usr/share/netgescon

echo "✅ NetGescon installato con successo!"
echo "🌐 Apri: http://localhost/netgescon"
EOF

    chmod +x "$deb_dir/DEBIAN/postinst"
    
    # Copia file applicazione
    cp -r "$PROJECT_ROOT/netgescon-laravel" "$deb_dir/usr/share/netgescon/"
    cp -r "$PROJECT_ROOT/docs" "$deb_dir/usr/share/netgescon/"
    
    # Build DEB
    dpkg-deb --build "$deb_dir" "$DIST_DIR/packages/netgescon_${version}_amd64.deb"
    
    echo "   ✅ Pacchetto DEB creato: netgescon_${version}_amd64.deb"
}

# Build Docker image
build_docker_image() {
    local version=$1
    echo ""
    echo "🐳 Build Docker image..."
    
    local docker_dir="$BUILD_DIR/netgescon-docker"
    mkdir -p "$docker_dir"
    
    # Dockerfile
    cat > "$docker_dir/Dockerfile" << 'EOF'
FROM php:8.1-apache

# Installa dipendenze
RUN apt-get update && apt-get install -y \
    libpng-dev \
    libjpeg-dev \
    libfreetype6-dev \
    libzip-dev \
    libonig-dev \
    libxml2-dev \
    zip \
    unzip \
    git \
    curl \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-install pdo pdo_mysql mbstring zip exif pcntl bcmath opcache

# Installa Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Copia applicazione
COPY netgescon-laravel /var/www/html/
COPY docs /var/www/html/docs/

# Configurazione Apache
RUN a2enmod rewrite
COPY apache-config.conf /etc/apache2/sites-available/000-default.conf

# Permessi
RUN chown -R www-data:www-data /var/www/html \
    && chmod -R 755 /var/www/html

# Installa dipendenze Laravel
WORKDIR /var/www/html
RUN composer install --no-dev --optimize-autoloader

# Script di avvio
COPY start.sh /start.sh
RUN chmod +x /start.sh

EXPOSE 80
CMD ["/start.sh"]
EOF

    # Configurazione Apache
    cat > "$docker_dir/apache-config.conf" << 'EOF'
<VirtualHost *:80>
    DocumentRoot /var/www/html/public
    
    <Directory /var/www/html/public>
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
EOF

    # Script di avvio
    cat > "$docker_dir/start.sh" << 'EOF'
#!/bin/bash

# Genera APP_KEY se non presente
if [ ! -f .env ]; then
    cp .env.example .env
    php artisan key:generate
fi

# Migrazioni database
php artisan migrate --force

# Avvia Apache
apache2-foreground
EOF

    # Copia file applicazione
    cp -r "$PROJECT_ROOT/netgescon-laravel" "$docker_dir/"
    cp -r "$PROJECT_ROOT/docs" "$docker_dir/"
    
    # Build immagine
    cd "$docker_dir"
    docker build -t "netgescon:$version" .
    docker tag "netgescon:$version" "netgescon:latest"
    
    # Salva immagine
    docker save "netgescon:$version" | gzip > "$DIST_DIR/docker/netgescon-$version.tar.gz"
    
    echo "   ✅ Docker image creata: netgescon:$version"
}

# Crea template VM
create_vm_template() {
    local version=$1
    echo ""
    echo "💿 Creazione template VM..."
    
    # Script di setup VM
    cat > "$DIST_DIR/vm-templates/setup-netgescon-vm.sh" << EOF
#!/bin/bash
# Setup NetGescon VM Template v$version

set -e

echo "💿 === SETUP NETGESCON VM v$version ==="

# Update sistema
apt update && apt upgrade -y

# Installa stack LAMP
apt install -y apache2 mysql-server php8.1 php8.1-mysql php8.1-xml php8.1-mbstring php8.1-zip php8.1-gd php8.1-curl

# Installa Composer
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# Installa NetGescon
wget -O /tmp/netgescon.deb https://dist.netgescon.it/packages/netgescon_${version}_amd64.deb
dpkg -i /tmp/netgescon.deb || apt-get install -f

# Configurazione automatica
systemctl enable apache2 mysql
systemctl start apache2 mysql

echo "✅ NetGescon VM v$version configurata!"
echo "🌐 Accesso: http://\$(hostname -I | awk '{print \$1}')/netgescon"
EOF

    chmod +x "$DIST_DIR/vm-templates/setup-netgescon-vm.sh"
    
    echo "   ✅ Template VM creato"
}

# Sistema aggiornamenti automatici
create_update_system() {
    local version=$1
    echo ""
    echo "🔄 Sistema aggiornamenti automatici..."
    
    # Script client di aggiornamento
    cat > "$DIST_DIR/updates/netgescon-updater.sh" << 'EOF'
#!/bin/bash
# NetGescon Auto-Updater Client

set -e

UPDATE_SERVER="https://dist.netgescon.it"
CURRENT_VERSION_FILE="/usr/share/netgescon/VERSION"
LOG_FILE="/var/log/netgescon/updater.log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

check_updates() {
    local current_version=$(cat "$CURRENT_VERSION_FILE" 2>/dev/null || echo "0.0.0")
    local latest_version=$(curl -s "$UPDATE_SERVER/latest-version.txt")
    
    log "Versione corrente: $current_version"
    log "Versione disponibile: $latest_version"
    
    if [ "$current_version" != "$latest_version" ]; then
        log "🔄 Aggiornamento disponibile!"
        return 0
    else
        log "✅ Sistema aggiornato"
        return 1
    fi
}

download_update() {
    local version=$1
    local temp_dir="/tmp/netgescon-update-$version"
    
    log "📦 Download aggiornamento v$version..."
    
    mkdir -p "$temp_dir"
    cd "$temp_dir"
    
    wget "$UPDATE_SERVER/packages/netgescon_${version}_amd64.deb"
    
    log "✅ Download completato"
}

install_update() {
    local version=$1
    
    log "🔄 Installazione aggiornamento v$version..."
    
    # Backup
    tar -czf "/backup/netgescon-backup-$(date +%Y%m%d-%H%M).tar.gz" /usr/share/netgescon
    
    # Installa nuovo pacchetto
    dpkg -i "/tmp/netgescon-update-$version/netgescon_${version}_amd64.deb"
    
    # Riavvia servizi
    systemctl restart apache2
    
    log "✅ Aggiornamento completato a v$version"
}

# Controllo automatico
if check_updates; then
    latest_version=$(curl -s "$UPDATE_SERVER/latest-version.txt")
    download_update "$latest_version"
    install_update "$latest_version"
fi
EOF

    chmod +x "$DIST_DIR/updates/netgescon-updater.sh"
    
    # File versione latest
    echo "$version" > "$DIST_DIR/updates/latest-version.txt"
    
    echo "   ✅ Sistema aggiornamenti creato"
}

# === COMANDO PRINCIPALE ===

case "${1:-help}" in

    "full")
        echo "🚀 Build completo di tutti i pacchetti..."
        
        if [ ! -f "$VERSION_FILE" ]; then
            echo "❌ File versione non trovato: $VERSION_FILE"
            exit 1
        fi
        
        version=$(cat "$VERSION_FILE")
        echo "📋 Versione: $version"
        
        prepare_build_env
        build_deb_package "$version"
        build_docker_image "$version"
        create_vm_template "$version"
        create_update_system "$version"
        
        echo ""
        echo "📊 === RIEPILOGO BUILD ==="
        echo "✅ Pacchetto DEB: $DIST_DIR/packages/netgescon_${version}_amd64.deb"
        echo "✅ Docker Image: netgescon:$version"
        echo "✅ Template VM: $DIST_DIR/vm-templates/"
        echo "✅ Sistema Updates: $DIST_DIR/updates/"
        ;;

    "deb")
        version=$(cat "$VERSION_FILE")
        prepare_build_env
        build_deb_package "$version"
        ;;

    "docker")
        version=$(cat "$VERSION_FILE")
        prepare_build_env
        build_docker_image "$version"
        ;;

    "vm")
        version=$(cat "$VERSION_FILE")
        prepare_build_env
        create_vm_template "$version"
        ;;

    "updates")
        version=$(cat "$VERSION_FILE")
        prepare_build_env
        create_update_system "$version"
        ;;

    "publish")
        echo "🌐 Pubblicazione pacchetti..."
        
        # Sincronizza su server distribuzione
        rsync -avz --progress "$DIST_DIR/" root@dist.netgescon.it:/var/www/dist/
        
        echo "   ✅ Pacchetti pubblicati su dist.netgescon.it"
        ;;

    "help"|*)
        echo "📦 === NETGESCON - SISTEMA DISTRIBUZIONE ==="
        echo ""
        echo "🏗️ BUILD:"
        echo "   $0 full        # Build completo (DEB + Docker + VM + Updates)"
        echo "   $0 deb         # Solo pacchetto DEB"
        echo "   $0 docker      # Solo Docker image"
        echo "   $0 vm          # Solo template VM"
        echo "   $0 updates     # Solo sistema aggiornamenti"
        echo ""
        echo "🌐 DISTRIBUZIONE:"
        echo "   $0 publish     # Pubblica su server distribuzione"
        echo ""
        echo "📋 Output in: $DIST_DIR"
        ;;

esac

echo ""
echo "📅 $(date '+%Y-%m-%d %H:%M:%S') - Operazione completata"
