# SQL Server connection parameters
$env:compareDir = $PSScriptRoot
$env:workdir = Split-Path -Path $env:compareDir -Parent
$env:logDir  = Join-Path $env:workdir "logs"
$env:scriptDir = Join-Path $env:workdir "script"
if (-not (Test-Path $env:logDir)) {
    New-Item -ItemType Directory -Path $env:logDir | Out-Null
}
$sqlbase = Join-Path $env:workdir "sql"
$env:dbUser = "sa"
$env:dbPassword = "_p1sap1a"
$env:dbHost = "DATABASE_PDC_LOCALE"
$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",
    "dbo.LogN.sql",
    ""
)

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

foreach ($fileName in $sqlFiles) {
    $fileSql = Join-Path $sqlbase $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:dbHost -U $env:dbUser -P $env:dbPassword -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
