cmake_minimum_required(VERSION 3.8)
project(SoapyAmarisoft CXX)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
endif()

# ── SoapySDR ──────────────────────────────────────────────────────────────────
find_package(SoapySDR "0.7" REQUIRED)

# ── Amarisoft libsdr ──────────────────────────────────────────────────────────
#
# libsdr.h lives in <trx_sdr>/api and pulls in <trx_sdr>/kernel/flags.h, so both
# directories are needed on the include path.  Override with
#   cmake -DTRX_SDR_ROOT=/root/trx_sdr-linux-YYYY-MM-DD ..
set(TRX_SDR_ROOT "/root/trx_sdr" CACHE PATH
    "Amarisoft trx_sdr install root (contains api/libsdr.h and api/libsdr.so)")

find_path(LIBSDR_INCLUDE_DIR
    NAMES libsdr.h
    HINTS "${TRX_SDR_ROOT}/api" "${TRX_SDR_ROOT}"
    DOC "Directory containing libsdr.h")

find_path(LIBSDR_FLAGS_INCLUDE_DIR
    NAMES flags.h
    HINTS "${TRX_SDR_ROOT}/kernel" "${TRX_SDR_ROOT}"
    DOC "Directory containing the kernel flags.h that libsdr.h includes")

find_library(LIBSDR_LIBRARY
    NAMES sdr
    HINTS "${TRX_SDR_ROOT}/api" "${TRX_SDR_ROOT}"
    DOC "Amarisoft libsdr.so")

if(NOT LIBSDR_INCLUDE_DIR OR NOT LIBSDR_FLAGS_INCLUDE_DIR OR NOT LIBSDR_LIBRARY)
    message(FATAL_ERROR
        "Amarisoft libsdr not found under '${TRX_SDR_ROOT}'.\n"
        "  libsdr.h : ${LIBSDR_INCLUDE_DIR}\n"
        "  flags.h  : ${LIBSDR_FLAGS_INCLUDE_DIR}\n"
        "  libsdr.so: ${LIBSDR_LIBRARY}\n"
        "Re-run with -DTRX_SDR_ROOT=<path to trx_sdr>")
endif()

message(STATUS "libsdr header : ${LIBSDR_INCLUDE_DIR}/libsdr.h")
message(STATUS "libsdr library: ${LIBSDR_LIBRARY}")

get_filename_component(LIBSDR_LIBRARY_DIR "${LIBSDR_LIBRARY}" DIRECTORY)

# ── module ────────────────────────────────────────────────────────────────────
SOAPY_SDR_MODULE_UTIL(
    TARGET amarisoftSupport
    SOURCES
        Registration.cpp
        Settings.cpp
        Streaming.cpp
    LIBRARIES
        ${LIBSDR_LIBRARY}
        dl
        pthread
        m
)

target_include_directories(amarisoftSupport PRIVATE
    "${CMAKE_CURRENT_SOURCE_DIR}"
    "${LIBSDR_INCLUDE_DIR}"
    "${LIBSDR_FLAGS_INCLUDE_DIR}"
)

# libsdr.so is not on the default loader path; record where it was found so
# the module resolves it without the caller having to set LD_LIBRARY_PATH.
set_target_properties(amarisoftSupport PROPERTIES
    INSTALL_RPATH "${LIBSDR_LIBRARY_DIR}"
    BUILD_WITH_INSTALL_RPATH TRUE
)

target_compile_options(amarisoftSupport PRIVATE -Wall -Wextra -Wno-unused-parameter)

# ── test utilities ────────────────────────────────────────────────────────────
option(BUILD_TESTS "Build the SoapyAmarisoft command line test tools" ON)
if(BUILD_TESTS)
    add_subdirectory(tests)
endif()
