# SPDX-FileCopyrightText: Copyright (c) 2022-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the \"License\");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an \"AS IS\" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

cmake_minimum_required(VERSION 3.20)
project(v4l2_camera CXX)

# Finds the package holoscan
find_package(holoscan REQUIRED CONFIG
             PATHS "/opt/nvidia/holoscan" "/workspace/holoscan-sdk/install")

# Add example C++ passthrough operator header
add_library(v4l2_camera_passthrough INTERFACE)
target_link_libraries(v4l2_camera_passthrough INTERFACE holoscan::core)
target_include_directories(v4l2_camera_passthrough INTERFACE "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>")
add_library(holoscan::ops::v4l2_camera_passthrough ALIAS v4l2_camera_passthrough)

# Create example
add_executable(v4l2_camera
  v4l2_camera.cpp
)

target_link_libraries(v4l2_camera
  PRIVATE
  holoscan::core
  holoscan::ops::v4l2
  holoscan::ops::holoviz
  holoscan::ops::format_converter
  holoscan::ops::v4l2_camera_passthrough
)

# Copy config file
add_custom_target(v4l2_camera_yaml
  COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/v4l2_camera.yaml" ${CMAKE_CURRENT_BINARY_DIR}
  DEPENDS "v4l2_camera.yaml"
  BYPRODUCTS "v4l2_camera.yaml"
)

add_dependencies(v4l2_camera v4l2_camera_yaml)

# Testing
option(HOLOSCAN_BUILD_V4L2_TESTS "Build tests for V4L2 loopback" OFF)
if(BUILD_TESTING AND HOLOSCAN_BUILD_V4L2_TESTS)
  # Assumes that the v4l2 video loopback has already been mounted and the yaml files have been
  # updated to use the virtual loopback device.

  # Modify testcase to only run 10 frames
  add_custom_command(OUTPUT v4l2_camera_test.cpp
    COMMAND sed 's/"visualizer",/"visualizer", make_condition<CountCondition>\(10\), /g'
            ${CMAKE_CURRENT_SOURCE_DIR}/v4l2_camera.cpp > v4l2_camera_test.cpp
  )

  # Create the test executable
  add_executable(v4l2_camera_test v4l2_camera_test.cpp)

  target_link_libraries(v4l2_camera_test
    PRIVATE
    holoscan::core
    holoscan::ops::v4l2
    holoscan::ops::holoviz
    holoscan::ops::format_converter
    holoscan::ops::v4l2_camera_passthrough
  )

  add_dependencies(v4l2_camera_test racerx_data)

  add_test(NAME EXAMPLE_CPP_V4L2_CAMERA_TEST
           COMMAND "${CMAKE_CURRENT_BINARY_DIR}/v4l2_camera_test"
           WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
          )
  set_tests_properties(EXAMPLE_CPP_V4L2_CAMERA_TEST PROPERTIES
                       PASS_REGULAR_EXPRESSION "Application has finished running")

endif()
