@echo off
setlocal enabledelayedexpansion
rem #####################################################################
rem Run test for the Gradle scenario of loading native code from a jar
rem With Gradle builds all the source code is put in one .so file,
rem which should only be loaded once
rem
rem Option argument: # of times to test loading the native code
rem
rem @since:  NeXtMidas 4.1.4
rem @author: Zachary Matthews
rem
rem NOTE: Based on original runNativeCodeJar.sh by Jeanette McCall
rem
rem #####################################################################

rem Check if JAVA_HOME is defined
if ["%JAVA_HOME%"] == [""] (
  if ["%JAVAHOME%"] == [""] (
    echo JAVA_HOME and JAVAHOME not defined
    rem exit /b 1
  ) else (
    echo JAVAHOME defined, setting JAVA_HOME to JAVAHOME
    set JAVA_HOME=%JAVAHOME%
  )
)

rem ##################################################################################
rem Dynamically set nm_root regardless of where runNativeCodeJar.sh gets called from
rem ##################################################################################

rem Get the full absolute path of the directory that contains runNativeCodeJar.bat
set dirPath=%~dp0

echo %dirPath% | find "\sys\src\test\midas\nxm\sys\test\" >nul 2>&1 && (set isGradle=true) || (set isGradle=false)

if %isGradle% == true (
  set nm_root=%dirPath:~0,-33%
) else (
  set nm_root=%dirPath:~0,-14%
)

rem ############################
rem Set reflective access flag
rem ############################
if exist %JAVA_HOME%\lib\tools.jar (
  set nm_reflective_access=
) else (
  set nm_reflective_access=--add-opens java.logging/java.util.logging=ALL-UNNAMED --add-opens java.base/java.security=ALL-UNNAMED
)

rem ###############################################
rem Set number of iterations for the running test
rem ###############################################
if ["%1"] == [""] (
  set /a numRuns=10
) else  (
  set /a numRuns=%1
)

echo Starting NeXtMidas and running native code load test %numRuns% times - may take a few seconds to complete

rem ###################################
rem Run the native-code-from-jar test
rem ###################################
set /a numRunsMinus1 = %numRuns%-1
for /l %%c in (0,1,%numRunsMinus1%) do (
  %JAVA_HOME%\bin\java -DNONATIVE=FALSE %nm_reflective_access% -DNMROOT="classpath:" -classpath "%nm_root%\jars\*" nxm.sys.test.TestNeXtMidas loadNativeCodeFromJar
)

echo COMPLETED - if there were no exceptions, this test passed

set dirPath=
set isGradle=
set nm_root=
set nm_reflective_access=
set numRuns=
set numRunsMinus1=
