@echo off
chcp 65001 >nul 2>&1
title CompArt Assistencia Remota - Configuracao

echo ============================================
echo   CompArt Assistencia Remota
echo   Configuracao do Servidor
echo ============================================
echo.

:: Check if running as admin
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [!] A executar como administrador...
    powershell -Command "Start-Process '%~f0' -Verb RunAs"
    exit /b
)

:: RustDesk paths
set "RUSTDESK_EXE=%ProgramFiles%\RustDesk\rustdesk.exe"
set "RUSTDESK_EXE2=%ProgramFiles(x86)%\RustDesk\rustdesk.exe"
set "RUSTDESK_PORTABLE=%TEMP%\RustDesk\rustdesk.exe"
set "CONFIG_DIR=%AppData%\RustDesk\config"
set "SERVICE_CONFIG=C:\Windows\ServiceProfiles\LocalService\AppData\Roaming\RustDesk\config"

:: Find RustDesk
set "RUSTDESK="
if exist "%RUSTDESK_EXE%" set "RUSTDESK=%RUSTDESK_EXE%"
if exist "%RUSTDESK_EXE2%" set "RUSTDESK=%RUSTDESK_EXE2%"
if exist "%RUSTDESK_PORTABLE%" set "RUSTDESK=%RUSTDESK_PORTABLE%"

:: Also check if running in system context for portable
tasklist /FI "IMAGENAME eq rustdesk.exe" 2>nul | find /I "rustdesk.exe" >nul
if %errorlevel% equ 0 (
    for /f "tokens=2" %%a in ('tasklist /FI "IMAGENAME eq rustdesk.exe" /NH 2^>nul') do (
        for /f "tokens=1 delims=\" %%b in ("%%a") do (
            wmic process where "processid=%%a" get ExecutablePath 2>nul | find /I "rustdesk" >nul
        )
    )
)

if "%RUSTDESK%"=="" (
    echo [ERRO] RustDesk nao encontrado!
    echo.
    echo Por favor:
    echo 1. Execute o ficheiro CompArt_Assistencia_Remota.exe que descarregou
    echo 2. Instale o RustDesk
    echo 3. Volte a executar este script
    echo.
    pause
    exit /b 1
)

echo [OK] RustDesk encontrado: %RUSTDESK%
echo.

:: Write config - User level
echo A configurar servidor CompArt...
if not exist "%CONFIG_DIR%" mkdir "%CONFIG_DIR%"

echo [options] > "%CONFIG_DIR%\RustDesk2.toml"
echo custom-rendezvous-server = "116.203.52.248:21116" >> "%CONFIG_DIR%\RustDesk2.toml"
echo relay-server = "116.203.52.248:21117" >> "%CONFIG_DIR%\RustDesk2.toml"
echo key = "VoNciHfK04+8tqVDJH8gLs5CbsXpECQ4jBTuFPEt1XU=" >> "%CONFIG_DIR%\RustDesk2.toml"

:: Write config - Service level (for unattended access)
if not exist "%SERVICE_CONFIG%" mkdir "%SERVICE_CONFIG%" 2>nul
echo [options] > "%SERVICE_CONFIG%\RustDesk2.toml"
echo custom-rendezvous-server = "116.203.52.248:21116" >> "%SERVICE_CONFIG%\RustDesk2.toml"
echo relay-server = "116.203.52.248:21117" >> "%SERVICE_CONFIG%\RustDesk2.toml"
echo key = "VoNciHfK04+8tqVDJH8gLs5CbsXpECQ4jBTuFPEt1XU=" >> "%SERVICE_CONFIG%\RustDesk2.toml"

echo [OK] Configuracao escrita com sucesso!
echo.

:: Stop RustDesk service if running
echo A reiniciar RustDesk...
sc stop RustDeskService >nul 2>&1
taskkill /F /IM rustdesk.exe >nul 2>&1
timeout /t 3 /nobreak >nul

:: Start RustDesk
if exist "%RUSTDESK%" (
    start "" "%RUSTDESK%"
)

timeout /t 5 /nobreak >nul

:: Get RustDesk ID
echo A obter ID RustDesk...
set "RUSTDESK_ID="
for /f "delims=" %%i in ('"%RUSTDESK%" --get-id 2^>nul') do set "RUSTDESK_ID=%%i"

:: Report to server
if defined RUSTDESK_ID (
    if not "%RUSTDESK_ID%"=="" (
        echo.
        echo ============================================
        echo   Configuracao concluida!
        echo ============================================
        echo.
        echo   O seu ID RustDesk: %RUSTDESK_ID%
        echo.
        echo   Partilhe este ID e a palavra-passe
        echo   com o tecnico da CompArt.
        echo.
        echo   Telefone/WhatsApp: +351 933 946 917
        echo ============================================
        
        :: Report ID to server
        powershell -Command "try { Invoke-RestMethod -Uri 'https://admin.compartsystems.pt/api/clients' -Method Post -ContentType 'application/json' -Body ('{\"rustdesk_id\":\"%RUSTDESK_ID%\",\"hostname\":\"' + $env:COMPUTERNAME + '\"}') -Headers @{'x-api-secret'='cs-remote-2026-xK9mP'} } catch {}"
    )
) else (
    echo.
    echo [AVISO] Nao foi possivel obter o ID automaticamente.
    echo Abra o RustDesk e partilhe o ID manualmente.
    echo.
)

echo.
pause