# - Try to find the libcppunit libraries
# Once done this will define
#
# CppUnit_FOUND - system has libcppunit
# CPPUNIT_INCLUDE_DIR - the libcppunit include directory
# CPPUNIT_LIBRARIES - libcppunit library

include (MacroEnsureVersion)

if(NOT CPPUNIT_MIN_VERSION)
  SET(CPPUNIT_MIN_VERSION 1.14.0)
endif(NOT CPPUNIT_MIN_VERSION)

FIND_PROGRAM(CPPUNIT_CONFIG_EXECUTABLE cppunit-config )

IF(CPPUNIT_INCLUDE_DIR AND CPPUNIT_LIBRARIES)

    # in cache already
    SET(CppUnit_FOUND TRUE)

ELSE(CPPUNIT_INCLUDE_DIR AND CPPUNIT_LIBRARIES)

    SET(CPPUNIT_INCLUDE_DIR)
    SET(CPPUNIT_LIBRARIES)

    IF(CPPUNIT_CONFIG_EXECUTABLE)
        EXEC_PROGRAM(${CPPUNIT_CONFIG_EXECUTABLE} ARGS --cflags RETURN_VALUE _return_VALUE OUTPUT_VARIABLE CPPUNIT_CFLAGS)
        EXEC_PROGRAM(${CPPUNIT_CONFIG_EXECUTABLE} ARGS --libs RETURN_VALUE _return_VALUE OUTPUT_VARIABLE CPPUNIT_LIBRARIES)
        EXEC_PROGRAM(${CPPUNIT_CONFIG_EXECUTABLE} ARGS --version RETURN_VALUE _return_VALUE OUTPUT_VARIABLE CPPUNIT_INSTALLED_VERSION)
        STRING(REGEX REPLACE "-I(.+)" "\\1" CPPUNIT_CFLAGS "${CPPUNIT_CFLAGS}")
    ELSE(CPPUNIT_CONFIG_EXECUTABLE)
        # in case win32 needs to find it the old way?
        FIND_PATH(CPPUNIT_CFLAGS cppunit/TestRunner.h PATHS /usr/include /usr/local/include )
        FIND_LIBRARY(CPPUNIT_LIBRARIES NAMES cppunit PATHS /usr/lib /usr/local/lib )
        # how can we find cppunit version?
        MESSAGE (STATUS "Ensure your cppunit installed version is at least ${CPPUNIT_MIN_VERSION}")
        SET (CPPUNIT_INSTALLED_VERSION ${CPPUNIT_MIN_VERSION})
    ENDIF(CPPUNIT_CONFIG_EXECUTABLE)

    SET(CPPUNIT_INCLUDE_DIR ${CPPUNIT_CFLAGS} "${CPPUNIT_CFLAGS}/cppunit")

ENDIF(CPPUNIT_INCLUDE_DIR AND CPPUNIT_LIBRARIES)

IF(CPPUNIT_INCLUDE_DIR AND CPPUNIT_LIBRARIES)

  SET(CppUnit_FOUND TRUE)

  if(NOT CppUnit_FIND_QUIETLY)
    MESSAGE (STATUS "Found cppunit: ${CPPUNIT_LIBRARIES}")
  endif(NOT CppUnit_FIND_QUIETLY)

  IF(CPPUNIT_CONFIG_EXECUTABLE)
    EXEC_PROGRAM(${CPPUNIT_CONFIG_EXECUTABLE} ARGS --version RETURN_VALUE _return_VALUE OUTPUT_VARIABLE CPPUNIT_INSTALLED_VERSION)
  ENDIF(CPPUNIT_CONFIG_EXECUTABLE)

  macro_ensure_version( ${CPPUNIT_MIN_VERSION} ${CPPUNIT_INSTALLED_VERSION} CPPUNIT_INSTALLED_VERSION_OK )

  IF(NOT CPPUNIT_INSTALLED_VERSION_OK)
    MESSAGE ("** CppUnit version is too old: found ${CPPUNIT_INSTALLED_VERSION} installed, ${CPPUNIT_MIN_VERSION} or newer is required")
    SET(CppUnit_FOUND FALSE)
  ENDIF(NOT CPPUNIT_INSTALLED_VERSION_OK)

ELSE(CPPUNIT_INCLUDE_DIR AND CPPUNIT_LIBRARIES)

  SET(CppUnit_FOUND FALSE CACHE BOOL "Not found cppunit library")

ENDIF(CPPUNIT_INCLUDE_DIR AND CPPUNIT_LIBRARIES)

MARK_AS_ADVANCED(CPPUNIT_INCLUDE_DIR CPPUNIT_LIBRARIES)
