# Fix DOS line endings on AD2 for Dataforth DOS system
Write-Host "=== Fixing DOS Files on AD2 (C:\Shares\test\) ===" -ForegroundColor Cyan
Write-Host ""

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

Write-Host "Connecting to AD2..." -ForegroundColor Yellow
Write-Host ""

try {
    $result = Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
        Write-Host "[INFO] Searching for .BAT files in C:\Shares\test\" -ForegroundColor Yellow
        Write-Host ""

        # Find all .BAT files in the test directory
        $batFiles = Get-ChildItem -Path "C:\Shares\test" -Filter "*.BAT" -Recurse -ErrorAction SilentlyContinue

        Write-Host "Found $($batFiles.Count) batch files" -ForegroundColor Cyan
        Write-Host ""

        $needsConversion = @()
        $results = @()

        foreach ($file in $batFiles) {
            try {
                $bytes = [System.IO.File]::ReadAllBytes($file.FullName)
                $hasCRLF = $false
                $hasLF = $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 ($bytes[$i] -eq 10 -and ($i -eq 0 -or $bytes[$i-1] -ne 13)) {
                        $hasLF = $true
                        break
                    }
                }

                $relativePath = $file.FullName.Replace("C:\Shares\test\", "")

                if ($hasCRLF) {
                    $status = "OK"
                    $format = "CRLF (DOS)"
                } elseif ($hasLF) {
                    $status = "NEEDS CONVERSION"
                    $format = "LF (Unix)"
                    $needsConversion += $file
                } else {
                    $status = "EMPTY/SINGLE LINE"
                    $format = "No line endings"
                }

                $results += [PSCustomObject]@{
                    File = $relativePath
                    Status = $status
                    Format = $format
                }

                Write-Host "[$status] $relativePath" -ForegroundColor $(if ($status -eq "OK") { "Green" } elseif ($status -eq "NEEDS CONVERSION") { "Red" } else { "Yellow" })
                Write-Host "         $format" -ForegroundColor Gray
                Write-Host ""
            } catch {
                Write-Host "[ERROR] $($file.Name): $($_.Exception.Message)" -ForegroundColor Red
            }
        }

        # Convert files that need it
        if ($needsConversion.Count -gt 0) {
            Write-Host "=== Converting $($needsConversion.Count) files to DOS format ===" -ForegroundColor Yellow
            Write-Host ""

            $converted = 0
            $errors = 0

            foreach ($file in $needsConversion) {
                try {
                    # Read content
                    $content = Get-Content $file.FullName -Raw

                    # Convert to DOS format (CRLF)
                    $dosContent = $content -replace "`r?`n", "`r`n"

                    # Write back as ASCII (DOS compatible)
                    [System.IO.File]::WriteAllText($file.FullName, $dosContent, [System.Text.Encoding]::ASCII)

                    Write-Host "[OK] $($file.Name)" -ForegroundColor Green
                    $converted++
                } catch {
                    Write-Host "[ERROR] $($file.Name): $($_.Exception.Message)" -ForegroundColor Red
                    $errors++
                }
            }

            Write-Host ""
            Write-Host "=== Conversion Complete ===" -ForegroundColor Green
            Write-Host "Converted: $converted files" -ForegroundColor Green
            if ($errors -gt 0) {
                Write-Host "Errors: $errors files" -ForegroundColor Red
            }
        } else {
            Write-Host "=== All Files OK ===" -ForegroundColor Green
            Write-Host "All batch files already have proper DOS (CRLF) line endings." -ForegroundColor Green
        }

        # Return summary
        return @{
            TotalFiles = $batFiles.Count
            Converted = $needsConversion.Count
            Results = $results
        }
    }

    Write-Host ""
    Write-Host "=== Summary ===" -ForegroundColor Cyan
    Write-Host "Total batch files found: $($result.TotalFiles)" -ForegroundColor White
    Write-Host "Files converted: $($result.Converted)" -ForegroundColor $(if ($result.Converted -gt 0) { "Yellow" } else { "Green" })

} catch {
    Write-Host "[ERROR] Failed to connect to AD2" -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Red
}
