# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

#[=======================================================================[.rst:
FindGeekbit
-----------

Find Geekbit (an open source software development kit for the Geekbit
handheld video game console) libraries and header files.

Imported targets
^^^^^^^^^^^^^^^^

This module defines the following :prop_tgt:`IMPORTED` targets:

  ``geekbit::geekbit``,
  The geekbit library, if found.

Result variables
^^^^^^^^^^^^^^^^

This module will set the following variables in your project:

``GEEKBIT_FOUND``
  true if geekbit libraries and header files were found.
``GEEKBIT_VERSION``
  geekbit release version
``GEEKBIT_INCLUDE_DIRS``
  the directory containing the geekbit headers; note
  ``GEEKBIT_INCLUDE_DIRS`` is also required
``GEEKBIT_LIBRARIES``
  geekbit libraries to be linked; note ``GEEKBIT_LIBRARIES`` is also
  required

#]=======================================================================]

find_path(GEEKBIT_INCLUDE_DIRS
    NAMES
        geekbit/gb.h
    HINTS
        ENV GEEKBIT_PATH
    PATH_SUFFIXES
        include
)

find_library(GEEKBIT_LIBRARIES
    NAMES geekbit
    HINTS
        ENV GEEKBIT_PATH
    PATH_SUFFIXES
        lib
)

# Header files are meant to be included as "geekbit/<file>.h". Therefore,
# the "geekbit" directory must not be referred to by GEEKBIT_INCLUDE_DIRS.
string(REGEX REPLACE "include/geekbit[/]*$"
    "include" GEEKBIT_INCLUDE_DIRS ${GEEKBIT_INCLUDE_DIRS})

if(GEEKBIT_INCLUDE_DIRS AND EXISTS "${GEEKBIT_INCLUDE_DIRS}/geekbit/version.h")
    set(version_regex "^#define[ \t]+GEEKBIT_VERSION_STRING[ \t]+\"([0-9\.]+)\"$")
    file(STRINGS "${GEEKBIT_INCLUDE_DIRS}/geekbit/version.h" GEEKBIT_VERSION_LINE REGEX ${version_regex})
    string(REGEX REPLACE ${version_regex} "\\1" GEEKBIT_VERSION "${GEEKBIT_VERSION_LINE}")
    unset(GEEKBIT_VERSION_LINE)
    unset(version_regex)
endif()

include(FindPackageHandleStandardArgs)

find_package_handle_standard_args(Geekbit
    REQUIRED_VARS
        GEEKBIT_LIBRARIES GEEKBIT_INCLUDE_DIRS
    VERSION_VAR
        GEEKBIT_VERSION
)

if(GEEKBIT_FOUND)
    if(NOT TARGET Geekbit::Geekbit)
        add_library(Geekbit::Geekbit INTERFACE IMPORTED)
        target_include_directories(Geekbit::Geekbit
            INTERFACE "${GEEKBIT_INCLUDE_DIRS}")
        set_target_properties(Geekbit::Geekbit PROPERTIES
            IMPORTED_LOCATION "${GEEKBIT_LIBRARIES}")
    endif()
endif()
