include(CheckIncludeFileCXX)
include(CheckLibraryExists)

set(JSONCPP_PATH "" CACHE PATH "Base path for json/json.h and lib/jsoncpp*")
set(JSONCPP_INCLUDE_DIRS "" CACHE PATH "Include path for json.h")
set(JSONCPP_LIBRARY_DIRS "" CACHE PATH "Path containing jsoncpp")

if(JSONCPP_PATH)
  set(JSONCPP_INCLUDE_DIRS "${JSONCPP_PATH}/include" CACHE PATH "Include path for json/json.h" FORCE)
  set(JSONCPP_LIBRARY_DIRS "${JSONCPP_PATH}/lib" CACHE PATH "Path containing jsoncpp" FORCE)
endif(JSONCPP_PATH)

if(JSONCPP_INCLUDE_DIRS)
  set(JSONCPP_INCLUDE_DIRS ${JSONCPP_INCLUDE_DIRS} CACHE INTERNAL "")
endif(JSONCPP_INCLUDE_DIRS)

if(JSONCPP_LIBRARY_DIRS)
  set(JSONCPP_LIBRARY_DIRS ${JSONCPP_LIBRARY_DIRS} CACHE INTERNAL "")
endif(JSONCPP_LIBRARY_DIRS)

if(NOT JSONCPP_FOUND)
  unset(HAVE_JSON_H)
  unset(HAVE_JSONCPP)
  unset(HAVE_JSON_H CACHE)
  unset(HAVE_JSONCPP CACHE)

  if(JSONCPP_INCLUDE_DIRS OR JSONCPP_LIBRARY_DIRS)
    set(CMAKE_REQUIRED_INCLUDES ${JSONCPP_INCLUDE_DIRS})
    check_include_file_cxx(json/json.h HAVE_JSON_H)
    if(HAVE_JSON_H)
      find_library(HAVE_JSONCPP jsoncpp "${JSONCPP_LIBRARY_DIRS}")
      if(HAVE_JSONCPP)
        set(JSONCPP_LIBRARIES jsoncpp CACHE INTERNAL "")
        set(JSONCPP_FOUND TRUE CACHE INTERNAL "Found jsoncpp" FORCE)
      else(HAVE_JSONCPP)
        message(STATUS "Couldn't find lib jsoncpp in ${JSONCPP_LIBRARY_DIRS}")
      endif(HAVE_JSONCPP)
    else(HAVE_JSON_H)
      message(STATUS "Couldn't find <json/json.h> in ${JSONCPP_INCLUDE_DIRS}")
    endif(HAVE_JSON_H)
  else(JSONCPP_INCLUDE_DIRS OR JSONCPP_LIBRARY_DIRS)
    pkg_check_modules(JSONCPP jsoncpp)
    if(NOT JSONCPP_FOUND)
      check_include_file_cxx(json/json.h HAVE_JSON_H)
      if(HAVE_JSON_H)
        find_library(HAVE_JSONCPP jsoncpp "")
        if(HAVE_JSONCPP)
          set(JSONCPP_LIBRARIES jsoncpp CACHE INTERNAL "")
          set(JSONCPP_FOUND TRUE CACHE INTERNAL "Found jsoncpp" FORCE)
        else(HAVE_JSONCPP)
          message(STATUS "Couldn't find lib jsoncpp")
        endif(HAVE_JSONCPP)
      else(HAVE_JSON_H)
        message(STATUS "Couldn't find <json/json.h>")
      endif(HAVE_JSON_H)
    endif(NOT JSONCPP_FOUND)
  endif(JSONCPP_INCLUDE_DIRS OR JSONCPP_LIBRARY_DIRS)
endif(NOT JSONCPP_FOUND)

if(NOT JSONCPP_FOUND)
  if(JSONCPP_FIND_REQUIRED)
    message(FATAL_ERROR "Could not find jsoncpp")
  endif(JSONCPP_FIND_REQUIRED)
endif(NOT JSONCPP_FOUND)

mark_as_advanced(JSONCPP_PATH JSONCPP_INCLUDE_DIRS JSONCPP_LIBRARY_DIRS)
