@echo off
setlocal EnableExtensions EnableDelayedExpansion
REM ============================================================
REM  FERABYTE REMOTO - seletor de servidor do RustDesk
REM  Uso: duplo clique (abre o menu)
REM       ou: rustdesk_servidor.bat ferabyte   (aplica o servidor Ferabyte)
REM       ou: rustdesk_servidor.bat publico    (volta ao servidor publico)
REM       ou: rustdesk_servidor.bat status     (mostra o servidor atual)
REM       ou: rustdesk_servidor.bat testar     (testa o Ferabyte e o publico)
REM       ou: rustdesk_servidor.bat testar-ferabyte  /  testar-publico
REM ============================================================

REM ---------- CONFIGURE AQUI (a chave e PUBLICA) ----------
set "SERVIDOR=remoto.ferabyte.com.br"
set "CHAVE=RaCS/FxOwcg8Q0OLZSeiu9Aw3QizzDmQWMEPlkx6oic="
REM --------------------------------------------------------

set "RD_BAT=%~f0"
set "RD_ARG=%~1"
set "RD_SERVIDOR=%SERVIDOR%"
set "RD_CHAVE=%CHAVE%"

REM Precisa de administrador (fltmc nao depende do servico "Servidor")
fltmc >nul 2>&1
if errorlevel 1 goto :elevar

title Ferabyte Remoto - RustDesk
mode con: cols=74 lines=30 >nul 2>&1

REM ---------- Cores (so no Windows 10 ou superior) ----------
set "ESC="
ver | findstr /c:" 10.0." >nul 2>&1 && for /f %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a"
set "CT=" & set "CG=" & set "CY=" & set "CR=" & set "CW=" & set "CD=" & set "CX="
if defined ESC (
    set "CT=%ESC%[96m"
    set "CG=%ESC%[92m"
    set "CY=%ESC%[93m"
    set "CR=%ESC%[91m"
    set "CW=%ESC%[97m"
    set "CD=%ESC%[90m"
    set "CX=%ESC%[0m"
)

REM ---------- Modo linha de comando ----------
if /i "%RD_ARG%"=="ferabyte" call :rodar ferabyte & goto :cli_fim
if /i "%RD_ARG%"=="publico" call :rodar publico & goto :cli_fim
if /i "%RD_ARG%"=="status" call :rodar status & goto :cli_fim
if /i "%RD_ARG%"=="testar" call :rodar testar & goto :cli_fim
if /i "%RD_ARG%"=="testar-ferabyte" call :rodar testar-ferabyte & goto :cli_fim
if /i "%RD_ARG%"=="testar-publico" call :rodar testar-publico & goto :cli_fim
goto :checar

:cli_fim
timeout /t 3 >nul 2>&1
goto :fim

REM ---------- Verifica rapido o servidor em uso (ao abrir e apos trocar) ----------
:checar
call :ler_status
set "RD_ALVO=!ATUAL!"
set "RD_ESTADO="
set "RD_ACAO=rapido"
cls
echo.
echo   %CD%Verificando o servidor...%CX%
powershell -NoProfile -ExecutionPolicy Bypass -Command "$s=[IO.File]::ReadAllText($env:RD_BAT); iex $s.Substring($s.IndexOf('#PS#'+'START'))"
set "RD_ESTADO=%errorlevel%"
goto :menu

REM ---------- Menu ----------
:menu
set "RD_MENU=1"
cls
call :ler_status
set "ES_COR=%CD%" & set "ES_TXT=nao verificado"
if "%RD_ESTADO%"=="10" set "ES_COR=%CG%" & set "ES_TXT=PRONTO"
if "%RD_ESTADO%"=="11" set "ES_COR=%CY%" & set "ES_TXT=ATENCAO - resposta parcial"
if "%RD_ESTADO%"=="12" set "ES_COR=%CR%" & set "ES_TXT=FALHA - sem resposta"
echo.
echo   %CT%==========================================================%CX%
echo   %CW%   FERABYTE REMOTO%CX%   %CD%seletor de servidor RustDesk%CX%
echo   %CT%==========================================================%CX%
echo.
echo     Servidor em uso:  %ST_COR%%ST_TXT%%CX%
echo     Situacao:         %ES_COR%%ES_TXT%%CX%
echo.
echo   %CD%----------------------------------------------------------%CX%
echo.
echo     %CG%[1]%CX%  Usar o servidor Ferabyte
echo     %CY%[2]%CX%  Voltar ao servidor publico do RustDesk
echo     %CT%[3]%CX%  Testar os servidores (Ferabyte e publico)
echo     %CW%[4]%CX%  Ver detalhes da configuracao
echo     %CR%[0]%CX%  Sair
echo.
echo   %CD%----------------------------------------------------------%CX%
echo.
choice /c 12340 /n /m "  Escolha uma opcao: "
if errorlevel 5 goto :fim
if errorlevel 4 goto :opc_detalhes
if errorlevel 3 goto :opc_testar
if errorlevel 2 goto :opc_publico
if errorlevel 1 goto :opc_ferabyte
goto :menu

:opc_ferabyte
call :rodar ferabyte
set "RD_RECHECA=1"
goto :voltar

:opc_publico
call :rodar publico
set "RD_RECHECA=1"
goto :voltar

:opc_testar
call :rodar testar
goto :voltar

:opc_detalhes
call :rodar detalhes
goto :voltar

:voltar
echo.
echo   %CD%Pressione qualquer tecla para voltar ao menu...%CX%
pause >nul
if defined RD_RECHECA set "RD_RECHECA=" & goto :checar
goto :menu

REM ---------- Executa uma acao no bloco PowerShell ----------
:rodar
set "RD_ACAO=%~1"
echo.
powershell -NoProfile -ExecutionPolicy Bypass -Command "$s=[IO.File]::ReadAllText($env:RD_BAT); iex $s.Substring($s.IndexOf('#PS#'+'START'))"
if errorlevel 1 (
    echo.
    echo   %CR%Algo deu errado. Leia a mensagem acima e tente novamente.%CX%
)
exit /b

REM ---------- Le o servidor atual (sem PowerShell, rapido) ----------
:ler_status
set "ATUAL="
set "ST_COR=%CY%"
set "ST_TXT=Publico do RustDesk (padrao)"
for %%F in ("%APPDATA%\RustDesk\config\RustDesk2.toml" "%SystemRoot%\ServiceProfiles\LocalService\AppData\Roaming\RustDesk\config\RustDesk2.toml") do (
    if not defined ATUAL if exist "%%~F" (
        for /f "usebackq tokens=2 delims==" %%a in (`findstr /b /c:"custom-rendezvous-server" "%%~F" 2^>nul`) do set "ATUAL=%%a"
    )
)
if not defined ATUAL exit /b
set "ATUAL=!ATUAL:'=!"
set "ATUAL=!ATUAL:"=!"
set "ATUAL=!ATUAL: =!"
set "ST_COR=%CT%"
set "ST_TXT=Personalizado - !ATUAL!"
if /i "!ATUAL!"=="%SERVIDOR%" set "ST_COR=%CG%" & set "ST_TXT=Ferabyte - !ATUAL!"
exit /b

REM ---------- Pede administrador (UAC) e reabre o proprio arquivo ----------
:elevar
echo.
echo   Solicitando permissao de administrador...
powershell -NoProfile -Command "try { if ($env:RD_ARG) { Start-Process -FilePath $env:RD_BAT -ArgumentList $env:RD_ARG -Verb RunAs } else { Start-Process -FilePath $env:RD_BAT -Verb RunAs } } catch { exit 1 }"
if errorlevel 1 (
    echo.
    echo   A permissao de administrador foi negada. Nada foi alterado.
    pause
)
exit /b

:fim
exit /b

#PS#START
$ErrorActionPreference = 'Stop'

$Servidor = $env:RD_SERVIDOR
$Chave    = $env:RD_CHAVE
$Acao     = ([string]$env:RD_ACAO).ToLower()

$Gerenciadas = @('custom-rendezvous-server', 'relay-server', 'key')
$NomeSvc     = 'RustDesk'
$ArqServico  = Join-Path $env:SystemRoot 'ServiceProfiles\LocalService\AppData\Roaming\RustDesk\config\RustDesk2.toml'
$Utf8SemBom  = New-Object System.Text.UTF8Encoding($false)
$script:ExeEmUso = $null   # caminho do RustDesk que estava aberto (instalado ou portatil)

function Ok([string]$m)    { Write-Host "  [OK]  $m" -ForegroundColor Green }
function Aviso([string]$m) { Write-Host "  [!]   $m" -ForegroundColor Yellow }
function Info([string]$m)  { Write-Host "        $m" -ForegroundColor Gray }

function Achar-Exe {
    $candidatos = @(
        "$env:ProgramFiles\RustDesk\rustdesk.exe",
        "${env:ProgramFiles(x86)}\RustDesk\rustdesk.exe",
        "$env:LOCALAPPDATA\Programs\RustDesk\rustdesk.exe"
    )
    foreach ($p in $candidatos) { if (Test-Path $p) { return $p } }
    return $null
}

# Arquivos de configuracao a ajustar: o do usuario atual, o do servico e os de
# outros perfis que ja tenham RustDesk (cobre o caso de elevar com outra conta admin).
function Listar-Alvos {
    $l = New-Object System.Collections.Generic.List[string]
    $l.Add((Join-Path $env:APPDATA 'RustDesk\config\RustDesk2.toml'))
    $raiz = Join-Path $env:SystemDrive 'Users'
    if (Test-Path $raiz) {
        foreach ($d in (Get-ChildItem $raiz -Directory -ErrorAction SilentlyContinue)) {
            $f = Join-Path $d.FullName 'AppData\Roaming\RustDesk\config\RustDesk2.toml'
            if ((Test-Path $f) -and -not ($l -contains $f)) { $l.Add($f) }
        }
    }
    if ((Test-Path $ArqServico) -and -not ($l -contains $ArqServico)) { $l.Add($ArqServico) }
    return $l
}

function Editar-Toml([string]$caminho, [string[]]$novas) {
    $linhas = @()
    if (Test-Path $caminho) {
        $linhas = [IO.File]::ReadAllLines($caminho)
        if (-not (Test-Path "$caminho.bak")) { Copy-Item $caminho "$caminho.bak" }   # guarda so o original
    } elseif ($novas.Count -eq 0) {
        return
    }

    $saida = New-Object System.Collections.Generic.List[string]
    $emOptions = $false
    $achou = $false

    foreach ($l in $linhas) {
        $s = $l.Trim()
        if ($s.StartsWith('[')) {
            $emOptions = ($s -eq '[options]')
            $saida.Add($l)
            if ($emOptions) {
                $achou = $true
                foreach ($n in $novas) { $saida.Add($n) }
            }
            continue
        }
        if ($emOptions -and $s.Contains('=')) {
            $nome = $s.Split('=')[0].Trim().Trim([char]39, [char]34)
            if ($Gerenciadas -contains $nome) { continue }
        }
        $saida.Add($l)
    }

    if (-not $achou -and $novas.Count -gt 0) {
        if ($saida.Count -gt 0 -and $saida[$saida.Count - 1].Trim() -ne '') { $saida.Add('') }
        $saida.Add('[options]')
        foreach ($n in $novas) { $saida.Add($n) }
    }

    if ($saida.Count -eq 0) { return }
    New-Item -ItemType Directory -Force -Path (Split-Path $caminho) | Out-Null
    [IO.File]::WriteAllText($caminho, (($saida -join "`n") + "`n"), $Utf8SemBom)
}

function Ler-Opcao([string]$caminho, [string]$nome) {
    if (-not (Test-Path $caminho)) { return $null }
    $emOptions = $false
    foreach ($l in [IO.File]::ReadAllLines($caminho)) {
        $s = $l.Trim()
        if ($s.StartsWith('[')) { $emOptions = ($s -eq '[options]'); continue }
        if ($emOptions -and $s.Contains('=')) {
            $p = $s.Split('=', 2)
            if ($p[0].Trim().Trim([char]39, [char]34) -eq $nome) {
                return $p[1].Trim().Trim([char]39, [char]34)
            }
        }
    }
    return $null
}

function Parar-RustDesk {
    # guarda de onde o RustDesk estava rodando, para reabrir o mesmo depois
    $rodando = @(Get-Process -Name rustdesk -ErrorAction SilentlyContinue | Where-Object { $_.Path } | Select-Object -ExpandProperty Path -Unique)
    if ($rodando.Count -gt 0) { $script:ExeEmUso = $rodando[0] }
    $svc = Get-Service -Name $NomeSvc -ErrorAction SilentlyContinue
    if ($svc -and $svc.Status -ne 'Stopped') {
        try {
            Stop-Service -Name $NomeSvc -Force -ErrorAction Stop
            $svc.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(15))
        } catch {
            Aviso 'Nao foi possivel parar o servico do RustDesk (continuando).'
        }
    }
    Get-Process -Name rustdesk -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
    for ($i = 0; $i -lt 10 -and (Get-Process -Name rustdesk -ErrorAction SilentlyContinue); $i++) {
        Start-Sleep -Milliseconds 500
    }
}

function Iniciar-RustDesk {
    $svc = Get-Service -Name $NomeSvc -ErrorAction SilentlyContinue
    if ($svc) {
        try { Start-Service -Name $NomeSvc -ErrorAction Stop }
        catch { Aviso 'O servico do RustDesk nao iniciou. Abra o RustDesk manualmente.' }
    }
    if ($script:ExeEmUso -and (Test-Path $script:ExeEmUso)) { $exe = $script:ExeEmUso } else { $exe = Achar-Exe }
    if ($exe) {
        # abre pelo explorer para o RustDesk rodar com o usuario normal, nao como administrador
        try { Start-Process -FilePath 'explorer.exe' -ArgumentList ('"{0}"' -f $exe) }
        catch { Start-Process -FilePath $exe }
    }
}

function Testar-Porta([string]$alvo, [int]$porta, [int]$ms = 3000) {
    $c = New-Object System.Net.Sockets.TcpClient
    try {
        $r = $c.BeginConnect($alvo, $porta, $null, $null)
        if ($r.AsyncWaitHandle.WaitOne($ms, $false) -and $c.Connected) {
            $c.EndConnect($r)
            return $true
        }
        return $false
    } catch {
        return $false
    } finally {
        $c.Close()
    }
}

# Testa um host (DNS + TCP 21116 e 21117) sem mostrar nada. Retorna quantas portas responderam (0, 1 ou 2)
function Testar-Host([string]$alvo, [int]$ms = 3000) {
    try { $ips = [System.Net.Dns]::GetHostAddresses($alvo) } catch { return 0 }
    if (-not $ips) { return 0 }
    $ok = 0
    foreach ($porta in @(21116, 21117)) {
        if (Testar-Porta $alvo $porta $ms) { $ok++ }
    }
    return $ok
}

# Servidores publicos padrao do RustDesk: usa o melhor resultado entre eles
function Testar-Publico([int]$ms = 3000) {
    $melhor = 0
    foreach ($h in @('rs-ny.rustdesk.com', 'rs-sg.rustdesk.com')) {
        $n = Testar-Host $h $ms
        if ($n -gt $melhor) { $melhor = $n }
        if ($melhor -ge 2) { break }
    }
    return $melhor
}

# Mensagem simples: pronto, atencao ou falha
function Resumo([string]$nome, [int]$n) {
    if ($n -ge 2) { Ok "${nome}: PRONTO" }
    elseif ($n -eq 1) { Aviso "${nome}: ATENCAO - resposta parcial" }
    else { Write-Host "  [X]   ${nome}: FALHA - sem resposta" -ForegroundColor Red }
}

# Em modo menu pergunta se deve continuar; em linha de comando segue direto
function Continuar-Mesmo-Assim {
    if ($env:RD_MENU -ne '1') { return $true }
    $r = Read-Host '  Aplicar mesmo assim? (S/N)'
    if ($r.Trim().ToUpper() -ne 'S') { Info 'Nada foi alterado.'; return $false }
    return $true
}

function Aplicar([string[]]$novas, $srvEsperado, $chaveEsperada) {
    if (-not (Achar-Exe) -and -not (Get-Process -Name rustdesk -ErrorAction SilentlyContinue)) {
        Aviso 'RustDesk nao encontrado neste PC. A configuracao sera gravada mesmo assim.'
    }
    Parar-RustDesk
    $falhas = 0
    foreach ($a in (Listar-Alvos)) {
        if (-not (Test-Path $a) -and $novas.Count -eq 0) { continue }
        try {
            Editar-Toml $a $novas
            $s = Ler-Opcao $a 'custom-rendezvous-server'
            $k = Ler-Opcao $a 'key'
            if (-not (($s -eq $srvEsperado) -and ($k -eq $chaveEsperada))) {
                throw 'a conferencia apos gravar nao bateu'
            }
        } catch {
            $falhas++
            Aviso "Falha ao gravar: $a"
        }
    }
    Iniciar-RustDesk
    return $falhas
}

try {
    if (-not $Servidor -or -not $Chave) { throw 'Servidor ou chave nao configurados no inicio do arquivo.' }

    switch ($Acao) {
        'ferabyte' {
            $n = Testar-Host $Servidor
            Resumo 'Servidor Ferabyte' $n
            if ($n -eq 0) {
                Write-Host ''
                if (-not (Continuar-Mesmo-Assim)) { exit 0 }
            }
            $f = Aplicar @("custom-rendezvous-server = '$Servidor'", "key = '$Chave'") $Servidor $Chave
            if ($f -eq 0) { Ok 'Aplicado! O RustDesk foi reiniciado.' } else { exit 1 }
        }
        'publico' {
            $n = Testar-Publico
            Resumo 'Servidor publico' $n
            if ($n -eq 0) {
                Write-Host ''
                if (-not (Continuar-Mesmo-Assim)) { exit 0 }
            }
            $f = Aplicar @() $null $null
            if ($f -eq 0) { Ok 'Aplicado! O RustDesk foi reiniciado.' } else { exit 1 }
        }
        'rapido' {
            # verificacao silenciosa ao abrir o menu: 10 = pronto, 11 = parcial, 12 = falha
            $alvo = ([string]$env:RD_ALVO).Split(':')[0].Trim()
            if ($alvo) { $n = Testar-Host $alvo 1200 } else { $n = Testar-Publico 1200 }
            exit (12 - [Math]::Min($n, 2))
        }
        'testar' {
            $nf = Testar-Host $Servidor
            $np = Testar-Publico
            Resumo 'Servidor Ferabyte' $nf
            Resumo 'Servidor publico' $np
            if ($nf -eq 0 -and $env:RD_MENU -ne '1') { exit 1 }
        }
        'testar-ferabyte' {
            $n = Testar-Host $Servidor
            Resumo 'Servidor Ferabyte' $n
            if ($n -eq 0 -and $env:RD_MENU -ne '1') { exit 1 }
        }
        'testar-publico' {
            $n = Testar-Publico
            Resumo 'Servidor publico' $n
            if ($n -eq 0 -and $env:RD_MENU -ne '1') { exit 1 }
        }
        'status' {
            $atual = Ler-Opcao (Join-Path $env:APPDATA 'RustDesk\config\RustDesk2.toml') 'custom-rendezvous-server'
            if ($atual) { Write-Host "  Servidor atual: $atual" } else { Write-Host '  Servidor atual: publico do RustDesk (padrao)' }
        }
        'detalhes' {
            Write-Host '  Detalhes da configuracao' -ForegroundColor Cyan
            Write-Host ''
            $exe = Achar-Exe
            if ($exe) { Ok "RustDesk encontrado: $exe" } else { Aviso 'RustDesk nao encontrado neste PC.' }
            $svc = Get-Service -Name $NomeSvc -ErrorAction SilentlyContinue
            if ($svc) { Info "Servico: $($svc.Status)" } else { Info 'Servico: nao instalado (modo portatil)' }
            Write-Host ''
            $achouAlgum = $false
            foreach ($a in (Listar-Alvos)) {
                if (-not (Test-Path $a)) { continue }
                $achouAlgum = $true
                $s = Ler-Opcao $a 'custom-rendezvous-server'
                $k = Ler-Opcao $a 'key'
                Write-Host "  $a" -ForegroundColor White
                if ($s) { Info "servidor : $s" } else { Info 'servidor : (padrao publico)' }
                if ($k) { Info ('chave    : ' + $k.Substring(0, [Math]::Min(10, $k.Length)) + '...') } else { Info 'chave    : (nenhuma)' }
                if (Test-Path "$a.bak") { Info 'backup   : existe (.bak)' } else { Info 'backup   : nao existe' }
                Write-Host ''
            }
            if (-not $achouAlgum) { Info 'Nenhum arquivo de configuracao encontrado ainda. Abra o RustDesk uma vez.' }
        }
        default { throw "Acao desconhecida: $Acao" }
    }
    exit 0
} catch {
    Write-Host "  [ERRO] $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}
