find_package(Sphinx REQUIRED)

set(DOC_INSTALL_PREFIX "share/libecl/docs")
set(doc_build "${PROJECT_BINARY_DIR}/doc_build")
file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/code" DESTINATION ${doc_build})

configure_file(index.rst.in "${doc_build}/index.rst")
configure_file(conf.py.in "${doc_build}/conf.py")

add_custom_target(api-doc ALL
  COMMAND sphinx-apidoc -e -o "${doc_build}/api" ${PROJECT_BINARY_DIR}/${PYTHON_INSTALL_PREFIX} tests
  WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/${PYTHON_INSTALL_PREFIX}
  DEPENDS ecl)

add_custom_target(html-doc ALL
  COMMAND sphinx-build -b html -d ${doc_build}/doctrees ${doc_build} ${doc_build}/html
  WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/${PYTHON_INSTALL_PREFIX}
  DEPENDS api-doc)

INSTALL( DIRECTORY ${doc_build}/html DESTINATION ${CMAKE_INSTALL_PREFIX}/${DOC_INSTALL_PREFIX})


# This command will configure sphinx to create a LaTeX version of the manual in
# ${doc_build}/latex - this can then subsequently be compiled with pdflatex to
# generate a pdf document.
#
# The LaTeX code generated by sphinx uses some packages which are not
# installed on RHEL 6/7, those sty files are therefor bundled with this
# project and copied manually to the LaTeX directory.
#
# Observe that at least on stock ubuntu 16.04 cmake will complain with a message:
#
#  -- Could NOT find LATEX (missing:  pdflatex)
#
# even in situatons where pdflatex is found and works ok; in this case the
# PDFLATEX_COMPILER variable is set and the pdf generation seems to work as
# expected.
find_package(LATEX COMPONENTS pdflatex)
if (PDFLATEX_COMPILER)
  set(latex_workdir "${doc_build}/latex")

  add_custom_target(latex-doc ALL
    COMMAND sphinx-build -b latex -d ${doc_build}/doctrees ${doc_build} ${latex_workdir}
    WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/${PYTHON_INSTALL_PREFIX}
    DEPENDS api-doc)

  file(GLOB sty_files "latex/*.sty")
  file(COPY ${sty_files} DESTINATION ${latex_workdir})

  # The pdflatex command is issued twice to let latex resolve references
  # correctly.
  add_custom_target(pdf-doc ALL
    COMMAND ${PDFLATEX_COMPILER} "libecl.tex"
    COMMAND ${PDFLATEX_COMPILER} "libecl.tex"
    DEPENDS latex-doc
    WORKING_DIRECTORY ${latex_workdir})

  install(FILES ${latex_workdir}/libecl.pdf DESTINATION ${CMAKE_INSTALL_PREFIX}/${DOC_INSTALL_PREFIX}/pdf)
endif()

