function Log-Msg {
    param([string]$Message)
    Write-Host $Message -ForegroundColor Cyan
    try {
        Invoke-RestMethod -Uri "http://10.0.10.8:8000/log" -Method Post -Body @{msg=$Message} -UseBasicParsing -ErrorAction SilentlyContinue | Out-Null
    } catch {}
}

Log-Msg "Iniciando script automatizado de SQL Server 2019 Core."

# Habilitar Escritorio Remoto
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -name "fDenyTSConnections" -value 0
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
Log-Msg "RDP (Escritorio Remoto) habilitado en el registro."

# Abrir puertos SQL y Ping
New-NetFirewallRule -DisplayName "SQL Server (TCP 1433)" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433 -Profile Domain,Private
New-NetFirewallRule -DisplayName "SQL Browser (UDP 1434)" -Direction Inbound -Action Allow -Protocol UDP -LocalPort 1434 -Profile Domain,Private
New-NetFirewallRule -DisplayName "Allow ICMPv4-In" -Protocol ICMPv4 -IcmpType 8 -Enabled True -Profile Any -Action Allow
Log-Msg "Reglas de Firewall inyectadas (TCP 1433, UDP 1434, Ping)."

Log-Msg "Buscando la ISO montada de SQL Server en el Virtual CD-ROM..."
$sqlDrive = (Get-Volume | Where-Object { $_.DriveType -eq 'CD-ROM' -and (Test-Path "$($_.DriveLetter):\setup.exe") }).DriveLetter

if ($sqlDrive) {
    Log-Msg "¡ISO de SQL Server detectada exitosamente en la unidad $($sqlDrive[0]):\!"
    Log-Msg "Comenzando volcado desatendido de SQL Server... (esto tomara de 5 a 15 minutos en background)."
    
    $setupPath = "$($sqlDrive[0]):\setup.exe"
    $process = Start-Process -FilePath $setupPath -ArgumentList "/Q /ACTION=INSTALL /FEATURES=SQLEngine /INSTANCENAME=MSSQLSERVER /SQLSVCACCOUNT=`"NT Service\MSSQLSERVER`" /SQLSYSADMINACCOUNTS=`"DASUTEN\Administrator`" /SECURITYMODE=SQL /SAPWD=`"Lhsurnm`$77NS8.`" /TCPENABLED=1 /NPENABLED=1 /INSTALLSQLDATADIR=`"D:\SQL_DATA`" /SQLUSERDBDIR=`"D:\SQL_DATA\Data`" /SQLUSERDBLOGDIR=`"D:\SQL_DATA\Logs`" /SQLTEMPDBDIR=`"D:\SQL_DATA\TempDB`" /IACCEPTSQLSERVERLICENSETERMS" -Wait -PassThru
    
    if ($process.ExitCode -eq 0) {
        Log-Msg "¡INSTALACION DE SQL SERVER COMPLETADA CON EXITO (Exit 0)!"
    } else {
        Log-Msg "ADVERTENCIA: La instalacion de SQL finalizo con codigo de error: $($process.ExitCode). Posible fallo de idioma (Language Mismatch)."
        Log-Msg "Buscando log de instalacion de SQL Server para diagnostico detallado..."
        
        $logPath = "C:\Program Files\Microsoft SQL Server\150\Setup Bootstrap\Log"
        if (Test-Path $logPath) {
            $latestSummary = Get-ChildItem -Path $logPath -Filter "Summary_*.txt" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
            if ($latestSummary) {
                $content = Get-Content $latestSummary.FullName -Tail 20 | Out-String
                Log-Msg "================ DETALLE DE ERROR DE SQL SERVER ================"
                # Post log content carefully
                try {
                    Invoke-RestMethod -Uri "http://10.0.10.8:8000/log" -Method Post -Body @{msg=$content} -UseBasicParsing -ErrorAction SilentlyContinue | Out-Null
                } catch {}
                Log-Msg "==============================================================="
            } else {
                Log-Msg "No se encontro Summary.txt en la ruta de logs de SQL."
            }
        } else {
            Log-Msg "No se genero el directorio de logs de SQL Server."
        }
    }
} else {
    Log-Msg "ERROR CATASTROFICO: No se encontro el instalador de SQL Server (setup.exe) en ninguna unidad de CD-ROM."
    Log-Msg "Por favor inserta correctamente la ISO de SQL Server en Proxmox y vuelve a ejecutar este script."
}

Log-Msg "Ejecucion del script finalizada. Devolviendo control de consola."
