# Fix NUL device references in DOS BAT files
# Replace with DOS 6.22 compatible tests

$BATFiles = @(
    "DEPLOY.BAT",
    "UPDATE.BAT",
    "NWTOC.BAT",
    "CTONW.BAT",
    "CHECKUPD.BAT",
    "AUTOEXEC.BAT",
    "DOSTEST.BAT"
)

Write-Host "[INFO] Fixing NUL device references in BAT files..." -ForegroundColor Cyan
Write-Host ""

foreach ($File in $BATFiles) {
    if (Test-Path $File) {
        Write-Host "Processing: $File"

        $Content = Get-Content $File -Raw
        $OriginalSize = $Content.Length

        # Fix 1: Replace "T: 2>NUL" with proper drive test
        $Content = $Content -replace '([A-Z]:)\s+2>NUL', 'DIR $1\ >nul'

        # Fix 2: Replace "IF NOT EXIST X:\NUL" with "IF NOT EXIST X:\*.*"
        $Content = $Content -replace 'IF NOT EXIST ([A-Z]:\\)NUL', 'IF NOT EXIST $1*.*'

        # Fix 3: Replace "IF NOT EXIST path\NUL" directory tests with proper test
        # This matches patterns like "C:\BAT\NUL" or "T:\COMMON\NUL"
        $Content = $Content -replace 'IF NOT EXIST ([A-Z]:\\[^\\]+(?:\\[^\\]+)*)\\NUL', 'IF NOT EXIST $1\*.*'

        # Fix 4: Replace "IF EXIST path\NUL" with proper test
        $Content = $Content -replace 'IF EXIST ([A-Z]:\\[^\\]+(?:\\[^\\]+)*)\\NUL', 'IF EXIST $1\*.*'

        $NewSize = $Content.Length

        if ($NewSize -ne $OriginalSize) {
            # Verify still has CRLF
            if ($Content -match "`r`n") {
                Set-Content $File -Value $Content -NoNewline
                Write-Host "  [OK] Fixed NUL references (CRLF preserved)" -ForegroundColor Green
            } else {
                Write-Host "  [ERROR] CRLF lost during fix!" -ForegroundColor Red
            }
        } else {
            Write-Host "  [OK] No NUL references found" -ForegroundColor Gray
        }

        Write-Host ""
    } else {
        Write-Host "[WARNING] $File not found" -ForegroundColor Yellow
        Write-Host ""
    }
}

Write-Host "[SUCCESS] NUL reference fixes complete" -ForegroundColor Green
Write-Host ""
Write-Host "Changes made:"
Write-Host "  - 'T: 2>NUL' → 'DIR T:\ >nul'"
Write-Host "  - 'IF NOT EXIST T:\NUL' → 'IF NOT EXIST T:\*.*'"
Write-Host "  - 'IF NOT EXIST path\NUL' → 'IF NOT EXIST path\*.*'"
Write-Host ""
Write-Host "Note: These tests are DOS 6.22 compatible"
