@echo off
TITLE RuneVision Setup
setlocal

REM Do not load the installed RuneVision agent into this updater.
REM Otherwise Java locks the old agent JAR before the installer can replace it.
set "_JAVA_OPTIONS="

set "SCRIPT_DIR=%~dp0"
set "JRE_DIR=%SCRIPT_DIR%jre"
set "JRE_URL=https://api.adoptium.net/v3/binary/latest/11/ga/windows/x64/jre/hotspot/normal/eclipse"
set "JRE_ZIP=%SCRIPT_DIR%jre.zip"

REM Check for bundled JRE
if exist "%JRE_DIR%\bin\java.exe" goto :run_installer

REM Check for system Java
where java >nul 2>&1
if not errorlevel 1 (
    set "JAVA_CMD=java"
    goto :run_with_system
)

REM Download portable JRE
echo Downloading Java runtime...
powershell -NoProfile -Command "Invoke-WebRequest -Uri '%JRE_URL%' -OutFile '%JRE_ZIP%' -UseBasicParsing"
if not exist "%JRE_ZIP%" (
    echo Failed to download Java runtime.
    echo Please install Java 11+ from https://adoptium.net
    pause
    exit /b 1
)

echo Extracting Java runtime...
powershell -NoProfile -Command "Expand-Archive -Path '%JRE_ZIP%' -DestinationPath '%SCRIPT_DIR%jre_temp' -Force"
del "%JRE_ZIP%"

REM Move extracted folder (has version in name) to jre/
for /d %%D in ("%SCRIPT_DIR%jre_temp\*") do (
    move "%%D" "%JRE_DIR%" >nul
)
rmdir "%SCRIPT_DIR%jre_temp" 2>nul

if not exist "%JRE_DIR%\bin\java.exe" (
    echo Java extraction failed.
    pause
    exit /b 1
)

:run_installer
set "JAVA_CMD=%JRE_DIR%\bin\java.exe"

:run_with_system
"%JAVA_CMD%" -jar "%SCRIPT_DIR%RuneVision.jar"
exit /b 0
