set -e

# prepare test environment
prepare() {
    cp -a default.build.properties Rakefile rakelib spec test "$AUTOPKGTEST_TMP"
    cp -a /usr/share/jruby/bin "$AUTOPKGTEST_TMP/bin"
    ln -s /usr/share/jruby/lib "$AUTOPKGTEST_TMP/lib"
    export LANG=C.UTF-8
    export LC_ALL=C.UTF-8
    export CI=1
    export JOBS=2

    # create home cache directory to avoid AppCDS warning on stderr
    mkdir -p "$HOME/.cache"
    # clear cache
    rm -f "$HOME/.cache/jruby-java*.jsa"

 }

# extra dependencies are needed to run the testsuite
install_gem_bundle() {
    echo "---> Start installing gem bundle"
    GEMFILE="${AUTOPKGTEST_TMP}/Gemfile"
    cp Gemfile "$GEMFILE"

    # append list of "bundled" gems to Gemfile
    while read -r gem version; do
        echo "gem '${gem}', '${version}'" >> "$GEMFILE"
    done < /usr/share/doc/jruby/bundled_gems

    # destination directory for installing gems
    export GEM_HOME="${AUTOPKGTEST_TMP}/gems"

    # run bundler
    jruby -S bundle install --gemfile "$GEMFILE"
    echo "---> Finished installing gem bundle"
}

spec_skip() {
    test_name="$1"
    test_file="$2"
    if [ "$test_name" = "ALL" ]; then
      sed -i "/it.*do$/a \    skip 'skipped for autopkgtest'" "${test_file}"
    else
      sed -i "/it \"${test_name}\" do$/a \    skip 'skipped for autopkgtest'" "${test_file}"
    fi
    echo "excluded test ${exclude_file}::${test_name}"
}

test_skip() {
    test_name="$1"
    test_file="$2"
    sed -i "/def ${test_name}$/a \    omit 'skipped for autopkgtest'" "${test_file}"
    echo "excluded test: ${exclude_file}::${test_name}"
}

mri_exclude() {
    test_name="$1"
    exclude_file="test/mri/excludes/$2"
    if [ ! -d "$(dirname ${exclude_file})" ]; then
        mkdir "$(dirname ${exclude_file})"
    fi
    if [ -f "${exclude_file}" ]; then
        if grep -q "^exclude :${test_name}," "${exclude_file}"; then
            echo "Warning: ${test_name} already exists in ${exclude_file}"
            return
        fi
        sed -i -e '$a\' "${exclude_file}"
    fi
    echo "exclude :${test_name}, \"autopkgtest\"" >> "${exclude_file}"
    echo "excluded test: ${exclude_file}::${test_name}"
}

# run 1 test at a time and output test names
# so we can more easily catch hanging tests
debug_tests() {
    export JOBS=1
    # modifies ADDITIONAL_TEST_OPTIONS
    sed -i 's/--tty=no/-v/' "$AUTOPKGTEST_TMP/rakelib/test.rake"
    # modifies TESTOPT
    sed -i 's/--no-use-color/--no-use-color -v/' "$AUTOPKGTEST_TMP/rakelib/test.rake"
    echo "** debugging mode enabled **"
}
