#!/bin/bash

# =============================================================================
# Script di Sincronizzazione NetGescon - Windows WSL → Linux Remote
# =============================================================================
# Descrizione: Sincronizza files, migrations e updates tra macchina locale e remota
# Autore: Sistema NetGescon
# Data: $(date +%Y-%m-%d)
# =============================================================================

# Configurazione
LOCAL_PROJECT_PATH="/mnt/u/home/michele/netgescon/netgescon-laravel"
REMOTE_HOST="192.168.0.43"
REMOTE_USER="michele"
REMOTE_PATH="/var/www/netgescon"
LOG_FILE="/tmp/netgescon_sync_$(date +%Y%m%d_%H%M%S).log"

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

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

error() {
    echo -e "${RED}[ERROR]${NC} $1" | tee -a "$LOG_FILE"
}

warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1" | tee -a "$LOG_FILE"
}

info() {
    echo -e "${BLUE}[INFO]${NC} $1" | tee -a "$LOG_FILE"
}

# Verifica connessione SSH
check_ssh_connection() {
    info "Verifico connessione SSH a $REMOTE_HOST..."
    if ssh -o ConnectTimeout=5 -o BatchMode=yes "$REMOTE_USER@$REMOTE_HOST" exit 2>/dev/null; then
        log "✅ Connessione SSH OK"
        return 0
    else
        error "❌ Connessione SSH fallita"
        return 1
    fi
}

# Backup remoto
create_remote_backup() {
    info "Creo backup remoto..."
    ssh "$REMOTE_USER@$REMOTE_HOST" "
        cd $REMOTE_PATH
        tar -czf /tmp/netgescon_backup_$(date +%Y%m%d_%H%M%S).tar.gz \
            database/migrations/ \
            database/seeders/ \
            app/ \
            config/ \
            .env
    "
    log "✅ Backup remoto creato"
}

# Sincronizza migrations
sync_migrations() {
    info "Sincronizzando migrations..."
    rsync -avz --delete \
        "$LOCAL_PROJECT_PATH/database/migrations/" \
        "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/database/migrations/"
    
    if [ $? -eq 0 ]; then
        log "✅ Migrations sincronizzate"
        return 0
    else
        error "❌ Errore sincronizzazione migrations"
        return 1
    fi
}

# Sincronizza seeders
sync_seeders() {
    info "Sincronizzando seeders..."
    rsync -avz --delete \
        "$LOCAL_PROJECT_PATH/database/seeders/" \
        "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH/database/seeders/"
    
    if [ $? -eq 0 ]; then
        log "✅ Seeders sincronizzati"
        return 0
    else
        error "❌ Errore sincronizzazione seeders"
        return 1
    fi
}

# Esegui migrations remote
run_remote_migrations() {
    info "Eseguo migrations remote..."
    ssh "$REMOTE_USER@$REMOTE_HOST" "
        cd $REMOTE_PATH
        php artisan migrate --force
    "
    
    if [ $? -eq 0 ]; then
        log "✅ Migrations remote eseguite"
        return 0
    else
        error "❌ Errore esecuzione migrations remote"
        return 1
    fi
}

# Esegui seeding remoto
run_remote_seeding() {
    info "Eseguo seeding remoto..."
    ssh "$REMOTE_USER@$REMOTE_HOST" "
        cd $REMOTE_PATH
        php artisan db:seed --force
    "
    
    if [ $? -eq 0 ]; then
        log "✅ Seeding remoto eseguito"
        return 0
    else
        warning "⚠️  Seeding remoto con errori (potrebbero essere normali)"
        return 0
    fi
}

# Restart services
restart_remote_services() {
    info "Riavvio servizi remoti..."
    ssh "$REMOTE_USER@$REMOTE_HOST" "
        sudo systemctl restart nginx
        sudo systemctl restart php8.2-fpm
    "
    log "✅ Servizi riavviati"
}

# Menu principale
show_menu() {
    echo -e "\n${BLUE}=== NetGescon Sync Tool ===${NC}"
    echo "1. Sincronizza solo migrations"
    echo "2. Sincronizza migrations + seeders"
    echo "3. Sincronizza + esegui migrations"
    echo "4. Sincronizza + esegui migrations + seeding"
    echo "5. Full sync + restart services"
    echo "6. Solo backup remoto"
    echo "7. Verifica connessione"
    echo "0. Esci"
    echo -n "Scegli un'opzione: "
}

# Main script
main() {
    log "🚀 Avvio NetGescon Sync Tool"
    
    while true; do
        show_menu
        read -r choice
        
        case $choice in
            1)
                if check_ssh_connection; then
                    create_remote_backup
                    sync_migrations
                fi
                ;;
            2)
                if check_ssh_connection; then
                    create_remote_backup
                    sync_migrations
                    sync_seeders
                fi
                ;;
            3)
                if check_ssh_connection; then
                    create_remote_backup
                    sync_migrations
                    run_remote_migrations
                fi
                ;;
            4)
                if check_ssh_connection; then
                    create_remote_backup
                    sync_migrations
                    sync_seeders
                    run_remote_migrations
                    run_remote_seeding
                fi
                ;;
            5)
                if check_ssh_connection; then
                    create_remote_backup
                    sync_migrations
                    sync_seeders
                    run_remote_migrations
                    run_remote_seeding
                    restart_remote_services
                fi
                ;;
            6)
                if check_ssh_connection; then
                    create_remote_backup
                fi
                ;;
            7)
                check_ssh_connection
                ;;
            0)
                log "👋 Arrivederci!"
                exit 0
                ;;
            *)
                error "Opzione non valida"
                ;;
        esac
        
        echo -e "\n${YELLOW}Premi ENTER per continuare...${NC}"
        read -r
    done
}

# Esegui main
main "$@"
