@echo off
setlocal
cd /d "%~dp0"

title RustDesk Setup

echo ==========================================
echo        RustDesk Auto Configuration
echo ==========================================
echo.

set "SRC=%~dp0RustDesk"
set "DST=%APPDATA%\RustDesk"
set "APP=%~dp0setup.exe"

echo Closing RustDesk if it is already running...
taskkill /IM rustdesk.exe /F >nul 2>&1
taskkill /IM RustDesk.exe /F >nul 2>&1
timeout /t 2 >nul

echo.

if not exist "%APP%" (
    echo ERROR: setup.exe was not found in this folder.
    echo Make sure config.bat is next to setup.exe.
    echo.
    pause
    exit /b 1
)

if not exist "%SRC%" (
    echo ERROR: RustDesk config folder was not found.
    echo Expected folder:
    echo %SRC%
    echo.
    echo Your folder should look like:
    echo setup.exe
    echo config.bat
    echo RustDesk\
    echo.
    pause
    exit /b 1
)

echo Preparing RustDesk configuration...

if exist "%DST%" (
    echo Existing RustDesk config found.
    echo Backing it up first...

    set "BACKUP=%APPDATA%\RustDesk.backup.%RANDOM%"

    move "%DST%" "%BACKUP%" >nul 2>&1

    if exist "%DST%" (
        echo WARNING: Could not fully move old config.
        echo Trying to continue anyway...
    ) else (
        echo Backup created:
        echo %BACKUP%
    )
)

echo.
echo Copying your preconfigured RustDesk settings...
xcopy "%SRC%" "%DST%" /E /I /Y /H >nul

if not exist "%DST%" (
    echo ERROR: Failed to copy RustDesk configuration.
    echo.
    pause
    exit /b 1
)

echo.
echo Removing machine-specific identity files...
echo This prevents the client from getting your RustDesk ID.

del /F /Q "%DST%\id_ed25519" >nul 2>&1
del /F /Q "%DST%\id_ed25519.pub" >nul 2>&1
del /F /Q "%DST%\config\id_ed25519" >nul 2>&1
del /F /Q "%DST%\config\id_ed25519.pub" >nul 2>&1

for /R "%DST%" %%F in (id_ed25519 id_ed25519.pub) do (
    del /F /Q "%%F" >nul 2>&1
)

echo.
echo Configuration copied successfully.
echo Starting RustDesk...
echo.

start "" "%APP%"

echo ==========================================
echo Done.
echo.
echo RustDesk should open now.
echo Tell the user:
echo.
echo   "Send me the ID number shown in RustDesk."
echo.
echo ==========================================
echo.
pause
exit /b 0
