cmake_minimum_required(VERSION 3.22)

set(CTEST_BINARY_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/build)
set(CTEST_SOURCE_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})

if(NOT "${GITHUB_PR_ID}" STREQUAL "")
  set(CTEST_CHANGE_ID ${GITHUB_PR_ID})
  set(CTEST_BUILD_NAME "${CTEST_BUILD_NAME}-PR${GITHUB_PR_ID}")
endif()

set(CTEST_UPDATE_COMMAND git)
set(CTEST_UPDATE_VERSION_ONLY 1)
set(CTEST_CMAKE_GENERATOR "Unix Makefiles")

file(REMOVE_RECURSE "${CTEST_BINARY_DIRECTORY}")

ctest_start(${CDASH_MODEL})
ctest_update()
ctest_configure(OPTIONS "${CMAKE_OPTIONS}" RETURN_VALUE config_ret)
ctest_build(RETURN_VALUE build_ret)
if(OUTPUT_JUNIT_FILE)
  ctest_test(OUTPUT_JUNIT "${OUTPUT_JUNIT_FILE}" RETURN_VALUE test_ret)
else()
  ctest_test(RETURN_VALUE test_ret)
endif()
ctest_submit()

if(NOT config_ret EQUAL 0)
  message(FATAL_ERROR "Error during configuration! Exit code: ${config_ret}")
endif()
if(NOT build_ret EQUAL 0)
  message(FATAL_ERROR "Error during build! Exit code: ${build_ret}")
endif()
if(NOT test_ret EQUAL 0)
  message(FATAL_ERROR "Error during testing! Exit code: ${test_ret}")
endif()
