@echo off
setlocal enabledelayedexpansion

:: Resolve the directory containing this script
set "SCRIPT_PATH=%~dp0"
set "SCRIPT_PATH=%SCRIPT_PATH:~0,-1%"
set "ORIGINAL_CWD=%cd%"
pushd "%SCRIPT_PATH%\.."
set "RUMI_CLI_HOME=%cd%"
popd

:: Check JAVA_HOME
if not defined JAVA_HOME (
    echo The JAVA_HOME environment variable needs to be set.
    exit /b 1
)

:: Check Java version (must be 11+)
for /f "delims=" %%v in ('cmd /v:on /c ^""%JAVA_HOME%\bin\java" -version 2^>^&1 ^| findstr "version"^"') do (
    for /f tokens^=2^ delims^=^" %%a in ("%%v") do set JAVA_VERSION_STRING=%%a
)
for /f tokens^=1^ delims^=. %%a in ("!JAVA_VERSION_STRING!") do set JAVA_VERSION_MAJOR=%%a
if "!JAVA_VERSION_MAJOR!" LSS "11" (
    echo The Rumi CLI requires Java version 11 or higher (JAVA_HOME currently points to !JAVA_VERSION_STRING!^)
    exit /b 1
)

:: Default trace level
set "DEFAULTTRACELEVEL=severe"

:: Parse arguments
set "EXTRA_JARS="
set "ENABLE_3X=false"
set args=
:parse_args
if "%1"=="" goto done_parse
if "%1"=="--extra-jars" (
    set "EXTRA_JARS=%2"
    shift
) else if "%1"=="--3x" (
    set "ENABLE_3X=true"
) else (
    set args=!args! %1
)
shift
goto parse_args
:done_parse

:: Build classpath
set "CLASSPATH=%RUMI_CLI_HOME%\libs\*"
if defined EXTRA_JARS (
    for %%J in (%EXTRA_JARS:,= %) do (
        set "CLASSPATH=!CLASSPATH!;%%J"
    )
)

:: Define Java options
set "JAVA_OPTS=--add-opens=java.base/jdk.internal.ref=ALL-UNNAMED"
set "JAVA_OPTS=!JAVA_OPTS! --add-opens=java.base/sun.nio.ch=ALL-UNNAMED"
set "JAVA_OPTS=!JAVA_OPTS! --add-opens=java.base/java.lang=ALL-UNNAMED"
set "JAVA_OPTS=!JAVA_OPTS! --add-opens=java.base/java.nio=ALL-UNNAMED"
set "JAVA_OPTS=!JAVA_OPTS! --add-opens=java.base/java.io=ALL-UNNAMED"
set "JAVA_OPTS=!JAVA_OPTS! --add-opens=java.management/sun.management=ALL-UNNAMED"
set "JAVA_OPTS=!JAVA_OPTS! --illegal-access=warn"

:: Add 3.x compatibility
if "%ENABLE_3X%"=="true" (
    set "JAVA_OPTS=!JAVA_OPTS! -Dnv.compat.3x.io=true"
)

:: Run the CLI
"%JAVA_HOME%\bin\java" !JAVA_OPTS! -Xms1g -Xmx1g ^
  -Dnv.app.propfile="%RUMI_CLI_HOME%\conf\cli.conf" ^
  -Dnv.trace.defaultLevel=%DEFAULTTRACELEVEL% ^
  -Dnv.cloud.trace=info ^
  -Djava.net.preferIPv4Stack=true ^
  -cp "%CLASSPATH%" ^
  com.neeve.tools.CliMain !args!

exit /b %errorlevel%
