@echo off
setlocal

:: === CONFIG ===
set "URL=https://agdi.servicedesk.atera.com/GetAgent/Windows/?cid=7&aid=001Q300000S4VEqIAN"
set "OUT=setup.msi"

:: ==== Fonction : test admin ====
:: net session nécessite les droits admin -> code 0 si admin
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [*] Droits admin requis. Relancement en mode administrateur...
    :: Relaunch this script elevated using PowerShell Start-Process -Verb RunAs
    powershell -Command "Start-Process -FilePath '%~f0' -ArgumentList '' -Verb RunAs"
    exit /b
)

echo [*] Execution en mode administrateur OK.

:: Supprime l'ancien fichier si présent
if exist "%OUT%" del /f /q "%OUT%"

:: ==== Téléchargement : curl si dispo, sinon PowerShell Invoke-WebRequest ====
where curl >nul 2>&1
if %errorlevel% equ 0 (
    echo [*] curl trouvé — téléchargement...
    curl -L -o "%OUT%" "%URL%"
    if %errorlevel% neq 0 (
        echo [!] curl a échoué (code %errorlevel%). Tentative via PowerShell...
        goto ps_download
    )
) else (
    goto ps_download
)

goto after_download

:ps_download
echo [*] Utilisation de PowerShell pour télécharger...
powershell -NoProfile -Command ^
  "$u = '%URL%'; $o = '%OUT%'; (New-Object System.Net.WebClient).DownloadFile($u,$o)"
if %errorlevel% neq 0 (
    echo [!] Le téléchargement a echoue (PowerShell). Abandon.
    pause
    exit /b 1
)

:after_download
if not exist "%OUT%" (
    echo [!] Fichier %OUT% absent après tentative de téléchargement.
    pause
    exit /b 1
)

echo [*] Lancement de l'installation MSI (silencieuse)...
msiexec /i "%OUT%" /qn /norestart
set "RC=%errorlevel%"

if "%RC%"=="0" (
    echo [+] Installation terminée avec succès.
) else (
    echo [!] msiexec a renvoyé le code %RC%.
)

:: Optionnel : supprimer le MSI après installation
:: del /f /q "%OUT%"

endlocal
exit /b %RC%
