# ubuntu 12.04 LTS cmake version 2.8.7
# ubuntu 14.04 LTS cmake version 2.8.12.2
# ubuntu 16.04 LTS cmake version 3.5.1
cmake_minimum_required(VERSION 2.8.3)

project(usb)

  set(LIBUSB_C
  libusb/core.c
  libusb/descriptor.c
  libusb/hotplug.c
  libusb/io.c
  libusb/strerror.c
  libusb/sync.c
  )

if(WIN32)
  LIST(APPEND LIBUSB_C
  libusb/os/threads_windows.c
  libusb/os/poll_windows.c
  libusb/os/windows_winusb.c
  libusb/os/windows_nt_common.c
  libusb/os/windows_usbdk.c
  )
elseif (APPLE)
  LIST(APPEND LIBUSB_C
  libusb/os/poll_posix.c
  libusb/os/threads_posix.c
  libusb/os/darwin_usb.c
  )
elseif(ANDROID)
  LIST(APPEND LIBUSB_C
  libusb/os/linux_usbfs.c
  libusb/os/poll_posix.c
  libusb/os/threads_posix.c
  libusb/os/linux_netlink.c
  )
else()
  LIST(APPEND LIBUSB_C
  config.h
  libusb/os/linux_usbfs.c
  libusb/os/poll_posix.c
  libusb/os/threads_posix.c
  libusb/os/linux_udev.c
  )
endif()

set(LIBUSB_H
    libusb/libusb.h
)

include_directories(
  libusb
  libusb/os
)

add_library(usb STATIC ${LIBUSB_C} ${LIBUSB_H})
# Apply LANG_VISIBILITY_PRESET to static libraries and archives as well
cmake_policy(SET CMP0063 NEW)
set_target_properties(usb PROPERTIES POSITION_INDEPENDENT_CODE ON
    C_VISIBILITY_PRESET hidden
    VISIBILITY_INLINES_HIDDEN ON
    )

if(WIN32)
    set_target_properties (usb PROPERTIES
        FOLDER "3rd Party"
    )
    include_directories(msvc)
    foreach(flag_var
        CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
        CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO
        CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE
        CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO)
        if(${flag_var} MATCHES "/MD")
            string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
        endif(${flag_var} MATCHES "/MD")
    endforeach(flag_var)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /utf-8")
    set(CMAKE_C_FLAGS   "${CMAKE_C_FLAGS}   /utf-8")
endif()

if(ANDROID)
    include_directories(android)
endif()

if(APPLE)
  find_library(corefoundation_lib CoreFoundation)
  find_library(iokit_lib IOKit)
  target_include_directories(usb PRIVATE XCode)
  TARGET_LINK_LIBRARIES(usb objc ${corefoundation_lib} ${iokit_lib})
endif()

if((NOT APPLE) AND (NOT ANDROID) AND (NOT WIN32))
  TARGET_LINK_LIBRARIES(usb PUBLIC udev)
  target_include_directories(usb PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
  add_custom_command(OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/config.h
      COMMAND ./autogen.sh
      WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
      BYPRODUCTS Makefile libusb-1.0.pc
      )
endif()

install(TARGETS ${PROJECT_NAME}
    EXPORT realsense2Targets
    ARCHIVE DESTINATION lib
    LIBRARY DESTINATION lib
    RUNTIME DESTINATION bin
    )
