#!/usr/bin/env bash

set -eo pipefail

if [ "$GRAALVM_HOME" != "" ]
then
  export JAVA_HOME=$GRAALVM_HOME
  export PATH=$GRAALVM_HOME/bin:$PATH
fi

java -version

unset BABASHKA_PRELOADS
unset BABASHKA_CLASSPATH
unset BABASHKA_PRELOADS_TEST

echo "running tests part 1"
lein "do" clean, test "$@"

echo "running flaky tests"
lein "do" clean, test :flaky || true

export BABASHKA_PRELOADS='(defn __bb__foo [] "foo") (defn __bb__bar [] "bar")'
export BABASHKA_PRELOADS_TEST=true
echo "running tests part 2"
lein test :only babashka.main-test/preloads-test

export BABASHKA_PRELOADS='(defn ithrow [] (/ 1 0))'
export BABASHKA_PRELOADS_TEST=true
echo "running tests part 3"
lein test :only babashka.main-test/preloads-file-location-test

export BABASHKA_PRELOADS="(require '[env-ns])"
export BABASHKA_CLASSPATH_TEST=true
export BABASHKA_CLASSPATH="test-resources/babashka/src_for_classpath_test/env"
echo "running tests part 4"
lein test :only babashka.classpath-test/classpath-env-test

export BABASHKA_POD_TEST=true
lein test :only babashka.pod-test

export BABASHKA_SOCKET_REPL_TEST=true
lein test :only babashka.impl.socket-repl-test

# test invoking script in subdir with bb.edn in parent dir
unset BABASHKA_PRELOADS
unset BABASHKA_CLASSPATH
pushd test-resources/bb_in_root_script_in_other_dir
if [[ $BABASHKA_TEST_ENV = "native" ]]
then
   ../../bb dir/script.clj
fi
popd
