NAME := main

RM := rm
TEX := lualatex
BIB := biber
PANDOC := pandoc
LUA := lualatex --luaonly

OUTDIR=./output
TEXFLAGS := --interaction=nonstopmode --output-directory=$(OUTDIR)/
BIBFLAGS := --input-directory=$(OUTDIR) --output-directory=$(OUTDIR)/

PRINTFORMAT := "\033[1;92;49m%s\033[m\n"

USE_MARKDOWN := true
MARKDOWNS := $(wildcard markdown/*.md)
MARKDOWN_OUTPUTS := $(patsubst markdown/%.md,md-out/%.tex,$(MARKDOWNS))

BIBFILE := references.bib
MAIN := $(addsuffix .tex,${NAME})

.PHONY: ${MAIN} clean

all: ${MAIN}

generate:
	${LUA} script/generate-main.lua > main.tex

md-out/%.tex: markdown/%.md
ifeq ($(USE_MARKDOWN),true)
	mkdir -p md-out
	${PANDOC} -f gfm $< -t latex -o $@
else
	@printf ${PRINTFORMAT} "[$@: No markdown output]"
endif

single:
	${TEX} ${TEXFLAGS} ./${NAME}.tex

bib:
	${BIB} ${BIBFLAGS} ${NAME}

optimize:
	qpdf --linearize output/${NAME}.pdf output/${NAME}-opt.pdf
	qpdf --optimize-images output/${NAME}-opt.pdf output/${NAME}-opt-final.pdf
	rm output/${NAME}-opt.pdf

output/${NAME}.bcf: ${BIBFILE}
	@mkdir -p $(OUTDIR)
	@printf ${PRINTFORMAT} "[$@: Generating Bibliography Contexts]"
	-${TEX} ${TEXFLAGS} ./${NAME}.tex
	@printf ${PRINTFORMAT} "[$@: Building Bibliography Auxiliary File]"
	${BIB} ${BIBFLAGS} ${NAME}
	@printf ${PRINTFORMAT} "[$@: Linking Indexes and Contexts]"
	-${TEX} ${TEXFLAGS} ./${NAME}.tex

${MAIN}: $(MARKDOWN_OUTPUTS) output/${NAME}.bcf
	@mkdir -p $(OUTDIR)
	@printf ${PRINTFORMAT} "[$@: Building Output]"
	${TEX} ${TEXFLAGS} ./${NAME}.tex

clean:
	${RM} ./output/{*.aux,*.log,*.out,*.blg,*.bcf,*.bbl,*.xml}
	${RM} -dr ./md-out
