# Importa configurazione
. "$PSScriptRoot\conf.ps1"

$scriptName = $MyInvocation.MyCommand.Name
$logFile = Join-Path $env:logDir "${scriptName}.log"	# for debug
"start" | Out-File -FilePath $logFile

# List of SQL files to execute in order
$sqlFiles = @(
    # "C6SC01_creadb.sql",
    # "C6SC08_creauser.sql",
    # "StampeCentralizzateBackupRidotto.sql",
    # "enable_sa_full.sql",
    # "enable_F701264_full.sql",
    ""
)

$sqlFiles = $sqlFiles[0..($sqlFiles.Count-2)]
Write-Host "Will execute $($sqlFiles.Count) SQL files in order"

foreach ($fileName in $sqlFiles) {
    $fileSql = Join-Path $env:sqlDir $fileName

    if (-not (Test-Path $fileSql)) {
        Write-Host "File not found: $fileSql" -ForegroundColor Red
        continue
    }

    (Get-Date).ToString("yyyy-MM-dd_HH:mm:ss")+" eseguo item: $fileName " | Out-File -FilePath $logFile -Append
    Write-Host "Elaboro $fileSql"
    $fileLog =  Join-Path $env:logDir ($fileName + ".log")
    
    $maxRetries = 3
    $retryCount = 0
    $success = $false
    
    while (-not $success -and $retryCount -lt $maxRetries) {
        # try {
        # Execute the SQL file using sqlcmd
        sqlcmd -S $env:dbHostOutput -U $env:dbUser -P $env:dbPassword -d $env:dbName -i $fileSql >$fileLog 2>&1
        $esitoComando = $LASTEXITCODE
        # $risultato = $risultato.TrimEnd("`r", "`n")
        "logSqlApp: $logSqlApp esitoComando: $esitoComando" | Out-File -FilePath $logFile -Append
            
        IF ( $esitoComando -eq 0 ) 
        {
            "run $fileName " | Out-File -FilePath $logFile -Append
            Remove-Item -Path $fileLog | Out-File -FilePath $logFile -Append
            (Get-Date).ToString("yyyy-MM-dd_HH:mm:ss")+"  item: $fileSql completed risultato in $fileLog " | Out-File -FilePath $logFile -Append
        } else {
            $(Get-Date -Format "yyyy-MM-dd_HH:mm:ss")+" $esitoComando"
            $(Get-Date -Format "yyyy-MM-dd_HH:mm:ss")+" ERROR per $fileSql, risultato in $fileLog " | Out-File -FilePath $logFile -Append
            $(Get-Date -Format "yyyy-MM-dd_HH:mm:ss")+" processo bloccato " | Out-File -FilePath $logFile -Append
            # if ($retryCount -lt $maxRetries - 1) {
            #     $retryCount++
            #     Write-Host "Retry attempt $retryCount after 2 seconds..."
            #     Start-Sleep -Seconds 2
            #     continue
            # }
            exit 1
        }
        $success = $true
    }
    # }
    # catch {
    #     $msg = [string]::Format("Error executing {0}: {1}", $fileName, $_.Exception.Message)
    #     Write-Host $msg -ForegroundColor Red
    # }

    Write-Host "----------------------------------------"
}
"fine lavori"  | Out-File -FilePath $logFile -Append
