cmake_minimum_required(VERSION 3.15)

project(Sensor3DCpp VERSION 1.0.0 LANGUAGES CXX)

# ---------------------------------------------------------------------------
# Options
# ---------------------------------------------------------------------------

# Build examples by default when configured standalone; default OFF when added
# via add_subdirectory() so a host project isn't surprised by extra executables.
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
    set(_sensor3dcpp_build_examples_default ON)
else()
    set(_sensor3dcpp_build_examples_default OFF)
endif()
option(SENSOR3DCPP_BUILD_EXAMPLES "Build the Sensor3DCpp example programs" ${_sensor3dcpp_build_examples_default})
unset(_sensor3dcpp_build_examples_default)
option(SENSOR3DCPP_BUILD_TESTS "Build the Sensor3DCpp unit tests" OFF)

# ---------------------------------------------------------------------------
# The core SDK
# ---------------------------------------------------------------------------

# Prefer an already-installed SDK; fetching the core-redistributable via
# FetchContent is only the fallback when no compatible install is found.
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/CORE_VERSION.txt" SENSOR3D_REQUIRED_VERSION)

# Inside an unpacked SDK package this folder is <sdk>/wrappers/cpp, and the SDK's
# Sensor3DConfig.cmake is at <sdk>/lib/cmake/Sensor3D, so no -DCMAKE_PREFIX_PATH is needed.
list(APPEND CMAKE_PREFIX_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../..")

# Force fetching the core-redistributable even if a compatible SDK is
# already installed locally.
option(SENSOR3DCPP_FORCE_FETCH_CORE_REDIST
    "Always fetch the core-redistributable via FetchContent, even if a compatible SDK is found locally" OFF)

if(SENSOR3DCPP_FORCE_FETCH_CORE_REDIST)
    set(Sensor3D_FOUND FALSE)
else()
    # QUIET: not finding a local install is the normal case, not an error --
    # we fall back to FetchContent below.
    find_package(Sensor3D ${SENSOR3D_REQUIRED_VERSION} QUIET)
endif()

if(Sensor3D_FOUND)
    message(STATUS "Using locally installed Sensor3D SDK ${Sensor3D_VERSION}")
else()
    message(STATUS "No compatible local Sensor3D SDK found -- fetching the core-redistributable")

    if(WIN32)
        set(_s3d_os "windows")
        set(_s3d_ext "zip")
    else()
        set(_s3d_os "linux")
        set(_s3d_ext "tar.gz")
    endif()
    set(_s3d_arch "x64")
    set(_s3d_asset "sensor3d-core-${_s3d_os}-${_s3d_arch}-${SENSOR3D_REQUIRED_VERSION}.${_s3d_ext}")
    set(SENSOR_3D_CORE_REDIST_URL "" CACHE STRING
        "Base URL of the sensor3d-core-redist repository releases are fetched from")

    if(NOT SENSOR_3D_CORE_REDIST_URL)
        message(FATAL_ERROR
            "No compatible Sensor3D SDK was found and SENSOR_3D_CORE_REDIST_URL is not set. "
            "Pass -DSENSOR_3D_CORE_REDIST_URL=<repository-url> pointing at your "
            "sensor3d-core-redist repository, or install the Sensor3D SDK so "
            "find_package(Sensor3D) can locate it.")
    endif()

    set(_s3d_release_url "${SENSOR_3D_CORE_REDIST_URL}/releases/download/v${SENSOR3D_REQUIRED_VERSION}")
    set(_s3d_url "${_s3d_release_url}/${_s3d_asset}")

    # Set this to pin an exact checksum instead of resolving the release's
    # own <asset>.sha256 sidecar below.
    set(SENSOR3DCPP_CORE_REDIST_SHA256 "" CACHE STRING
        "Expected SHA256 of the fetched asset; leave empty to resolve it automatically from the release's <asset>.sha256 sidecar")

    # Resolve the checksum from the release's own <asset>.sha256 file so the
    # download below is verified by default.
    if(NOT SENSOR3DCPP_CORE_REDIST_SHA256)
        set(_s3d_sha256_file "${CMAKE_BINARY_DIR}/${_s3d_asset}.sha256")
        file(DOWNLOAD "${_s3d_url}.sha256" "${_s3d_sha256_file}" STATUS _s3d_sha256_status)
        list(GET _s3d_sha256_status 0 _s3d_sha256_code)
        if(_s3d_sha256_code EQUAL 0)
            file(STRINGS "${_s3d_sha256_file}" _s3d_sha256_line LIMIT_COUNT 1)
            string(REGEX MATCH "^[0-9a-fA-F]+" SENSOR3DCPP_CORE_REDIST_SHA256 "${_s3d_sha256_line}")
        endif()
        if(NOT SENSOR3DCPP_CORE_REDIST_SHA256)
            message(WARNING
                "Could not resolve a SHA256 for ${_s3d_asset} from "
                "${_s3d_url}.sha256 -- proceeding WITHOUT checksum "
                "verification. Set -DSENSOR3DCPP_CORE_REDIST_SHA256=<hash> to pin one explicitly.")
        endif()
        unset(_s3d_sha256_file)
        unset(_s3d_sha256_status)
        unset(_s3d_sha256_code)
        unset(_s3d_sha256_line)
    endif()

    set(_s3d_fetch_extra_args "")
    if(SENSOR3DCPP_CORE_REDIST_SHA256)
        list(APPEND _s3d_fetch_extra_args URL_HASH SHA256=${SENSOR3DCPP_CORE_REDIST_SHA256})
    endif()

    include(FetchContent)
    FetchContent_Declare(sensor3d_core URL "${_s3d_url}" ${_s3d_fetch_extra_args})
    FetchContent_MakeAvailable(sensor3d_core)
    list(APPEND CMAKE_PREFIX_PATH "${sensor3d_core_SOURCE_DIR}")

    unset(_s3d_os)
    unset(_s3d_ext)
    unset(_s3d_arch)
    unset(_s3d_asset)
    unset(_s3d_release_url)
    unset(_s3d_url)
    unset(_s3d_fetch_extra_args)

    find_package(Sensor3D ${SENSOR3D_REQUIRED_VERSION} REQUIRED)  # must not fail now
endif()

# ---------------------------------------------------------------------------
# Sources
# ---------------------------------------------------------------------------

set(SENSOR3DCPP_SOURCES
    src/camera_parameters.cpp
    src/constants_check.cpp
    src/device_info.cpp
    src/error.cpp
    src/error_context.cpp
    src/frame.cpp
    src/frame_callback.cpp
    src/sensor.cpp
    src/version.cpp
)

# An intermediate object library, so the unit tests can reuse the compiled
# objects while linking a mock of the C API instead of the real one.
add_library(Sensor3DCpp_objs OBJECT ${SENSOR3DCPP_SOURCES})

target_include_directories(Sensor3DCpp_objs
    PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}/include
        ${CMAKE_CURRENT_SOURCE_DIR}/src
        $<TARGET_PROPERTY:Sensor3D::Sensor3D,INTERFACE_INCLUDE_DIRECTORIES>
)
target_compile_features(Sensor3DCpp_objs PRIVATE cxx_std_17)
set_target_properties(Sensor3DCpp_objs PROPERTIES POSITION_INDEPENDENT_CODE ON)

# ---------------------------------------------------------------------------
# The library
# ---------------------------------------------------------------------------

# STATIC rather than SHARED: the public interface uses std::string and
# std::vector, which a shared build would expose across a fragile ABI boundary.
add_library(Sensor3DCpp STATIC $<TARGET_OBJECTS:Sensor3DCpp_objs>)
add_library(Sensor3DCpp::Sensor3DCpp ALIAS Sensor3DCpp)

set_target_properties(Sensor3DCpp PROPERTIES LINKER_LANGUAGE CXX)
target_compile_features(Sensor3DCpp PUBLIC cxx_std_17)
target_link_libraries(Sensor3DCpp PUBLIC Sensor3D::Sensor3D)
target_include_directories(Sensor3DCpp
    PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
        $<INSTALL_INTERFACE:include>
)

# ---------------------------------------------------------------------------
# Install and package config
# ---------------------------------------------------------------------------

include(CMakePackageConfigHelpers)

# Config files land in <prefix>/cmake to match where the core SDK puts
# Sensor3DConfig.cmake, so one CMAKE_PREFIX_PATH finds both.
set(SENSOR3DCPP_CMAKE_DESTINATION cmake)

install(DIRECTORY include/Sensor3DCpp DESTINATION include)

install(TARGETS Sensor3DCpp
    EXPORT Sensor3DCppTargets
    ARCHIVE DESTINATION lib
    LIBRARY DESTINATION lib
    RUNTIME DESTINATION bin
    INCLUDES DESTINATION include
)

install(EXPORT Sensor3DCppTargets
    FILE Sensor3DCppTargets.cmake
    NAMESPACE Sensor3DCpp::
    DESTINATION ${SENSOR3DCPP_CMAKE_DESTINATION}
)

configure_package_config_file(
    ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Sensor3DCppConfig.cmake.in
    ${CMAKE_CURRENT_BINARY_DIR}/Sensor3DCppConfig.cmake
    INSTALL_DESTINATION ${SENSOR3DCPP_CMAKE_DESTINATION}
)

write_basic_package_version_file(
    ${CMAKE_CURRENT_BINARY_DIR}/Sensor3DCppConfigVersion.cmake
    VERSION ${PROJECT_VERSION}
    COMPATIBILITY SameMajorVersion
)

install(FILES
    ${CMAKE_CURRENT_BINARY_DIR}/Sensor3DCppConfig.cmake
    ${CMAKE_CURRENT_BINARY_DIR}/Sensor3DCppConfigVersion.cmake
    DESTINATION ${SENSOR3DCPP_CMAKE_DESTINATION}
)

# ---------------------------------------------------------------------------
# Examples and tests
# ---------------------------------------------------------------------------

if(SENSOR3DCPP_BUILD_EXAMPLES)
    add_subdirectory(examples)
endif()

# tests/ is not part of the customer package, so only add it when present.
if(SENSOR3DCPP_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/CMakeLists.txt")
    enable_testing()
    add_subdirectory(tests)
endif()
