cmake_minimum_required(VERSION 3.12.4)

# 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.0.2 REQUIRED
    HINTS /usr/lib/cmake)
# 4) extend the CMake module path such that bindings generator can be include within CMake
list(APPEND CMAKE_MODULE_PATH "${GridTools_MODULE_PATH}")

# 5) include c bindings module
include(gt_bindings)

enable_testing()

# 6) 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)
gt_add_bindings_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)
    # 7) If a library needs to be used from Fortran, it is necessary to call
    #    gt_enable_bindings_library_fortran with the bindings library in order to
    #    build the right modules
    gt_enable_bindings_library_fortran(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)
        gt_add_bindings_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(CMAKE_CUDA_COMPILER)
