find_path(periphery_PROJECT CMakeLists.txt HINTS "${CMAKE_SOURCE_DIR}/dependency/c-periphery")

if (periphery_PROJECT)
    set(periphery_FOUND TRUE)

    # Check for Linux kernel header files for character device GPIO support
    include(CheckIncludeFiles)
    CHECK_INCLUDE_FILES(linux/gpio.h HAVE_CDEV_GPIO_HEADERS)
    if (NOT HAVE_CDEV_GPIO_HEADERS)
        message(WARNING "Linux kernel header files not found for character device GPIO support. c-periphery will be built with legacy sysfs GPIO support only.")
    endif ()
    add_definitions(-DPERIPHERY_GPIO_CDEV_SUPPORT=$<BOOL:${HAVE_CDEV_GPIO_HEADERS}>)

    # Glob sources, headers, tests
    file(GLOB_RECURSE periphery_SOURCES ${periphery_PROJECT}/src/*.c)
    file(GLOB_RECURSE periphery_HEADERS ${periphery_PROJECT}/src/*.h)

    # Define C flags
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99 -pedantic -Wall -Wextra -Wno-stringop-truncation -fPIC")
    set(CMAKE_C_FLAGS_DEBUG "-g")
    set(CMAKE_C_FLAGS_RELEASE "-O3")

    # Include directories
    include_directories("${periphery_PROJECT}/src")

    # Declare library target
    add_library(periphery ${periphery_SOURCES} ${periphery_HEADERS})

    include(GNUInstallDirs)

    # Generate pkg-config pc file
    configure_file(${periphery_PROJECT}/src/libperiphery.pc.in ${CMAKE_CURRENT_BINARY_DIR}/libperiphery.pc @ONLY)

    # Declare install targets
    install(TARGETS periphery LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
    install(FILES ${periphery_HEADERS} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${CMAKE_FIND_PACKAGE_NAME})
    install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libperiphery.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)

    message(STATUS "Found c-periphery at: ${periphery_PROJECT}")
else ()
    message(FATAL_ERROR "Failed to locate c-periphery dependency")
endif ()
