# This file is part of the Owl Positioning System (OwlPS) project.
# It is subject to the copyright notice and license terms in the
# COPYRIGHT.t2t file found in the top-level directory of this
# distribution and at
#   https://code.lm7.fr/mcy/owlps/src/master/COPYRIGHT.t2t
# No part of the OwlPS Project, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the COPYRIGHT.t2t file; the COPYRIGHT.t2t file must be
# distributed along with this file, either separately or by replacing
# this notice by the COPYRIGHT.t2t file's contents.


set(MAN_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/man")
add_custom_target(doc ALL true)


### txt2tags manual pages ###

# Make sure txt2tags is available
find_package(Txt2tags)
if (NOT TXT2TAGS_FOUND)
  message(WARNING
    "Couldn't find txt2tags: disabling generation of txt2tags-based man pages")
else()

  set(PREPROC_MAN ./preproc-man.sh)

  function(add_manpage PAGENAME SECTION)
    set(OUTPUT_DIRECTORY "${MAN_OUTPUT_DIRECTORY}/man${SECTION}")
    set(SOURCE ${PAGENAME}.t2t)
    set(TARGETNAME ${PAGENAME}.${SECTION})
    set(TARGET "${OUTPUT_DIRECTORY}/${TARGETNAME}")

    # Create the output directory
    # Note: this is done only when first calling cmake and when rebuilding
    # cache; it would be nice if it could be called every time, but there
    # doesn't seem to be any simple solution.
    file(MAKE_DIRECTORY "${OUTPUT_DIRECTORY}")

    # Command to generate the man page
    add_custom_command(
      OUTPUT "${TARGET}"
      COMMAND OWLPS_VERSION=${OWLPS_VERSION} INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX} "${PREPROC_MAN}" "${SOURCE}" | "${TXT2TAGS_EXECUTABLE}" -q --infile=- --outfile="${TARGET}" -t man
      DEPENDS "${SOURCE}"
      WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
      COMMENT "Generating ${TARGETNAME}")

    # Set up the target
    add_custom_target(${TARGETNAME} true DEPENDS "${TARGET}")

    # Add the target to the "doc" meta-target
    add_dependencies(doc "${TARGETNAME}")
  endfunction()

  add_manpage(owlps 7)
  add_manpage(owlps-architecture 7)
  add_manpage(owlps-deployment 7)
  add_manpage(owlps-client 1)
  add_manpage(owlps-listenerd 1)
  add_manpage(owlps-aggregatord 1)
  add_manpage(owlps-positionerd 1)
  add_manpage(owlps-udp-to-http 1)

endif()


### pod2man-generated man pages ###

find_package(Pod2man)
if (NOT POD2MAN_FOUND)
  message(WARNING
    "Couldn't find pod2man: disabling generation of man pages for Perl programs")
else()

  function(add_pod_manpage SOURCE PAGENAME SECTION)
    set(TARGETNAME "${PAGENAME}.${SECTION}")
    if(${SECTION} STREQUAL "3perl")
      set(SECTION 3)
    endif()
    set(OUTPUT_DIRECTORY "${MAN_OUTPUT_DIRECTORY}/man${SECTION}")
    set(FINALTARGETFILE "${OUTPUT_DIRECTORY}/${TARGETNAME}")
    # Change TARGETNAME so that the CMake target don't contain any ':'
    string(REGEX REPLACE ":" "-" TARGETNAME ${TARGETNAME})
    set(TARGETFILE "${OUTPUT_DIRECTORY}/${TARGETNAME}")

    # Create the output directory
    # Note: this is done only when first calling cmake and when rebuilding
    # cache; it would be nice if it could be called every time, but there
    # doesn't seem to be any simple solution.
    file(MAKE_DIRECTORY "${OUTPUT_DIRECTORY}")

    # Get source file last modification date from the git history
    execute_process(
      COMMAND git log -1 --pretty=%ai "${SOURCE}"
      WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
      RESULT_VARIABLE RET
      OUTPUT_VARIABLE DATE
      ERROR_QUIET
      OUTPUT_STRIP_TRAILING_WHITESPACE)
    if (DATE)
      # Take only the first field (the date without the time)
      string(REGEX REPLACE " .*" "" DATE ${DATE})
    else()
      # Take today's date from the system instead
      execute_process(
        COMMAND date --iso-8601
        WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
        RESULT_VARIABLE RET
        OUTPUT_VARIABLE DATE
        ERROR_QUIET
        OUTPUT_STRIP_TRAILING_WHITESPACE)
    endif()

    # Command to generate the man page
    add_custom_command(
      OUTPUT "${TARGETFILE}"
      COMMAND "${POD2MAN_EXECUTABLE}" --center "OwlPS User Manual" --release "OwlPS ${OWLPS_VERSION}" --date "${DATE}" "${SOURCE}" "${TARGETFILE}"
      COMMAND ${CMAKE_COMMAND} -E rename "${TARGETFILE}" "${FINALTARGETFILE}"
      DEPENDS "${SOURCE}"
      COMMENT "Generating ${TARGETNAME}")

    # Set up the target
    add_custom_target("${TARGETNAME}" true DEPENDS "${TARGETFILE}")

    # Add the target to the "doc" meta-target
    add_dependencies(doc "${TARGETNAME}")

    # Add a special cleaning rule (in case the file was renamed)
    set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES "${FINALTARGETFILE}")
  endfunction()

  add_pod_manpage(${CMAKE_SOURCE_DIR}/scripts/owlps-aggcheck.pl owlps-aggcheck 1)
  add_pod_manpage(${CMAKE_SOURCE_DIR}/scripts/owlps-aggsetcoord.pl owlps-aggsetcoord 1)
  add_pod_manpage(${CMAKE_SOURCE_DIR}/scripts/OwlPS/CSV.pm OwlPS::CSV 3perl)
  add_pod_manpage(${CMAKE_SOURCE_DIR}/scripts/OwlPS/TimeInterpolation.pm OwlPS::TimeInterpolation 3perl)

endif()


### Doxygen-generated man pages ###

if (NOT DOXYGEN_FOUND)
  message(WARNING
    "Couldn't find Doxygen: disabling generation of Doxygen-based man pages")
else()

  # Base output directory for Doxygen (it will append "man" for the
  # man pages, "html" for the HTML output, etc.)
  set(DOXYGEN_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
  # Section of the man pages we generate
  set(SECTION 3)
  # Final output directory (as assembled by Doxygen)
  set(OUTPUT_DIRECTORY "${DOXYGEN_OUTPUT_DIRECTORY}/man/man${SECTION}")
  # Output files
  set(DOXYGEN_MANPAGES
    "${OUTPUT_DIRECTORY}/owlps.h.${SECTION}"
    "${OUTPUT_DIRECTORY}/owlps-client.h.${SECTION}"
    "${OUTPUT_DIRECTORY}/owlps-resultreader.h.${SECTION}")

  # Corresponding input files (note that we cannot use this list as input
  # for Doxygen, due to space protection issues, therefore it is
  # duplicated in the Doxyfile)
  set(INPUT_FILES
    ${CMAKE_SOURCE_DIR}/libowlps/owlps.h
    ${CMAKE_SOURCE_DIR}/libowlps/libowlps.c
    ${CMAKE_SOURCE_DIR}/libowlps-client/owlps-client.h
    ${CMAKE_SOURCE_DIR}/libowlps-client/libowlps-client.c
    ${CMAKE_SOURCE_DIR}/libowlps-resultreader/owlps-resultreader.h
    ${CMAKE_SOURCE_DIR}/libowlps-resultreader/libowlps-resultreader.c)

  # Doxygen configuration file name
  set(DOXYFILE Doxyfile)

  add_custom_command(
    OUTPUT ${DOXYGEN_MANPAGES}
    COMMAND DOXYGEN_OUTPUT_DIRECTORY=${DOXYGEN_OUTPUT_DIRECTORY} DOXYGEN_MAN_EXTENSION=.${SECTION} OWLPS_VERSION=${OWLPS_VERSION} "${DOXYGEN_EXECUTABLE}" "${DOXYFILE}"
    DEPENDS ${INPUT_FILES}
    WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
    COMMENT "Generating Doxygen-based man pages")

  # Target to clean the files generated by Doxygen that we don't want
  # (so-called "directory references"). This cannot be done with CMake's
  # file() commands because it has to be run every time the target is
  # built, and you cannot use CMake functions in a custom target or
  # command.
  add_custom_target(clean_doxygen_garbage
    COMMAND ${CMAKE_COMMAND} -E remove "${OUTPUT_DIRECTORY}/_*_owlps_libowlps*_.${SECTION}")

  # Set up the target
  add_custom_target(doc_doxygen true DEPENDS ${DOXYGEN_MANPAGES})

  # Add the target to the "doc" meta-target. The fact that "doc" depends
  # only on "clean_doxygen_garbage" and that the latter depends on
  # "doc_doxygen" guaranties that the garbage are actually cleaned *after*
  # they are generated.
  add_dependencies(clean_doxygen_garbage doc_doxygen)
  add_dependencies(doc clean_doxygen_garbage)

endif()


### Installation ###

install(
  DIRECTORY ${MAN_OUTPUT_DIRECTORY}
  DESTINATION share)
