@echo off
title RustDesk Setup - Owlypia Remote Support
color 0A
echo.
echo  ================================================
echo    Owlypia Remote Support - Automatic Setup
echo  ================================================
echo.
echo  Downloading RustDesk, please wait...
echo.

:: Create temp folder
set TMPDIR=%TEMP%\rustdesk_setup
mkdir "%TMPDIR%" 2>nul

:: Download RustDesk
powershell -Command "Invoke-WebRequest -Uri 'https://github.com/rustdesk/rustdesk/releases/download/1.3.8/rustdesk-1.3.8-x86_64.exe' -OutFile '%TMPDIR%\rustdesk.exe'"

if not exist "%TMPDIR%\rustdesk.exe" (
    echo  ERROR: Download failed. Please check your internet connection.
    pause
    exit /b 1
)

echo  Installing RustDesk...
"%TMPDIR%\rustdesk.exe" --silent-install

:: Wait for installation to complete
timeout /t 8 /nobreak >nul

:: Find RustDesk executable dynamically
set RUSTDESK_EXE=
if exist "%ProgramFiles%\RustDesk\rustdesk.exe" set RUSTDESK_EXE=%ProgramFiles%\RustDesk\rustdesk.exe
if exist "%ProgramFiles(x86)%\RustDesk\rustdesk.exe" set RUSTDESK_EXE=%ProgramFiles(x86)%\RustDesk\rustdesk.exe
if exist "%LOCALAPPDATA%\RustDesk\rustdesk.exe" set RUSTDESK_EXE=%LOCALAPPDATA%\RustDesk\rustdesk.exe

:: Search in registry if not found yet
if "%RUSTDESK_EXE%"=="" (
    for /f "tokens=2*" %%a in ('reg query "HKLM\SOFTWARE\RustDesk" /v InstallLocation 2^>nul') do set RUSTDESK_EXE=%%b\rustdesk.exe
)

if "%RUSTDESK_EXE%"=="" (
    echo  ERROR: RustDesk installation not found. Please try running as Administrator.
    pause
    exit /b 1
)

echo  Found RustDesk at: %RUSTDESK_EXE%

:: Run RustDesk once so it creates its config folder, then kill it
echo  Initializing RustDesk...
start "" "%RUSTDESK_EXE%"
timeout /t 5 /nobreak >nul
taskkill /f /im rustdesk.exe >nul 2>&1
timeout /t 2 /nobreak >nul

:: Create config folder (in case it still doesn't exist)
set CONFIGDIR=%APPDATA%\RustDesk\config
mkdir "%CONFIGDIR%" 2>nul

:: Write server configuration
echo  Configuring server settings...
(
echo rendezvous_server = 'remote.owlypia.org'
echo relay_server = 'remote.owlypia.org'
echo public_key = 'RHhttpf76YSJ1e6pwuh3CvnYjm4mmzH5pDYT18fDPcc='
) > "%CONFIGDIR%\RustDesk2.toml"

:: Verify config was written
if not exist "%CONFIGDIR%\RustDesk2.toml" (
    echo  ERROR: Could not write configuration file.
    pause
    exit /b 1
)

:: Clean up temp files
rmdir /s /q "%TMPDIR%" 2>nul

echo.
echo  ================================================
echo    Installation complete!
echo.
echo    Double-click the RustDesk icon on your desktop.
echo    Share the ID and password shown on screen
echo    with our support team.
echo  ================================================
echo.

:: Launch RustDesk
start "" "%RUSTDESK_EXE%"

pause
