# Usage:
# 1. add 'setup_openmp()' after catkin_simple command
# 2. add ${OpenMP_LIBS} to target_link_libraries of your library
# 3. add ${OpenMP_FLAGS} to target_compile_options(<YOUR_LIBRARY> PRIVATE ${OpenMP_FLAGS}) of your library
macro(setup_openmp)
  if(APPLE)
    set(LLVM_PATH "/usr/local/opt/llvm")
    find_package(LLVM HINTS ${LLVM_PATH}/lib/cmake/llvm)
    if (LLVM_FOUND)
      message(STATUS "Building with LLVM clang and omp support.")
      set(CMAKE_C_COMPILER ${LLVM_TOOLS_BINARY_DIR}/clang)
      set(CMAKE_CXX_COMPILER ${LLVM_TOOLS_BINARY_DIR}/clang++)
      set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fopenmp -L${LLVM_PATH}/lib -Wl,-rpath,${LLVM_PATH}/lib")
      set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fopenmp -L${LLVM_PATH}/lib -Wl,-rpath,${LLVM_PATH}/lib")
    else()
      message(STATUS "LLVM not found, building without omp support.")
    endif()
  else()
    find_package(OpenMP)
    if(OPENMP_FOUND)
      if(${CMAKE_CXX_COMPILER_ID} STREQUAL Clang)
        set(OpenMP_FLAGS ${OpenMP_CXX_FLAGS})
        set(OpenMP_LIBS omp)
        # add_definitions(-Wno-unknown-pragmas -fopenmp)
      elseif(${CMAKE_CXX_COMPILER_ID} STREQUAL GNU)
        set(OpenMP_FLAGS ${OpenMP_CXX_FLAGS})
        set(OpenMP_LIBS gomp)
        # add_definitions(-Wno-unknown-pragmas -fopenmp)
      else()
        message(WARNING "Unrecognized C++ compiler: ${CMAKE_CXX_COMPILER} ID: ${CMAKE_CXX_COMPILER_ID}. Compiling without openMP support.")
      endif()
    else()
      message(WARNING "OpenMP not found! Compiling without openMP support.")
    endif()
  endif()
endmacro()
