# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS    ?=
SPHINXBUILD   ?= sphinx-build
SOURCEDIR     = source
BUILDDIR      = build

# Put it first so that "make" without argument is like "make help".
help:
	@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
	@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

# Default make weasyprint target has a bug so we have to call it manually on the generated index.html file
# Then we execute count_pdf_pages.py that will count the number of pages, and update print-theme.css
# Then we generate index.pdf again (with the correct number of pages in the footer)
# After that, extract table of content data from the pdf and generate a .tex file
# Then generate a toc.pdf from the .tex file
# And put them together in a .pdf file
# Finally, we generate the final PDF by adding the bookmarks (for easier navigation in the PDF)
# After all, clean up
pdf: weasyprint
	weasyprint "$(BUILDDIR)/weasyprint/index.html" "$(BUILDDIR)/weasyprint/index.pdf" -s "$(SOURCEDIR)/css/print-theme.css"
	python3 sphinx-tools/count_pdf_pages.py "$(BUILDDIR)/weasyprint/index.pdf" "$(SOURCEDIR)/css/print-theme.css"
	weasyprint "$(BUILDDIR)/weasyprint/index.html" "$(BUILDDIR)/weasyprint/index.pdf" -s "$(SOURCEDIR)/css/print-theme.css"
	./pdftoc-to-latex "$(BUILDDIR)/weasyprint/index.pdf" > "$(BUILDDIR)/weasyprint/toc.tex"
	- pdflatex -interaction nonstopmode "-output-directory=$(BUILDDIR)/weasyprint" "$(BUILDDIR)/weasyprint/toc.tex"
	pdftk "A=$(BUILDDIR)/weasyprint/index.pdf" "B=$(BUILDDIR)/weasyprint/toc.pdf" cat A1 B A2-end output "$(BUILDDIR)/weasyprint/vheliotech-without-bookmarks.pdf"
	python3 sphinx-tools/update_pdf_bookmarks.py "$(BUILDDIR)/weasyprint/index.pdf" "$(BUILDDIR)/weasyprint/vheliotech-without-bookmarks.pdf" "$(BUILDDIR)/weasyprint/vheliotech.pdf"
	#rm "$(BUILDDIR)/weasyprint/index.pdf" "$(BUILDDIR)/weasyprint/toc.tex" "$(BUILDDIR)/weasyprint/toc.pdf" "$(BUILDDIR)/weasyprint/GuidedemontageVheliotech.pdf"