# Copyright 2026 Intelligent Robotics Lab
#
# 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.

# The kairos command, built on the public library only
add_executable(kairos_cli main.cpp completion.cpp)
set_target_properties(kairos_cli PROPERTIES OUTPUT_NAME kairos)
target_link_libraries(kairos_cli PRIVATE kairos)
kairos_configure_target(kairos_cli)
# Installed, the command finds its library next to it (any prefix, no LD_LIBRARY_PATH needed)
file(RELATIVE_PATH _kairos_bin_to_lib
  ${CMAKE_INSTALL_FULL_BINDIR} ${CMAKE_INSTALL_FULL_LIBDIR})
set_target_properties(kairos_cli PROPERTIES INSTALL_RPATH "$ORIGIN/${_kairos_bin_to_lib}")
install(TARGETS kairos_cli RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})

# Shell completion, generated by the built command so it never drifts from its options:
# - share/kairos/completion: sourced by the colcon hooks (see colcon.pkg) when a workspace is
#   sourced;
# - the standard places of bash-completion and fish, for installs in a system prefix.
if(NOT CMAKE_CROSSCOMPILING)
  set(_completion_dir ${CMAKE_CURRENT_BINARY_DIR}/completion)
  set(_completion_files)
  foreach(shell bash zsh fish)
    add_custom_command(
      OUTPUT ${_completion_dir}/kairos.${shell}
      COMMAND ${CMAKE_COMMAND} -E make_directory ${_completion_dir}
      COMMAND kairos_cli --completion ${shell} > ${_completion_dir}/kairos.${shell}
      DEPENDS kairos_cli
      COMMENT "kairos completion for ${shell}"
      VERBATIM)
    list(APPEND _completion_files ${_completion_dir}/kairos.${shell})
  endforeach()
  add_custom_target(kairos_completion ALL DEPENDS ${_completion_files})
  install(FILES ${_completion_files} DESTINATION ${CMAKE_INSTALL_DATADIR}/kairos/completion)
  install(FILES ${_completion_dir}/kairos.bash
    DESTINATION ${CMAKE_INSTALL_DATADIR}/bash-completion/completions RENAME kairos)
  install(FILES ${_completion_dir}/kairos.fish
    DESTINATION ${CMAKE_INSTALL_DATADIR}/fish/vendor_completions.d)
endif()
