Write-Host "Connecting to i9-13ks..."

try {
    $remoteCommand = @'
Write-Host "Checking current network connections..."
net use

Write-Host "`nDisconnecting from NEXUS shares..."
# First disconnect from specific NEXUS shares
net use \\NEXUS\amazon /delete /y 2>$null
net use \\NEXUS\flamenco /delete /y 2>$null
# Then disconnect any mapped drives
net use A: /delete /y 2>$null
net use F: /delete /y 2>$null
Write-Host "Existing NEXUS connections cleared."

Write-Host "`nMapping network drives..."
Write-Host "Connecting drives to NEXUS..."

# First connect to the share without a drive letter
Write-Host "Establishing initial NEXUS connection..."
net use \\NEXUS\amazon /user:Nathan /persistent:yes
if ($LASTEXITCODE -eq 0) {
    Write-Host "Initial NEXUS connection established."
    Start-Sleep -Seconds 2

    Write-Host "`nMapping A: drive..."
    net use A: \\NEXUS\amazon /persistent:yes
    if ($LASTEXITCODE -eq 0) {
        Write-Host "A: drive connected successfully."
        
        Write-Host "`nMapping F: drive..."
        net use F: \\NEXUS\flamenco /persistent:yes
        if ($LASTEXITCODE -eq 0) {
            Write-Host "F: drive connected successfully."
            
            # Copy files from C:\nexus\amazon to F:\renders
            Write-Host "`nCopying files..."
            robocopy "C:\nexus\amazon" "F:\renders" /E /MOVE
            
            Write-Host "Operation completed successfully!"
            
            # Delete the C:\NEXUS directory
            Write-Host "`nDeleting C:\NEXUS directory..."
            rmdir /s /q "C:\NEXUS"
            if ($LASTEXITCODE -eq 0) {
                Write-Host "C:\NEXUS directory deleted successfully."
            } else {
                Write-Host "Failed to delete C:\NEXUS directory" -ForegroundColor Red
            }
        } else {
            Write-Host "Failed to connect F: drive" -ForegroundColor Red
        }
    } else {
        Write-Host "Failed to connect A: drive" -ForegroundColor Red
    }
} else {
    Write-Host "Failed to establish initial NEXUS connection" -ForegroundColor Red
}

Write-Host "`nVerifying connections..."
net use

Write-Host "`nPress Enter to continue..."
Read-Host
'@

    # Encode the command to handle special characters
    $bytes = [System.Text.Encoding]::Unicode.GetBytes($remoteCommand)
    $encodedCommand = [Convert]::ToBase64String($bytes)
    
    # Execute the encoded command on the remote machine
    ssh -t i9-13ks "powershell -EncodedCommand $encodedCommand"

} catch {
    Write-Host "`nAn error occurred:" -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Red
}

Write-Host "`nPress Enter to exit..."
Read-Host 