#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#
option(CODECHECKER "Turns on codecheck processing if it is found." OFF)
option(CODECHECKER_STORE "Store results on central codechecker server" OFF)
option(CODECHECKER_RUN "Name of the codechecker run" "run-1")
option(CODECHECKER_BRANCH "Name of the branch codecheker is run for" "unknown")
option(CODECHECKER_URL "URL and product link to codechecker server" "http://localhost:8001/Default")
option(CODECHECK_TRIM_PATH "beginning of the path to be removed when storing" "/tmp")

find_program(CODECHECKER_PATH
    NAME CodeChecker
    PATHS ~/bin/
          /usr/bin/
          /usr/local/bin
)

if (CODECHECKER_PATH )
  message(STATUS "CodeChecker found")
else()
  message(STATUS "CodeChecker not found")
endif()

# export compile commands to json file to be used by atom c++ ide (clangd)
set(CMAKE_EXPORT_COMPILE_COMMANDS 1)
set(CODECHECKER_COMPILE_COMMANDS "${CMAKE_BINARY_DIR}/compile_commands.json")

# check if a skip file exists
if(EXISTS ${CMAKE_SOURCE_DIR}/codecheck.skip)
  set(CODECHECKER_SKIP "-i${CMAKE_SOURCE_DIR}/codecheck.skip")
endif()


# output directory for codecheck analysis
set(CODECHECKER_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/codechecker_results)

# html output directory
set(CODECHECKER_HTML_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/codechecker_html)

# Common initialization/checks
if(CODECHECKER AND CODECHECKER_PATH AND NOT CODECHECKER_ADDED)
  set(CODECHECKER_ADDED ON)

  IF(NOT TARGET codechecker)

  add_custom_target(codechecker
                    COMMAND ${CODECHECKER_PATH}
                            analyze
                            ${CODECHECKER_SKIP}
                            -j 4
                            -o ${CODECHECKER_OUTPUT_DIRECTORY}
                            ${CODECHECKER_COMPILE_COMMANDS}
                    )

  add_custom_target(codechecker-clean
                    COMMAND  rm -rf ${CODECHECKER_OUTPUT_DIRECTORY}
                    )


  add_custom_target(codechecker-html
                    COMMAND ${CODECHECKER_PATH}
                            parse
                            ${CODECHECKER_OUTPUT_DIRECTORY}
                            -e html
                            -o ${CODECHECKER_HTML_OUTPUT_DIRECTORY}
                    )

 if (CODECHECKER_STORE)
   add_custom_target(codechecker-store
                     COMMAND ${CODECHECKER_PATH}
                             store
                             --trim-path-prefix \"${CODECHECK_TRIM_PATH}\"
                             --tag \"${CODECHECKER_BRANCH}\"
                             -n \"${CODECHECKER_RUN}\"
                             --url ${CODECHECKER_URL}
                             ${CODECHECKER_OUTPUT_DIRECTORY}
                     )
 endif()

endif()
endif()
