#!/bin/csh
######################################################################
# Run test for the Gradle scenario of loading native code from a jar #
# With Gradle builds all the source code is put in one .so file,     #
# which should only be loaded once                                   #
#                                                                    #
# Option argument: # of times to test loading the native code        #
######################################################################

###################################################################################
# Dynamically set nm_root regardless of where runNativeCodeJar.sh gets called from #
###################################################################################
# Get the full absolute path of runNativeCodeJar.sh regardless of where it's being called from
set filePath=`readlink -f $0`

# Get the full absolute path of the directory that contains runNativeCodeJar.sh
set dirPath=`dirname $filePath`

# Scenario 1: Path for dir containing runNativeCodeJar.sh for Gradle full build:     <nmroot-dir>/sys/src/test/midas/nxm/sys/test
# Scenario 2: Path for dir containing runNativeCodeJar.sh for Gradle softlink build: <nmroot-dir>                   /nxm/sys/test

# Both scenarios contain "/nxm/sys/test", so must filter this out first
set testSuffix="\/nxm\/sys\/test"
set nm_root=`echo $dirPath | sed s/$testSuffix//g`

# Only Scenario 1 will contain "/sys/src/test/midas"
# This is because the dir path read in is the path to the original file (independent of symbolic links),
# and the Gradle softlink build (Scenario 2) maintains the original files in the original NeXtMidas directory structure.
set gradleRestructSuffix="\/sys\/src\/test\/midas"
set nm_root=`echo $nm_root | sed s/$gradleRestructSuffix//g`

##############################
# Set reflective access flag #
##############################
if ( -f ${JAVAHOME}/lib/tools.jar ) then
  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"
endif

#################################################
# Set number of iterations for the running test #
#################################################
if ($# < 1) then
  set num_runs = 10
else 
  set num_runs = $1
endif

echo "Starting NeXtMidas and running native code load test $num_runs times - may take a few seconds to complete"
set counter = 1

#####################################
# Run the native-code-from-jar test #
#####################################
while ($counter <= $num_runs)
  $JAVA_HOME/bin/java -DNONATIVE=FALSE $nm_reflective_access -DNMROOT="classpath:" -classpath "$nm_root/jars/*" nxm.sys.test.TestNeXtMidas loadNativeCodeFromJar
  @ counter = $counter + 1
end

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