@echo off
setlocal enabledelayedexpansion

:: Paths
set CONFIG_FILE=C:\Windows\ServiceProfiles\LocalService\AppData\Roaming\RustDesk\config\RustDesk.toml

:: Check if RustDesk service exists
sc query RustDesk >nul 2>&1
if errorlevel 1 (
    echo RustDesk is not installed or the service does not exist.
    exit /b 1
)

echo Stopping RustDesk service...
sc stop RustDesk >nul 2>&1

:: Read current ID (first line of file)
for /f "usebackq delims=" %%A in (`type "%CONFIG_FILE%" ^| findstr /n "^" ^| findstr "^1:"`) do (
    set "current_id=%%A"
)
set "current_id=!current_id:*:=!"

echo Current ID: !current_id!

:: Prompt for new ID
set /p newIdValue=Enter your custom RustDesk ID: 
set "newId=id = '!newIdValue!'"

echo New ID: !newId!

:: Read current password (second line of file)
for /f "usebackq delims=" %%A in (`type "%CONFIG_FILE%" ^| findstr /n "^" ^| findstr "^2:"`) do (
    set "current_pw=%%A"
)
set "current_pw=!current_pw:*:=!"

echo Current password line: !current_pw!

:: Use fixed password (since Batch cannot generate easily)
set "randomPassword=P055um69*"
set "newPassword=password = '!randomPassword!'"

echo New password line: !newPassword!

:: Replace old values in file
(for /f "usebackq delims=" %%A in ("%CONFIG_FILE%") do (
    set "line=%%A"
    if "!line!"=="!current_id!" (
        echo !newId!
    ) else if "!line!"=="!current_pw!" (
        echo !newPassword!
    ) else (
        echo !line!
    )
)) > "%CONFIG_FILE%.tmp"

move /y "%CONFIG_FILE%.tmp" "%CONFIG_FILE%" >nul

echo Starting RustDesk service...
sc start RustDesk >nul 2>&1

echo.
echo RustDesk ID has been changed to: !newId!
echo RustDesk password has been changed to: !randomPassword!

endlocal
pause
