#------------------------------------------
# Manage Include what you use
#-------------------------------------------

# see https://stackoverflow.com/a/30951493
# and https://blog.kitware.com/static-checks-with-cmake-cdash-iwyu-clang-tidy-lwyu-cpplint-and-cppcheck/

# Flag CMAKE_CXX_INCLUDE_WHAT_YOU_USE is only available in CMake 3.3 and above
if(${CMAKE_VERSION} VERSION_GREATER "3.3" OR ${CMAKE_VERSION} VERSION_EQUAL "3.3") 

    option(CAMITK_INCLUDE_WHAT_YOU_USE "Enable the header analysis on you code, CMake version 3.3 or greater is needed" OFF)    

    if (CAMITK_INCLUDE_WHAT_YOU_USE)
        
        find_program(IWYU_EXECUTABLE NAMES include-what-you-use iwyu)
        
        if(IWYU_EXECUTABLE)
        
            set(IWYU_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/iwyu.out" CACHE PATH "Output filename for include-what-you-use")

            # set the cmake flag in order to generate include-what-you-use report all the time
            set(CMAKE_CXX_INCLUDE_WHAT_YOU_USE ${IWYU_EXECUTABLE})
            
            #-- define a target that generate the include-what-you-use report for all the project

            # determine cmake macro path
            if (NOT EXISTS ${SDK_TOP_LEVEL_SOURCE_DIR})
                # this macro is called outside the sdk 
                set(CAMITK_CMAKE_MACRO_PATH ${CAMITK_CMAKE_DIR}/macros/camitk/test)
                if(NOT IS_DIRECTORY ${CAMITK_CMAKE_MACRO_PATH})
                    # inside communityedition but not in sdk (modeling or imaging)
                    set(CAMITK_CMAKE_MACRO_PATH ${CMAKE_SOURCE_DIR}/sdk/cmake/modules/macros/camitk/test)
                endif()
            else()
                # directly use the macro source dir
                set(CAMITK_CMAKE_MACRO_PATH ${SDK_TOP_LEVEL_SOURCE_DIR}/cmake/modules/macros/camitk/test)
            endif()   

            add_custom_target(camitk-ce-iwyu
                            COMMAND ${CMAKE_COMMAND} -E echo "Running include-what-you-use. Results can be found in ${IWYU_OUTPUT}"
                            COMMAND ${CMAKE_COMMAND} --build ${CMAKE_CURRENT_BINARY_DIR} --target clean
                            COMMAND ${CMAKE_COMMAND} "-DCMAKE_CXX_INCLUDE_WHAT_YOU_USE=${IWYU_EXECUTABLE}" ${CMAKE_SOURCE_DIR}
                            COMMAND ${CMAKE_COMMAND}
                                    -DMAKE_ERROR_OUTPUT_FILE=${IWYU_OUTPUT}
                                    -P ${CAMITK_CMAKE_MACRO_PATH}/CamiTKMakeWithRedirectedError.cmake
                            COMMAND ${CMAKE_COMMAND} "-UCMAKE_CXX_INCLUDE_WHAT_YOU_USE" ${CMAKE_SOURCE_DIR}
                            COMMENT "Running include-what-you-use for all project"
            )
                        
        else ()
            message(FATAL_ERROR "Could not find the program include-what-you-use")
        endif()
    else()
        unset(CMAKE_CXX_INCLUDE_WHAT_YOU_USE)
    endif()

endif()

