#!/usr/bin/env bash
set -eo pipefail

cleanup() {
    # Remove if nothing was generated.
    [ -d artifacts ] && find artifacts -type d -empty -delete
}
trap cleanup EXIT

# Make a central directory to store all output artifacts of our test run to
# avoid having to configure multiple upload-artifacts steps in the workflow
# file.
OSSL_CI_ARTIFACTS_PATH="artifacts/"
if [ -n "${GITHUB_RUN_NUMBER}" ]; then
    OSSL_CI_ARTIFACTS_PATH="artifacts/github-${GITHUB_JOB}-${GITHUB_RUN_NUMBER}-${GITHUB_RUN_ID}/"
fi
mkdir -p "$OSSL_CI_ARTIFACTS_PATH"
export OSSL_CI_ARTIFACTS_PATH="$(cd "$OSSL_CI_ARTIFACTS_PATH"; pwd)"

# Enable core dumps so a crashing test leaves a core with every thread's stack
# for diagnosis. Only a failing run produces one; green runs dump nothing.
# Linux only for now; best effort - a runner that disallows this just won't
# dump.
if [ "$(uname)" = Linux ]; then
    ulimit -c unlimited 2>/dev/null || true
    if command -v sudo >/dev/null 2>&1; then
        sudo mkdir -p /tmp/cores && sudo chmod 1777 /tmp/cores || true
        echo '/tmp/cores/core.%e.%p' | sudo tee /proc/sys/kernel/core_pattern >/dev/null 2>&1 || true
    fi
fi

# Run the tests. This might fail, but we need to capture artifacts anyway.
set +e
make test HARNESS_JOBS=${HARNESS_JOBS:-4} LHASH_WORKERS=${LHASH_WORKERS:-16} "$@"
RESULT=$?
set -e

# Move the qlog output from the radix tests into the artifacts staging
# directory.
if [ -d "test-runs/test_quic_radix/qlog-output" ]; then
    mv "test-runs/test_quic_radix/qlog-output" "$OSSL_CI_ARTIFACTS_PATH/quic_radix_qlog"
fi

# Collect any core dumps together with the matching test binary, so the core is
# usable with gdb without a rebuild. The executable name is the %e field of the
# core file name. Only a failing run produces any. Linux only for now.
if [ "$(uname)" = Linux ]; then
    for core in /tmp/cores/core.*; do
        [ -f "$core" ] || continue
        exe=$(basename "$core"); exe=${exe#core.}; exe=${exe%.*}
        [ -f "test/$exe" ] && cp "test/$exe" "$OSSL_CI_ARTIFACTS_PATH/" || true
        mv "$core" "$OSSL_CI_ARTIFACTS_PATH/" || true
    done
fi

# Log the artifact tree.
echo "::group::List of artifact files generated"
echo "Test suite exited with $RESULT, artifacts path is $OSSL_CI_ARTIFACTS_PATH"
(cd "$OSSL_CI_ARTIFACTS_PATH"; find . -type f | sort)
echo "::endgroup::"

echo "Archive artifacts"
tar -czf artifacts.tar.gz $OSSL_CI_ARTIFACTS_PATH

exit $RESULT
