include(CheckIncludeFiles)
include(CheckLibraryExists)

set(LIBEV_PATH "" CACHE PATH "Base path for include/ev.h and lib/libev*")
set(LIBEV_INCLUDE_PATH "" CACHE PATH "Include path for ev.h")
set(LIBEV_LIBDIR "" CACHE PATH "Path containing libev")

if(LIBEV_PATH)
  set(LIBEV_INCLUDE_PATH "${LIBEV_PATH}/include" CACHE PATH "Include path for ev.h" FORCE)
  set(LIBEV_LIBDIR "${LIBEV_PATH}/lib" CACHE PATH "Path containing libev" FORCE)
endif(LIBEV_PATH)

if(LIBEV_INCLUDE_PATH)
  set(LIBEV_INCLUDE_DIRS ${LIBEV_INCLUDE_PATH} CACHE INTERNAL "")
endif(LIBEV_INCLUDE_PATH)

if(LIBEV_LIBDIR)
  set(LIBEV_LIBRARY_DIRS ${LIBEV_LIBDIR} CACHE INTERNAL "")
endif(LIBEV_LIBDIR)

if(NOT LIBEV_FOUND)
  unset(HAVE_EV_H)
  unset(HAVE_LIBEV)
  unset(HAVE_EV_H CACHE)
  unset(HAVE_LIBEV CACHE)

  if(LIBEV_INCLUDE_PATH OR LIBEV_LIBDIR)
    set(CMAKE_REQUIRED_INCLUDES ${LIBEV_INCLUDE_PATH})
    check_include_files(ev.h HAVE_EV_H)
    if(HAVE_EV_H)
      check_library_exists(ev ev_time "${LIBEV_LIBDIR}" HAVE_LIBEV)
      if(HAVE_LIBEV)
        set(LIBEV_LIBRARIES ev CACHE INTERNAL "")
        set(LIBEV_FOUND TRUE CACHE INTERNAL "Found libev" FORCE)
      else(HAVE_LIBEV)
        message(STATUS "Couldn't find lib ev in ${LIBEV_LIBDIR}")
      endif(HAVE_LIBEV)
    else(HAVE_EV_H)
      message(STATUS "Couldn't find <ev.h> in ${LIBEV_INCLUDE_PATH}")
    endif(HAVE_EV_H)
  else(LIBEV_INCLUDE_PATH OR LIBEV_LIBDIR)
    pkg_check_modules(LIBEV libev)
    if(NOT LIBEV_FOUND)
      check_include_files(ev.h HAVE_EV_H)
      if(HAVE_EV_H)
        check_library_exists(ev ev_time "" HAVE_LIBEV)
        if(HAVE_LIBEV)
          set(LIBEV_LIBRARIES ev CACHE INTERNAL "")
          set(LIBEV_FOUND TRUE CACHE INTERNAL "Found libev" FORCE)
        else(HAVE_LIBEV)
          message(STATUS "Couldn't find lib ev")
        endif(HAVE_LIBEV)
      else(HAVE_EV_H)
        message(STATUS "Couldn't find <ev.h>")
      endif(HAVE_EV_H)
    endif(NOT LIBEV_FOUND)
  endif(LIBEV_INCLUDE_PATH OR LIBEV_LIBDIR)
endif(NOT LIBEV_FOUND)

if(NOT LIBEV_FOUND)
  if(LibEV_FIND_REQUIRED)
    message(FATAL_ERROR "Could not find libev")
  endif(LibEV_FIND_REQUIRED)
endif(NOT LIBEV_FOUND)

mark_as_advanced(LIBEV_PATH LIBEV_INCLUDE_PATH LIBEV_LIBDIR)
