@echo off
setlocal EnableDelayedExpansion
chcp 65001 >nul

:: ============================================================
:: RustDesk - Installazione Servizio + Configurazione Persistente
:: Server: rd.prosys-tech.it
:: ============================================================

echo.
echo ================================================
echo  Installazione RustDesk - ProSys Tech
echo ================================================
echo.

:: 1. Controlla privilegi amministratore
net session >nul 2>&1
if %errorLevel% neq 0 (
    echo [ERRORE] Esegui come Amministratore!
    pause
    exit /b 1
)

:: Variabili
set SERVER=rd.prosys-tech.it
set INSTALLER=%TEMP%\rustdesk-installer.exe
set API_URL=https://api.github.com/repos/rustdesk/rustdesk/releases/latest

:: 2. Recupera ultima versione
echo [1/6] Recupero ultima versione...
for /f "delims=" %%i in ('powershell -NoProfile -Command "(Invoke-RestMethod -Uri '%API_URL%').tag_name"') do set LATEST_VERSION=%%i

:: 3. Download
echo [2/6] Download in corso...
set DOWNLOAD_URL=https://github.com/rustdesk/rustdesk/releases/download/!LATEST_VERSION!/rustdesk-!LATEST_VERSION!-x86_64.exe
curl -s -L "!DOWNLOAD_URL!" -o "%INSTALLER%"

:: 4. Installazione e Registrazione Servizio
echo [3/6] Installazione file e REGISTRAZIONE SERVIZIO...
start /wait "" "%INSTALLER%" --silent-install
timeout /t 5 /nobreak >nul

:: COMANDO CHIAVE: Forza l'installazione del servizio Windows
"%ProgramFiles%\RustDesk\rustdesk.exe" --install-service

:: Chiudiamo eventuali istanze aperte per configurare i file
taskkill /f /im rustdesk.exe >nul 2>&1

:: 5. Configurazione Persistente
echo [4/6] Scrittura configurazioni di sistema...
set CONFIG_USER=%APPDATA%\RustDesk\config
set CONFIG_SYS=C:\Windows\ServiceProfiles\LocalService\AppData\Roaming\RustDesk\config

if not exist "%CONFIG_USER%" mkdir "%CONFIG_USER%"
if not exist "%CONFIG_SYS%" mkdir "%CONFIG_SYS%"

(
echo [options]
echo custom-rendezvous-server = '%SERVER%'
echo relay-server = '%SERVER%'
echo direct-server = ''
echo key = ''
) > "%TEMP%\RustDesk2.toml"

copy /y "%TEMP%\RustDesk2.toml" "%CONFIG_USER%\RustDesk2.toml" >nul
copy /y "%TEMP%\RustDesk2.toml" "%CONFIG_SYS%\RustDesk2.toml" >nul

:: 6. Avvio Servizio
echo [5/6] Avvio servizio Windows...
net start RustDesk >nul 2>&1

:: 7. Pulizia
echo [6/6] Finalizzazione...
del "%INSTALLER%" >nul 2>&1
del "%TEMP%\RustDesk2.toml" >nul 2>&1

:: Avvia l'interfaccia
start "" "%ProgramFiles%\RustDesk\rustdesk.exe"

echo.
echo ================================================
echo  INSTALLAZIONE COMPLETATA! 
echo ================================================
echo.
pause
exit