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

#[=======================================================================[.rst:
FindENET
-----------

Locate ENET library

This module defines:

::

  ENET, the name of the target to use with target_*() commands
  ENET_LIBRARIES, the name of the library to link against
  ENET_INCLUDE_DIRS, where to find the headers
  ENET_FOUND, if false, do not try to link against
  ENET_VERSION_STRING - human-readable string containing the
                             version of ENET

$ENETDIR is an environment variable that would correspond to the
./configure --prefix=$ENETDIR used in building ENET.
#]=======================================================================]

find_path(ENET_INCLUDE_DIRS
  NAMES
    enet/callbacks.h
    enet/enet.h
    enet/list.h
    enet/protocol.h
    enet/time.h
    enet/types.h
    enet/unix.h
    enet/utility.h
    enet/win32.h
  HINTS
    ENV ENETDIR
  PATH_SUFFIXES
    enet
    # path suffixes to search inside ENV{ENETDIR}
    include
)

if(CMAKE_SIZEOF_VOID_P EQUAL 8)
  set(VC_LIB_PATH_SUFFIX lib/x64)
else()
  set(VC_LIB_PATH_SUFFIX lib/x86)
endif()

find_library(ENET_LIBRARIES
  NAMES enet
  HINTS
    ENV ENETDIR
  PATH_SUFFIXES
    lib
    ${VC_LIB_PATH_SUFFIX}
)

if(ENET_INCLUDE_DIRS AND EXISTS "${ENET_INCLUDE_DIRS}/enet.h")
  file(STRINGS "${ENET_INCLUDE_DIRS}/enet.h" ENET_VERSION_MAJOR_LINE REGEX "^#define[ \t]+ENET_VERSION_MAJOR[ \t]+[0-9]+$")
  file(STRINGS "${ENET_INCLUDE_DIRS}/enet.h" ENET_VERSION_MINOR_LINE REGEX "^#define[ \t]+ENET_VERSION_MINOR[ \t]+[0-9]+$")
  file(STRINGS "${ENET_INCLUDE_DIRS}/enet.h" ENET_VERSION_PATCH_LINE REGEX "^#define[ \t]+ENET_VERSION_PATCH[ \t]+[0-9]+$")
  string(REGEX REPLACE "^#define[ \t]+ENET_VERSION_MAJOR[ \t]+([0-9]+)$" "\\1" ENET_VERSION_MAJOR "${ENET_VERSION_MAJOR_LINE}")
  string(REGEX REPLACE "^#define[ \t]+ENET_VERSION_MINOR[ \t]+([0-9]+)$" "\\1" ENET_VERSION_MINOR "${ENET_VERSION_MINOR_LINE}")
  string(REGEX REPLACE "^#define[ \t]+ENET_VERSION_PATCH[ \t]+([0-9]+)$" "\\1" ENET_VERSION_PATCH "${ENET_VERSION_PATCH_LINE}")
  set(ENET_VERSION_STRING ${ENET_VERSION_MAJOR}.${ENET_VERSION_MINOR}.${ENET_VERSION_PATCH})
  unset(ENET_VERSION_MAJOR_LINE)
  unset(ENET_VERSION_MINOR_LINE)
  unset(ENET_VERSION_PATCH_LINE)
  unset(ENET_VERSION_MAJOR)
  unset(ENET_VERSION_MINOR)
  unset(ENET_VERSION_PATCH)
endif()

include(FindPackageHandleStandardArgs)

FIND_PACKAGE_HANDLE_STANDARD_ARGS(ENET
                                  REQUIRED_VARS ENET_LIBRARIES ENET_INCLUDE_DIRS
                                  VERSION_VAR ENET_VERSION_STRING)

if(ENET_FOUND)
  if(NOT TARGET ENET)
    add_library(ENET INTERFACE IMPORTED)
    set_target_properties(ENET PROPERTIES
      INTERFACE_INCLUDE_DIRECTORIES "${ENET_INCLUDE_DIRS}"
      INTERFACE_LINK_LIBRARIES "${ENET_LIBRARIES}")
  endif()
endif()
