PANDOC = pandoc
LATEX = lualatex
LATEX_FLAGS = \
	-file-line-error \
	-recorder \
	-interaction=nonstopmode \
	-halt-on-error \
	--shell-escape
PANDOC_FLAGS = --top-level-division=section
PANDOC_TEX_FLAGS = --template=template.tex
PANDOC_TEX_DEPENDENCIES = template.tex
SOFFICE = soffice
SOFFICE_FLAGS = --headless
INKSCAPE = inkscape
INKSCAPE_FLAGS = 

MARKDOWN_INPUTS = $(wildcard *.md)

ODG_INPUTS = $(wildcard img/*/*.odg)

.PHONY: all clean clean-pdf clean-tex clean-svg clean-png all-pdf all-tex all-svg all-png default

TEXINPUTS := .:./pkg/:$(TEXINPUTS)
export TEXINPUTS

default: all

all: all-tex all-svg all-png all-pdf

all-svg: $(addsuffix .svg,$(basename $(ODG_INPUTS)))

all-png: $(addsuffix .png,$(basename $(ODG_INPUTS)))

all-tex: $(addsuffix .tex,$(basename $(MARKDOWN_INPUTS)))

all-pdf: $(addsuffix .pdf,$(basename $(MARKDOWN_INPUTS)))

clean: clean-pdf clean-tex clean-svg clean-png

clean-svg:
	rm -f $(addsuffix .svg,$(basename $(ODG_INPUTS)))

clean-png:
	rm -f $(addsuffix .png,$(basename $(ODG_INPUTS)))

clean-tex:
	rm -f $(addsuffix .tex,$(basename $(MARKDOWN_INPUTS)))

clean-pdf:
	rm -f \
		$(addsuffix .aux,$(basename $(MARKDOWN_INPUTS))) \
		$(addsuffix .pdf,$(basename $(MARKDOWN_INPUTS))) \
		$(addsuffix .out,$(basename $(MARKDOWN_INPUTS))) \
		$(addsuffix .fls,$(basename $(MARKDOWN_INPUTS))) \
		$(addsuffix .log,$(basename $(MARKDOWN_INPUTS))) \
		$(addsuffix .toc,$(basename $(MARKDOWN_INPUTS))) \
		missfont.log

%.svg: %.odg
	@echo $< "->" $@
	$(SOFFICE) $(SOFFICE_FLAGS) --draw --convert-to svg:draw_svg_Export \
		--outdir $(dir $<) $<

%.png: %.svg
	@echo $< "->" $@
	$(INKSCAPE) $(INKSCAPE_FLAGS) -D -z -e $@ -d 720 $<

%.pdf: %.tex all-svg $(PANDOC_TEX_DEPENDENCIES)
	@echo $< "->" $@
	$(LATEX) $(LATEX_FLAGS) $(LATEX_PDF_FLAGS) $< 1>/dev/null
	$(LATEX) $(LATEX_FLAGS) $(LATEX_PDF_FLAGS) $< 1>/dev/null

%.tex: %.md
	@echo $< "->" $@
	$(PANDOC) $(PANDOC_FLAGS) $(PANDOC_TEX_FLAGS) --listings -s $< -o $@
