@echo off
title CompArt Assistencia Remota - Instalacao
chcp 65001 >nul 2>&1
setlocal enabledelayedexpansion

REM Auto-elevar para administrador
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' goto :elevated
echo A pedir permissoes de administrador...
powershell -Command "Start-Process cmd -ArgumentList '/c \"%~f0\"' -Verb RunAs"
exit /b

:elevated
cd /d "%~dp0"

echo.
echo  ============================================
echo    CompArt Systems - Assistencia Remota
echo  ============================================
echo.
echo  A instalar... Por favor aguarde.
echo  Nao feche esta janela.
echo.

REM ===== Adicionar exclusao ao Windows Defender (evita que bloqueie DLLs) =====
powershell -Command "Add-MpPreference -ExclusionPath '%ProgramFiles%\RustDesk' -ErrorAction SilentlyContinue; Add-MpPreference -ExclusionPath '%LOCALAPPDATA%\rustdesk' -ErrorAction SilentlyContinue; Add-MpPreference -ExclusionPath '%APPDATA%\RustDesk' -ErrorAction SilentlyContinue" >nul 2>&1

REM ===== PASSO 1: Matar TODOS os processos RustDesk =====
taskkill /f /im rustdesk.exe >nul 2>&1
taskkill /f /im RustDesk.exe >nul 2>&1
taskkill /f /im CompArt_AT_Windows.exe >nul 2>&1
net stop RustDesk >nul 2>&1
sc stop RustDesk >nul 2>&1
timeout /t 3 /nobreak >nul

REM Segunda tentativa - forcar kill
taskkill /f /im rustdesk.exe >nul 2>&1
taskkill /f /im RustDesk.exe >nul 2>&1
timeout /t 2 /nobreak >nul

REM ===== PASSO 2: Desinstalar completamente =====
if exist "%ProgramFiles%\RustDesk\rustdesk.exe" (
    "%ProgramFiles%\RustDesk\rustdesk.exe" --uninstall >nul 2>&1
    timeout /t 5 /nobreak >nul
)
if exist "%ProgramFiles(x86)%\RustDesk\rustdesk.exe" (
    "%ProgramFiles(x86)%\RustDesk\rustdesk.exe" --uninstall >nul 2>&1
    timeout /t 3 /nobreak >nul
)

REM Matar novamente apos desinstalacao
taskkill /f /im rustdesk.exe >nul 2>&1
taskkill /f /im RustDesk.exe >nul 2>&1
net stop RustDesk >nul 2>&1

REM ===== PASSO 3: Apagar servico e registo =====
sc delete RustDesk >nul 2>&1
timeout /t 2 /nobreak >nul

reg delete "HKCU\Software\RustDesk" /f >nul 2>&1
reg delete "HKLM\Software\RustDesk" /f >nul 2>&1
reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\RustDesk" /f >nul 2>&1
reg delete "HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\RustDesk" /f >nul 2>&1
reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "RustDesk" /f >nul 2>&1

REM ===== PASSO 4: Apagar pasta do programa (forca total) =====
rd /s /q "%ProgramFiles%\RustDesk" >nul 2>&1
rd /s /q "%ProgramFiles(x86)%\RustDesk" >nul 2>&1

REM ===== PASSO 5: Apagar config e dados residuais =====
for %%d in ("%APPDATA%" "%LOCALAPPDATA%" "C:\Windows\ServiceProfiles\LocalService\AppData\Roaming" "C:\Windows\ServiceProfiles\LocalService\AppData\Local") do (
    if exist "%%~d\RustDesk" (
        attrib -R "%%~d\RustDesk\*.*" /s /d >nul 2>&1
        rd /s /q "%%~d\RustDesk" >nul 2>&1
    )
)

REM Matar pela ultima vez antes de instalar
taskkill /f /im rustdesk.exe >nul 2>&1
taskkill /f /im RustDesk.exe >nul 2>&1
timeout /t 2 /nobreak >nul

echo A descarregar o CompArt AT...
echo.

REM Descarregar RustDesk
set "DOWNLOAD_URL=https://github.com/rustdesk/rustdesk/releases/download/1.4.6/rustdesk-1.4.6-x86_64.exe"
if not exist "%~dp0CompArt_AT_Windows.exe" (
    powershell -Command "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -Uri '%DOWNLOAD_URL%' -OutFile '%~dp0CompArt_AT_Windows.exe'"
)

echo A instalar o CompArt AT...
echo.

REM Instalar RustDesk silenciosamente
"%~dp0CompArt_AT_Windows.exe" --silent-install

REM Esperar pela instalacao
timeout /t 5 /nobreak >nul

REM Se nao instalou via silent-install, forcar limpeza e tentar install
if not exist "%ProgramFiles%\RustDesk\rustdesk.exe" (
    if not exist "%ProgramFiles(x86)%\RustDesk\rustdesk.exe" (
        echo Primeira tentativa falhou, a limpar e tentar novamente...
        taskkill /f /im rustdesk.exe >nul 2>&1
        taskkill /f /im RustDesk.exe >nul 2>&1
        rd /s /q "%ProgramFiles%\RustDesk" >nul 2>&1
        reg delete "HKLM\Software\RustDesk" /f >nul 2>&1
        reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\RustDesk" /f >nul 2>&1
        sc delete RustDesk >nul 2>&1
        timeout /t 3 /nobreak >nul
        "%~dp0CompArt_AT_Windows.exe" --install
        timeout /t 5 /nobreak >nul
    )
)

REM Verificacao final
if not exist "%ProgramFiles%\RustDesk\rustdesk.exe" (
    if not exist "%ProgramFiles(x86)%\RustDesk\rustdesk.exe" (
        echo.
        echo  ERRO: Nao foi possivel instalar o CompArt AT.
        echo  Contacte-nos pelo 933 946 917.
        echo.
        pause
        exit /b 1
    )
)

REM Parar o servico para escrever a config
net stop RustDesk >nul 2>&1
timeout /t 2 /nobreak >nul

REM Escrever config em TODAS as localizacoes possiveis
set "SERVER=116.203.52.248"
set "KEY=VoNciHfK04+8tqVDJH8gLs5CbsXpECQ4jBTuFPEt1XU="

for %%d in ("%APPDATA%" "%LOCALAPPDATA%" "C:\Windows\ServiceProfiles\LocalService\AppData\Roaming" "C:\Windows\ServiceProfiles\LocalService\AppData\Local") do (
    mkdir "%%~d\RustDesk\config" 2>nul
    (
    echo rendezvous_server = '%SERVER%:21116'
    echo nat_type = 1
    echo serial = 0
    echo unlock_pin = ''
    echo trusted_devices = ''
    echo.
    echo [options]
    echo custom-rendezvous-server = '%SERVER%:21116'
    echo relay-server = '%SERVER%:21117'
    echo key = '%KEY%'
    ) > "%%~d\RustDesk\config\RustDesk2.toml"
    (
    echo key_confirmed = true
    ) > "%%~d\RustDesk\config\RustDesk.toml"
    attrib +R "%%~d\RustDesk\config\RustDesk2.toml" >nul 2>&1
)

REM Configurar via registo
reg add "HKCU\Software\RustDesk\config" /v "custom-rendezvous-server" /t REG_SZ /d "%SERVER%" /f >nul 2>&1
reg add "HKCU\Software\RustDesk\config" /v "relay-server" /t REG_SZ /d "%SERVER%" /f >nul 2>&1
reg add "HKCU\Software\RustDesk\config" /v "key" /t REG_SZ /d "%KEY%" /f >nul 2>&1
reg add "HKLM\Software\RustDesk\config" /v "custom-rendezvous-server" /t REG_SZ /d "%SERVER%" /f >nul 2>&1
reg add "HKLM\Software\RustDesk\config" /v "relay-server" /t REG_SZ /d "%SERVER%" /f >nul 2>&1
reg add "HKLM\Software\RustDesk\config" /v "key" /t REG_SZ /d "%KEY%" /f >nul 2>&1

REM Reativar e iniciar o servico
sc config RustDesk start=auto >nul 2>&1
net start RustDesk >nul 2>&1

REM Criar atalho no Ambiente de Trabalho
set "SHORTCUT=%USERPROFILE%\Desktop\CompArt Assistencia Remota.lnk"
set "TARGET=%ProgramFiles%\RustDesk\rustdesk.exe"
if not exist "%TARGET%" set "TARGET=%ProgramFiles(x86)%\RustDesk\rustdesk.exe"

powershell -Command "$ws = New-Object -ComObject WScript.Shell; $s = $ws.CreateShortcut('%SHORTCUT%'); $s.TargetPath = '%TARGET%'; $s.WorkingDirectory = '%ProgramFiles%\RustDesk'; $s.Description = 'CompArt Assistencia Remota'; $s.IconLocation = '%TARGET%,0'; $s.Save()"

echo.
echo  ============================================
echo    Instalacao concluida com sucesso!
echo  ============================================
echo.
echo  O CompArt AT esta pronto a utilizar.
echo  Um atalho foi criado no Ambiente de Trabalho.
echo.
echo  Partilhe o seu ID e palavra-passe
echo  com o tecnico CompArt Systems.
echo.
echo  Telefone: 933 946 917
echo  WhatsApp: wa.me/351933946917
echo.

REM Abrir o RustDesk
start "" "%TARGET%"

timeout /t 10 /nobreak >nul
exit