# =============================================================================
# Script di Sincronizzazione NetGescon - Windows PowerShell
# =============================================================================
# Descrizione: Sincronizza files, migrations e updates tra Windows e Linux
# Autore: Sistema NetGescon
# Data: $(Get-Date -Format "yyyy-MM-dd")
# =============================================================================

# Configurazione
$LOCAL_PROJECT_PATH = "U:\home\michele\netgescon\netgescon-laravel"
$REMOTE_HOST = "192.168.0.43"
$REMOTE_USER = "michele"
$REMOTE_PATH = "/var/www/netgescon"
$LOG_FILE = "C:\temp\netgescon_sync_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"

# Assicurati che la directory dei log esista
$logDir = Split-Path $LOG_FILE
if (!(Test-Path $logDir)) {
    New-Item -ItemType Directory -Path $logDir -Force
}

# Logging functions
function Write-Log {
    param([string]$Message, [string]$Level = "INFO")
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] $Message"
    
    switch ($Level) {
        "ERROR" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "SUCCESS" { Write-Host $logEntry -ForegroundColor Green }
        default { Write-Host $logEntry -ForegroundColor Cyan }
    }
    
    Add-Content -Path $LOG_FILE -Value $logEntry
}

# Verifica connessione SSH
function Test-SSHConnection {
    Write-Log "Verifico connessione SSH a $REMOTE_HOST..."
    
    try {
        $result = ssh -o ConnectTimeout=5 -o BatchMode=yes "$REMOTE_USER@$REMOTE_HOST" "exit" 2>$null
        if ($LASTEXITCODE -eq 0) {
            Write-Log "Connessione SSH OK" "SUCCESS"
            return $true
        } else {
            Write-Log "Connessione SSH fallita" "ERROR"
            return $false
        }
    } catch {
        Write-Log "Errore durante test connessione SSH: $_" "ERROR"
        return $false
    }
}

# Backup remoto
function New-RemoteBackup {
    Write-Log "Creo backup remoto..."
    
    $backupCommand = @"
cd $REMOTE_PATH
tar -czf /tmp/netgescon_backup_`$(date +%Y%m%d_%H%M%S).tar.gz \
    database/migrations/ \
    database/seeders/ \
    app/ \
    config/ \
    .env
"@
    
    ssh "$REMOTE_USER@$REMOTE_HOST" $backupCommand
    
    if ($LASTEXITCODE -eq 0) {
        Write-Log "Backup remoto creato" "SUCCESS"
        return $true
    } else {
        Write-Log "Errore creazione backup remoto" "ERROR"
        return $false
    }
}

# Sincronizza migrations tramite SCP
function Sync-Migrations {
    Write-Log "Sincronizzando migrations..."
    
    # Usa SCP per Windows
    scp -r "$LOCAL_PROJECT_PATH\database\migrations\*" "$REMOTE_USER@$REMOTE_HOST`:$REMOTE_PATH/database/migrations/"
    
    if ($LASTEXITCODE -eq 0) {
        Write-Log "Migrations sincronizzate" "SUCCESS"
        return $true
    } else {
        Write-Log "Errore sincronizzazione migrations" "ERROR"
        return $false
    }
}

# Sincronizza seeders
function Sync-Seeders {
    Write-Log "Sincronizzando seeders..."
    
    scp -r "$LOCAL_PROJECT_PATH\database\seeders\*" "$REMOTE_USER@$REMOTE_HOST`:$REMOTE_PATH/database/seeders/"
    
    if ($LASTEXITCODE -eq 0) {
        Write-Log "Seeders sincronizzati" "SUCCESS"
        return $true
    } else {
        Write-Log "Errore sincronizzazione seeders" "ERROR"
        return $false
    }
}

# Esegui migrations remote
function Invoke-RemoteMigrations {
    Write-Log "Eseguo migrations remote..."
    
    ssh "$REMOTE_USER@$REMOTE_HOST" "cd $REMOTE_PATH && php artisan migrate --force"
    
    if ($LASTEXITCODE -eq 0) {
        Write-Log "Migrations remote eseguite" "SUCCESS"
        return $true
    } else {
        Write-Log "Errore esecuzione migrations remote" "ERROR"
        return $false
    }
}

# Esegui seeding remoto
function Invoke-RemoteSeeding {
    Write-Log "Eseguo seeding remoto..."
    
    ssh "$REMOTE_USER@$REMOTE_HOST" "cd $REMOTE_PATH && php artisan db:seed --force"
    
    if ($LASTEXITCODE -eq 0) {
        Write-Log "Seeding remoto eseguito" "SUCCESS"
        return $true
    } else {
        Write-Log "Seeding remoto con errori (potrebbero essere normali)" "WARNING"
        return $true
    }
}

# Restart services
function Restart-RemoteServices {
    Write-Log "Riavvio servizi remoti..."
    
    ssh "$REMOTE_USER@$REMOTE_HOST" "sudo systemctl restart nginx && sudo systemctl restart php8.2-fpm"
    
    if ($LASTEXITCODE -eq 0) {
        Write-Log "Servizi riavviati" "SUCCESS"
        return $true
    } else {
        Write-Log "Errore riavvio servizi" "ERROR"
        return $false
    }
}

# Menu principale
function Show-Menu {
    Write-Host ""
    Write-Host "=== NetGescon Sync Tool ===" -ForegroundColor Blue
    Write-Host "1. Sincronizza solo migrations"
    Write-Host "2. Sincronizza migrations + seeders"
    Write-Host "3. Sincronizza + esegui migrations"
    Write-Host "4. Sincronizza + esegui migrations + seeding"
    Write-Host "5. Full sync + restart services"
    Write-Host "6. Solo backup remoto"
    Write-Host "7. Verifica connessione"
    Write-Host "8. Visualizza log"
    Write-Host "0. Esci"
    Write-Host ""
}

# Main script
function Main {
    Write-Log "Avvio NetGescon Sync Tool" "SUCCESS"
    
    while ($true) {
        Show-Menu
        $choice = Read-Host "Scegli un'opzione"
        
        switch ($choice) {
            "1" {
                if (Test-SSHConnection) {
                    New-RemoteBackup
                    Sync-Migrations
                }
            }
            "2" {
                if (Test-SSHConnection) {
                    New-RemoteBackup
                    Sync-Migrations
                    Sync-Seeders
                }
            }
            "3" {
                if (Test-SSHConnection) {
                    New-RemoteBackup
                    Sync-Migrations
                    Invoke-RemoteMigrations
                }
            }
            "4" {
                if (Test-SSHConnection) {
                    New-RemoteBackup
                    Sync-Migrations
                    Sync-Seeders
                    Invoke-RemoteMigrations
                    Invoke-RemoteSeeding
                }
            }
            "5" {
                if (Test-SSHConnection) {
                    New-RemoteBackup
                    Sync-Migrations
                    Sync-Seeders
                    Invoke-RemoteMigrations
                    Invoke-RemoteSeeding
                    Restart-RemoteServices
                }
            }
            "6" {
                if (Test-SSHConnection) {
                    New-RemoteBackup
                }
            }
            "7" {
                Test-SSHConnection
            }
            "8" {
                if (Test-Path $LOG_FILE) {
                    Get-Content $LOG_FILE | Select-Object -Last 20
                } else {
                    Write-Host "Log file non trovato" -ForegroundColor Yellow
                }
            }
            "0" {
                Write-Log "Arrivederci!" "SUCCESS"
                break
            }
            default {
                Write-Log "Opzione non valida" "ERROR"
            }
        }
        
        Write-Host ""
        Write-Host "Premi ENTER per continuare..." -ForegroundColor Yellow
        Read-Host
    }
}

# Esegui main
Main
