#! /usr/bin/make

##### This part is to generate html files in the current directory ###########

SOURCES = $(wildcard _sources/*.rst | grep -v index.rst | sed 's%_sources/%%')
HTML_FILES = $(patsubst %.rst, %.html, $(SOURCES))

all: $(HTML_FILES)
	@echo
	@echo "[Done]"
%.html: _sources/%.rst
	@echo -n "$@ "
	@rst2html $< $@

###### That part is for the User Manual #######################################

# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line.
SPHINXOPTS    =
SPHINXBUILD   = sphinx-build
SOURCEDIR     = _sources
SOURCES       = $(wildcard $(SOURCEDIR)/*.rst)
BUILDDIR      = build

PAPER = a4

# Internal variables.
PAPEROPT_a4     = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(SPHINXOPTS)
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .


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

.PHONY: help Makefile

.PHONY: latexpdf real_latexpdf

# for languages without correct LaTeX babel, change this dependency
# so latexpdf will not be called
latexpdf:
	@if [ -f NoLaTeX ]; then \
	  printf "+----------------------------------+\n| No LaTeX build since it is not   |\n| well supported for this language |\n+----------------------------------+\n"; \
	else \
	  $(MAKE) real_latexpdf; \
	fi

real_latexpdf: cover/coverpage.pdf cover/preface.pdf $(SOURCES)
	$(SPHINXBUILD) -b latex "$(SOURCEDIR)" $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo copying a few files
	cp cover/*.pdf $(BUILDDIR)/latex
	@echo modifying the title page
	cd $(BUILDDIR)/latex; \
	  sed -i '/\\usepackage{sphinx}/r ../../include.tex' expEYES-Junior.tex; \
	  sed -i 's/\\sphinxmaketitle/\\includepdf{coverpage.pdf}\n\\includepdf{preface.pdf}/' expEYES-Junior.tex;
	@echo launching prettyLaTeX.py
	python3 prettyLaTeX.py $(BUILDDIR)/latex expEYES-Junior.tex
	@echo generating PDF images in the LaTeX directory
	rm -f $(BUILDDIR)/latex/Makefile-images
	ln -s ../../../Makefile-images $(BUILDDIR)/latex
	make -C $(BUILDDIR)/latex -f Makefile-images -j4
	@echo "Running LaTeX files through xelatex..."
	$(MAKE) -C $(BUILDDIR)/latex all-pdf PDFLATEX="latexmk -xelatex -silent -f -dvi- -ps-" || cat $(BUILDDIR)/latex/expEYES-Junior.log
	@echo "xelatex finished; the PDF files are in $(BUILDDIR)/latex."

.PHONY: epub
epub:
	$(SPHINXBUILD) -b epub "$(SOURCEDIR)" $(ALLSPHINXOPTS) $(BUILDDIR)/epub
	@echo
	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."

.PHONY: clean
clean:
	rm -rf $(BUILDDIR)/*
	cd cover; rm -f *.aux *.log *~

.PHONY: distclean
distclean: clean
	cd cover; rm -f *.pdf
