#
# This is not a script per se, it is a common part that every continuous script should include using
# include("${CTEST_SOURCE_DIRECTORY}/sdk/cmake/ctest/ci-setup.cmake")
#
# note that required variables for setup are:
# CTEST_SITE                      the name of the current machine (it will appear in the "site" column on the cdash)
# CI_MODE                         ctest mode (Nightly, Continuous, Experimental...), Experimental is default
# CI_ID                           the unique id (eg: "Pipeline $CI_PIPELINE_ID Job $CI_BUILD_ID Configure"
# CI_BRANCH                       the name of the current branch (check directly with git if not defined)
# CI_BUILD_SETTINGS               compiler-arch-buildtype string (eg. "GCC-64bits-Debug")
# CTEST_SOURCE_DIRECTORY          path to CamiTK code source directory
# CTEST_BINARY_DIRECTORY          path to the intended build directory

# ------------------------ STEP 1: information step ------------------------
message(STATUS "Step 1. Gather information about this test...")

# Need to be defined, for the build to run.
if(NOT DEFINED CTEST_SOURCE_DIRECTORY)
    message(FATAL_ERROR "Please provide the source directory of the continuous test with the CTEST_SOURCE_DIRECTORY argument")
endif()

if(NOT DEFINED CTEST_BINARY_DIRECTORY)
    message(FATAL_ERROR "Please provide the build directory of the continuous test with the CTEST_BINARY_DIRECTORY argument")
endif()

# Script configuration, depending of the build, computer running the script
# Update to feat each computer which runs this script

# Get VM compilation information given by ctest call command
if(CI_BUILD_SETTINGS)
    string(REGEX REPLACE "^(.*)-.*-.*" "\\1" COMPILER "${CI_BUILD_SETTINGS}")
    string(REGEX REPLACE "^.*-(.*)-.*" "\\1" ARCH "${CI_BUILD_SETTINGS}")
    string(REGEX REPLACE "^.*-.*-(.*)" "\\1" BUILDTYPE "${CI_BUILD_SETTINGS}")
else()
    message(FATAL_ERROR "CI_BUILD_SETTINGS value must be given as option of the ctest command calling this script.")
endif()

# Compose with those variables the CTest required ones.
site_name(CTEST_SITE)

# get the git hash
find_package(Git QUIET)
if(GIT_FOUND)
    include("${CTEST_SOURCE_DIRECTORY}/sdk/cmake/modules/macros/GetGitInfo.cmake")
    set(CMAKE_SOURCE_DIR ${CTEST_SOURCE_DIRECTORY})
    get_git_info(${CTEST_SOURCE_DIRECTORY})
    set(CURRENT_GIT_HASH ${CAMITK_GIT_ABBREVIATED_HASH})
    # in gitlab context, we get a "detached HEAD", so if you ask git in a gitlab runner docker
    # you only get "HEAD", which is not very helpful
    if (NOT CI_BRANCH)
        set(CURRENT_GIT_BRANCH ${CAMITK_GIT_ABBREVIATED_HASH})
    endif()
else()
    set(CURRENT_GIT_HASH "[unknown hash]")
    if (NOT CI_BRANCH)
        set(CURRENT_GIT_BRANCH "[unknown branch]")
    endif()
endif()

# if CURRENT_GIT_BRANCH is not yet defined at this stage, it means that CI_BRANCH is defined... just use it
if (NOT CURRENT_GIT_BRANCH)
    set(CURRENT_GIT_BRANCH ${CI_BRANCH})
endif()

# set the build name using the compiler and commit hash
set(CTEST_BUILD_NAME "${CURRENT_GIT_BRANCH} ${CURRENT_GIT_HASH} ${CI_BUILD_SETTINGS}")

if(UNIX)
    set(CTEST_CMAKE_GENERATOR  "Ninja" )
elseif(WIN32)
    if(COMPILER MATCHES "MinGW" OR "MINGW")
        set(CTEST_CMAKE_GENERATOR "MinGW Makefiles" )
    elseif(COMPILER MATCHES "MSVC2019") # only 64 bit supports
        set(CTEST_CMAKE_GENERATOR "Visual Studio 16 2019")
    elseif(COMPILER MATCHES "MSVC2022") # only 64 bit supports
        set(CTEST_CMAKE_GENERATOR "Visual Studio 17 2022")
    elseif(COMPILER MATCHES "Ninja")
        set(CTEST_CMAKE_GENERATOR "Ninja")
        if("${CMAKE_CXX_FLAGS}" STREQUAL "")
            # set flag
            set(CMAKE_CXX_FLAGS "/EHsc")
        else()
            # add to existing flag (need some test)
            set(CMAKE_CXX_FLAGS "\"${CMAKE_CXX_FLAGS} /EHsc\"")
        endif()
    else()
        message(FATAL_ERROR "CTEST COMPILER ERROR : No proper or supported compiler found, please check ctest command syntax or update this script.")
    endif()
endif()

if(BUILDTYPE)
    set(CTEST_BUILD_CONFIGURATION ${BUILDTYPE})
    set(CTEST_CONFIGURATION_TYPE ${BUILDTYPE})
else()
    message(FATAL_ERROR "NO BUILD TYPE : Please provide a build type: Debug or Release")
endif()

# parallelize ci scripts if possible
include(ProcessorCount)
ProcessorCount(NUMBER_OF_PROC)
message(STATUS "Detected ${NUMBER_OF_PROC} processors")
if(NOT NUMBER_OF_PROC EQUAL 0)
  set(CTEST_BUILD_FLAGS -j${NUMBER_OF_PROC})
  set(ctest_test_args ${ctest_test_args} PARALLEL_LEVEL ${NUMBER_OF_PROC})
endif()

# CMake configuration (put here all the configure flags)
set(CTEST_CONFIGURE_COMMAND "\"${CMAKE_COMMAND}\" -Wno-dev -G \"${CTEST_CMAKE_GENERATOR}\"")
set(CTEST_CONFIGURE_COMMAND "${CTEST_CONFIGURE_COMMAND} -DCMAKE_BUILD_TYPE:STRING=${CTEST_BUILD_CONFIGURATION}")
set(CTEST_CONFIGURE_COMMAND "${CTEST_CONFIGURE_COMMAND} -DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}" )
if(COMPILER MATCHES "MSVC2010" AND ARCH MATCHES "64bits") # Do not compile MML and PhysicalModel until libxml2 MSVC2010 x64 bug remains.
    set(CTEST_CONFIGURE_COMMAND "${CTEST_CONFIGURE_COMMAND} -DACTION_MML=FALSE -DCOMPONENT_MML=FALSE -DCOMPONENT_PHYSICALMODEL=FALSE")
endif()
set(CTEST_CONFIGURE_COMMAND "${CTEST_CONFIGURE_COMMAND} -DCEP_IMAGING=TRUE -DCEP_MODELING=TRUE -DCEP_TUTORIALS=TRUE -DAPIDOC_SDK=TRUE -DCAMITK_TEST_COVERAGE=TRUE ${CTEST_SOURCE_DIRECTORY}")
# python integration
set(CTEST_CONFIGURE_COMMAND "${CTEST_CONFIGURE_COMMAND} -DPYTHON_BINDING=TRUE")

# get CamiTK CDash server configuration
include("${CTEST_SOURCE_DIRECTORY}/CTestConfig.cmake")

# append only if not a configure stage (at configure stage a new timestamp should be generated)
if (NOT ${CI_STAGE} MATCHES "Configure")    
    set(CI_APPEND "APPEND")
endif()

# Start the cdash report
# The type of build that this script will make 
if (CI_MODE)
    if(${CI_MODE} MATCHES "Nightly" OR ${CI_MODE} MATCHES "Continuous")
        ctest_start(${CI_MODE} TRACK ${CI_MODE} ${CI_APPEND})
    else()
        # if not nightly or continuous, then it is an experimental mode
        ctest_start(Experimental TRACK Experimental ${CI_APPEND})
    endif()
else()
    # if nothing specified, it must be continuous (e.g., triggered by a commit to develop)
    ctest_start(Continuous TRACK Continuous ${CI_APPEND})
endif()
