cmake_minimum_required(VERSION 3.14.5)

# 1) GridTools needs the language CXX
project(GridTools-examples LANGUAGES CXX)

# enable CUDA if it is found on the system
include(../workaround_check_language.cmake) # see https://gitlab.kitware.com/cmake/cmake/issues/19013
_workaround_check_language(CUDA)
if(CMAKE_CUDA_COMPILER)
    # 2) Enable the CUDA language if you want to run your code on a CUDA-capable GPU. This
    #    must be done before calling `find_package(GridTools)`
    enable_language(CUDA)
endif()

# 3) find installed GridTools version
find_package(GridTools 1.1.3 REQUIRED
    HINTS /usr/lib/cmake)

# 4) In the future cpp_bindgen will not be shipped with GridTools, then the following
#    steps are needed to make the library available
# include(FetchContent)
# FetchContent_Declare(
#   cpp_bindgen
#   GIT_REPOSITORY https://github.com/GridTools/cpp_bindgen.git
#   GIT_TAG        master # consider replacing master by a tagged version
# )
# FetchContent_MakeAvailable(cpp_bindgen)

enable_testing()

# 5) generate a bindings library for mc-backend. This generates two targets:
#    - copy_stencil_lib_mc_c (the C library)
#    - copy_stencil_lib_mc_fortran (the Fortran Library)
bindgen_add_library(copy_stencil_lib_mc SOURCES copy_stencil_wrapper.cpp)
target_link_libraries(copy_stencil_lib_mc PUBLIC GridTools::gridtools)

include(CheckLanguage)
check_language(C)
if (CMAKE_C_COMPILER)
    enable_language(C)

    add_executable(example_driver_mc_c driver_mc.c)
    target_link_libraries(example_driver_mc_c copy_stencil_lib_mc_c)

    add_test(NAME example_driver_mc_c COMMAND $<TARGET_FILE:example_driver_mc_c>)
endif()

check_language(Fortran)
if (CMAKE_Fortran_COMPILER)
    enable_language(Fortran)
    # 6) If a library needs to be used from Fortran, it is necessary to call
    #    bindgen_enable_fortran_library with the bindings library in order to
    #    build the right modules
    bindgen_enable_fortran_library(copy_stencil_lib_mc)

    add_executable(example_driver_fortran driver.f90)
    target_link_libraries(example_driver_fortran copy_stencil_lib_mc_fortran)
    set_target_properties(example_driver_fortran PROPERTIES LINKER_LANGUAGE Fortran)
    add_test(NAME example_driver_fortran COMMAND $<TARGET_FILE:example_driver_fortran>)
endif()

if (CMAKE_CUDA_COMPILER)
    if(GRIDTOOLS_HAS_BACKEND_CUDA)
        bindgen_add_library(copy_stencil_lib_cuda SOURCES copy_stencil_wrapper.cu)
        target_link_libraries(copy_stencil_lib_cuda PUBLIC GridTools::gridtools)

        if (CMAKE_C_COMPILER_LOADED)
            add_executable(example_driver_cuda_c driver_cuda.c)
            target_link_libraries(example_driver_cuda_c copy_stencil_lib_cuda_c)
            add_test(NAME example_driver_cuda_c COMMAND $<TARGET_FILE:example_driver_cuda_c>)
        endif()
    endif()
endif()
