@echo off
setlocal EnableExtensions
title Fix RustDesk Issues

fltmc >nul 2>&1
if errorlevel 1 (
  echo.
  echo This tool must be run as Administrator.
  echo.
  echo Close this window, right-click the downloaded file, and choose "Run as administrator".
  echo.
  pause
  exit /b 1
)

echo.
echo Fix RustDesk Issues
echo.
echo This will stop RustDesk and remove its local configuration data from this PC.
echo It does not delete your personal files.
echo.
choice /C YN /M "Continue"
if errorlevel 2 exit /b 0

set "LOG=%TEMP%\rustdesk-reset.log"
echo RustDesk reset started %DATE% %TIME%>"%LOG%"

echo.
echo Stopping RustDesk...
call :stop_service RustDesk
call :stop_service rustdesk
taskkill /F /T /IM rustdesk.exe >>"%LOG%" 2>&1
taskkill /F /T /IM RustDesk.exe >>"%LOG%" 2>&1
timeout /t 2 /nobreak >nul

echo.
echo Removing RustDesk configuration...
call :remove "%ProgramData%\RustDesk"
call :remove "%SystemRoot%\ServiceProfiles\LocalService\AppData\Roaming\RustDesk"
call :remove "%SystemRoot%\ServiceProfiles\LocalService\AppData\Local\RustDesk"
call :remove "%SystemRoot%\ServiceProfiles\NetworkService\AppData\Roaming\RustDesk"
call :remove "%SystemRoot%\ServiceProfiles\NetworkService\AppData\Local\RustDesk"
call :remove "%ProgramFiles%\RustDesk\config"
if not "%ProgramFiles(x86)%"=="" call :remove "%ProgramFiles(x86)%\RustDesk\config"

for /D %%U in ("%SystemDrive%\Users\*") do (
  if /I not "%%~nxU"=="Public" (
    call :remove "%%~fU\AppData\Roaming\RustDesk"
    call :remove "%%~fU\AppData\Local\RustDesk"
    call :remove "%%~fU\AppData\LocalLow\RustDesk"
  )
)

echo.
echo RustDesk local configuration has been reset.
echo.
echo Next step:
echo 1. Return to xrayservice.net.
echo 2. Click "Download Remote Support Installer".
echo 3. Run the installer and read the new 9-digit ID to your technician.
echo.
echo Log file: %LOG%
echo.
pause
exit /b 0

:stop_service
sc query "%~1" >nul 2>&1
if not errorlevel 1 (
  sc stop "%~1" >>"%LOG%" 2>&1
)
exit /b 0

:remove
if exist "%~1" (
  echo Removing "%~1"
  echo Removing "%~1">>"%LOG%"
  attrib -R -S -H "%~1" /S /D >>"%LOG%" 2>&1
  rmdir /S /Q "%~1" >>"%LOG%" 2>&1
)
exit /b 0
