#!/bin/bash
#-------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
#-------------------------------------------------------------

# A script to execute the tests inside the docker container.

cd /github/workspace/src/main/cpp
./build.sh
cd /github/workspace

export MAVEN_OPTS="-Xmx512m"

# Printed when Maven fails to download an artifact (transient repo/network
# error), unlike genuine compilation or test failures which fail fast.
transient_mvn_error="Could not transfer artifact"

log="/tmp/sysdstest.log"
compile_log="$(mktemp)"
# test-compile downloads all dependencies; retry once on a transient repo
# error so the test run below can resolve them from the local cache.
mvn -ntp -B test-compile 2>&1 | tee "$compile_log" | stdbuf -oL grep -E "BUILD|Total time:|---|Building SystemDS"
compile_status=${PIPESTATUS[0]}

# True only when test-compile failed because of a transient repository download.
compile_transient_failure=false
[ "$compile_status" -ne 0 ] && grep -qE "$transient_mvn_error" "$compile_log" && compile_transient_failure=true
rm -f "$compile_log"

if [ "$compile_transient_failure" = true ]; then
	echo "Transient Maven repository error; retrying test-compile in 15s..."
	sleep 15
	mvn -ntp -B test-compile 2>&1 | stdbuf -oL grep -E "BUILD|Total time:|---|Building SystemDS"
else
	echo "No transient Maven repository error detected; no retry needed."
fi
mvn -ntp -B test -D maven.test.skip=false -D automatedtestbase.outputbuffering=true -D test=$1 2>&1 \
	| stdbuf -oL grep -Ev "already exists in destination.|Using incubator" \
	| tee $log


grep_args="SUCCESS"
grepvals="$( tail -n 100 $log | grep $grep_args)"

if [[ $grepvals == *"SUCCESS"* ]]; then
	# Merge Federated test runs.
	# if merged jacoco exist temporarily rename to not overwrite.
	[ -f target/jacoco.exec ] && mv target/jacoco.exec target/jacoco_main.exec
	# merge jacoco files.
	mvn -ntp -B jacoco:merge 2>&1 | stdbuf -oL grep -E "jacoco"

	exit 0
else
	exit 1
fi
