# Fix Runtime Library Settings for All Projects
# Changes all Debug configurations to /MDd (MultiThreadedDebugDLL)
# Changes all Release configurations to /MD (MultiThreadedDLL)

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Runtime Library Fix Script" -ForegroundColor Cyan
Write-Host "========================================`n" -ForegroundColor Cyan

$projectFiles = Get-ChildItem -Recurse -Filter "*.vcxproj" | Where-Object {
    $_.Name -notlike "*LUA.vcxproj"  # LUA project may need different settings
}

$totalFiles = $projectFiles.Count
$currentFile = 0

Write-Host "Found $totalFiles project files to process`n" -ForegroundColor Green

foreach ($file in $projectFiles) {
    $currentFile++
    Write-Host "[$currentFile/$totalFiles] Processing: $($file.Name)" -ForegroundColor Yellow

    $content = Get-Content $file.FullName -Raw -Encoding UTF8
    $originalContent = $content

    # Debug configurations: Change to MultiThreadedDebugDLL (/MDd)
    $content = $content -replace '<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>', '<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>'

    # Release configurations: Change to MultiThreadedDLL (/MD)
    $content = $content -replace '<RuntimeLibrary>MultiThreaded</RuntimeLibrary>', '<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>'

    if ($content -ne $originalContent) {
        # Backup original file
        $backupPath = $file.FullName + ".bak"
        Copy-Item $file.FullName $backupPath -Force

        # Save modified content
        [System.IO.File]::WriteAllText($file.FullName, $content, [System.Text.Encoding]::UTF8)
        Write-Host "  -> Modified (backup saved as $($file.Name).bak)" -ForegroundColor Green
    } else {
        Write-Host "  -> No changes needed" -ForegroundColor Gray
    }
}

Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "Summary" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Processed $totalFiles project files" -ForegroundColor Green
Write-Host "`nAll Debug configurations -> /MDd (MultiThreadedDebugDLL)" -ForegroundColor Green
Write-Host "All Release configurations -> /MD (MultiThreadedDLL)" -ForegroundColor Green
Write-Host "`nBackup files created with .bak extension" -ForegroundColor Yellow
Write-Host "`nNext steps:" -ForegroundColor Cyan
Write-Host "1. Close Visual Studio if it's open" -ForegroundColor White
Write-Host "2. Run: Clean solution (delete Intermediate/ folder)" -ForegroundColor White
Write-Host "3. Rebuild solution" -ForegroundColor White
Write-Host "`nPress any key to exit..." -ForegroundColor Gray
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
