cmake_minimum_required(VERSION 3.2.3)

# Restrict building in top-level directory
if("${CMAKE_CURRENT_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_BINARY_DIR}")
    message(FATAL_ERROR "In-source builds are not allowed.\nPlease create a "
        "build directory first and execute cmake configuration from this "
        "directory. Example: mkdir build && cd build && cmake ..")
endif()

project(ddX VERSION 0.1.1 LANGUAGES Fortran CXX)
# If ddX is a subproject, append ddx_ prefix to all targets.
if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME)
    set(ddx_is_subproject false)
    set(ddx_ "")
else()
    set(ddx_is_subproject true)
    set(ddx_ "ddx_")
endif()

# Add flag in case of Intel compiler to avoid fast inaccurate math
if(CMAKE_Fortran_COMPILER_ID MATCHES "Intel")
    add_compile_options(-fp-model=precise)
    message(STATUS "Extending Intel compiler flags by \"-fp-model=precise\"")
endif()

# Requirements: Blas and Lapack
find_package(BLAS REQUIRED)
find_package(LAPACK REQUIRED)
find_package(OpenMP REQUIRED)

# Coverage compiler flag setup
option(COVERAGE "Generate code coverage report" OFF)
if(COVERAGE)
    message(STATUS "Code coverage report can be generated by \"make coverage\" command.")
    include(cmake/CodeCoverage.cmake)
    append_coverage_compiler_flags()
    # Set excluded coverage paths
    set(COVERAGE_EXCLUDES "tests/*" "src/llgnew.f" "src/bessel.f90" "src/cbessel.F90")
    # Setup a target for an overall coverage
    setup_target_for_coverage_lcov(NAME ${ddx_}coverage
        EXECUTABLE ctest -R ${ddx_}tests
        LCOV_ARGS --no-external)
endif()

# Documentation
find_package(Doxygen)
if(DOXYGEN_FOUND)
    add_custom_target(docs COMMAND "${DOXYGEN_EXECUTABLE}" Doxyfile
                      WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR})
endif()

# Pass onto subdirectories
add_subdirectory(src)

option(EXAMPLES "Compile examples" ON)
if (EXAMPLES)
    enable_language(C)
    add_subdirectory(examples)
endif()

option(TESTS "Compile tests" ON)
if (TESTS)
    enable_testing()
    add_subdirectory(tests)
endif()
