cmake_minimum_required(VERSION 3.15)

project(
  ethercat
  VERSION 1.5.3
  DESCRIPTION "IgH EtherCAT Master userspace client library"
  LANGUAGES C)

# Options
option(BUILD_SHARED_LIBS "Build shared library" ON)
set(EC_MAX_NUM_DEVICES
    1
    CACHE STRING
          "Max number of Ethernet devices per master (must match kernel module)"
)

# Library sources
set(LIB_SOURCES
    lib/common.c
    lib/domain.c
    lib/master.c
    lib/reg_request.c
    lib/sdo_request.c
    lib/slave_config.c
    lib/soe_request.c
    lib/voe_handler.c)

set(LIB_PUBLIC_HEADERS include/ecrt.h include/ectty.h)

# Create the library
add_library(ethercat ${LIB_SOURCES})
add_library(EtherLab::ethercat ALIAS ethercat)

# Set library properties
set_target_properties(
  ethercat
  PROPERTIES VERSION ${PROJECT_VERSION}
             SOVERSION 3
             PUBLIC_HEADER "${LIB_PUBLIC_HEADERS}")

# Compile definitions These defines substitute for config.h which is generated
# by autotools and primarily used for kernel module. The userspace library only
# needs VERSION, REV, and EC_MAX_NUM_DEVICES.
target_compile_definitions(
  ethercat PRIVATE ethercat_EXPORTS EC_MAX_NUM_DEVICES=${EC_MAX_NUM_DEVICES}
                   VERSION="${PROJECT_VERSION}" REV="")

# Create a minimal config.h that just checks if defines already exist
file(
  WRITE ${CMAKE_CURRENT_BINARY_DIR}/config.h
  "/* Minimal config.h for CMake build */
#ifndef CONFIG_H
#define CONFIG_H
#ifndef VERSION
#define VERSION \"${PROJECT_VERSION}\"
#endif
#ifndef REV
#define REV \"\"
#endif
// #ifndef EC_MAX_NUM_DEVICES
// #define EC_MAX_NUM_DEVICES 1
// #endif
#endif
")

# Include directories
target_include_directories(
  ethercat
  PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
         $<INSTALL_INTERFACE:include>
  PRIVATE ${CMAKE_CURRENT_BINARY_DIR}
          ${CMAKE_CURRENT_SOURCE_DIR}
          ${CMAKE_CURRENT_SOURCE_DIR}/lib
          # client lib still needs some header from kernel module
          ${CMAKE_CURRENT_SOURCE_DIR}/master)

# Compile options
target_compile_options(ethercat PRIVATE -fno-strict-aliasing -Wall
                                        -Wmissing-prototypes)

# Link libraries
if(UNIX)
  target_link_libraries(ethercat PRIVATE rt)
endif()

install(
  TARGETS ethercat
  EXPORT ethercatTargets
  LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
  ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
  RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
  PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
