# Simple version - fix specific DOS files on AD2
Write-Host "=== Fixing DOS Files on AD2 ===" -ForegroundColor Cyan
Write-Host ""

# Setup admin credentials
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)

# Known batch file locations on AD2
$filesToCheck = @(
    "C:\Shares\test\COMMON\ProdSW\DEPLOY.BAT",
    "C:\Shares\test\COMMON\ProdSW\NWTOC.BAT",
    "C:\Shares\test\COMMON\ProdSW\CTONW.BAT",
    "C:\Shares\test\COMMON\ProdSW\UPDATE.BAT",
    "C:\Shares\test\COMMON\ProdSW\STAGE.BAT",
    "C:\Shares\test\COMMON\ProdSW\CHECKUPD.BAT",
    "C:\Shares\test\COMMON\DOS\AUTOEXEC.NEW",
    "C:\Shares\test\UPDATE.BAT"
)

Write-Host "Checking and converting DOS batch files on AD2..." -ForegroundColor Yellow
Write-Host ""

Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
    param($files)

    $converted = 0
    $alreadyOK = 0
    $notFound = 0

    foreach ($filePath in $files) {
        $fileName = Split-Path $filePath -Leaf

        if (-not (Test-Path $filePath)) {
            Write-Host "[SKIP] $fileName - Not found" -ForegroundColor Yellow
            $notFound++
            continue
        }

        try {
            # Check current line endings
            $bytes = [System.IO.File]::ReadAllBytes($filePath)
            $hasCRLF = $false

            for ($i = 0; $i -lt ($bytes.Length - 1); $i++) {
                if ($bytes[$i] -eq 13 -and $bytes[$i+1] -eq 10) {
                    $hasCRLF = $true
                    break
                }
            }

            if ($hasCRLF) {
                Write-Host "[OK]   $fileName - Already DOS format (CRLF)" -ForegroundColor Green
                $alreadyOK++
            } else {
                # Convert to DOS format
                $content = Get-Content $filePath -Raw
                $dosContent = $content -replace "`r?`n", "`r`n"
                [System.IO.File]::WriteAllText($filePath, $dosContent, [System.Text.Encoding]::ASCII)

                Write-Host "[CONV] $fileName - Converted to DOS format" -ForegroundColor Cyan
                $converted++
            }
        } catch {
            Write-Host "[ERROR] $fileName - $($_.Exception.Message)" -ForegroundColor Red
        }
    }

    Write-Host ""
    Write-Host "=== Summary ===" -ForegroundColor Cyan
    Write-Host "Already OK:  $alreadyOK" -ForegroundColor Green
    Write-Host "Converted:   $converted" -ForegroundColor Cyan
    Write-Host "Not Found:   $notFound" -ForegroundColor Yellow

} -ArgumentList (,$filesToCheck)
