get_filename_component(GENERATE_MANPAGES_SCRIPT_DIR "${CMAKE_CURRENT_LIST_DIR}" ABSOLUTE)
list(APPEND CMAKE_MODULE_PATH ${GENERATE_MANPAGES_SCRIPT_DIR})

set(SRC "${CURRENT_SOURCE_DIR}/${target}.${section}.in")
configure_file(${SRC} ${manpage}.tmp @ONLY IMMEDIATE)

# write header (aka name of the manpage), truncate existing
file(READ ${CURRENT_BINARY_DIR}/${manpage}.tmp CONTENTS)
file(WRITE ${CURRENT_BINARY_DIR}/${manpage} "${CONTENTS}")

string(REPLACE " " ";" DEPS ${dependencies})
foreach(DEP IN LISTS DEPS)
  get_filename_component(DNAME "${DEP}" NAME)
  set(SRC_IN ${CURRENT_SOURCE_DIR}/${DEP}.in)
  set(DST_IN ${CURRENT_BINARY_DIR}/${DEP}.in)
  set(SRC ${CURRENT_SOURCE_DIR}/${DEP})
  set(BIN ${CURRENT_BINARY_DIR}/${DEP})
  set(DST ${CURRENT_BINARY_DIR}/${DNAME})

  if(EXISTS ${SRC_IN})
    message("using generated ${DST} from ${SRC_IN}")
    configure_file(${SRC_IN} ${DST} @ONLY IMMEDIATE)
  elseif(EXISTS ${DST_IN})
    message("using generated ${DST} from ${DST_IN}")
    configure_file(${DST_IN} ${DST} @ONLY IMMEDIATE)
  elseif(EXISTS ${SRC})
    set(DST ${SRC})
    message("using ${DST}")
  elseif(EXISTS ${BIN})
    set(DST ${BIN})
    message("using ${DST}")
  elseif(EXISTS ${DST})
    message("using ${DST}")
  else()
    message(WARNING "Missing manpage section, considered:")
    message(WARNING "   ${SRC_IN}")
    message(WARNING "   ${DST_IN}")
    message(WARNING "   ${SRC}")
    message(WARNING "   ${BIN}")
    message(WARNING "   ${DST}")
    message(FATAL_ERROR "Can not continue, terminating")
  endif()

  file(READ ${DST} CONTENTS)
  file(APPEND ${CURRENT_BINARY_DIR}/${manpage} "${CONTENTS}")
endforeach()
