MAIN     = songbook
ENGINE   = lualatex
OUTDIR   = output
TEXENV   = TEXINPUTS=.:$(shell pwd):$(shell pwd)/$(OUTDIR):
FLAGS    = --output-directory=$(OUTDIR) --interaction=nonstopmode

.PHONY: all clean distclean

all: $(OUTDIR)/$(MAIN).pdf

$(OUTDIR):
	mkdir -p $(OUTDIR)

# Run until page references stabilize (max 5 passes).
# The .songtoc file needs: pass 1 to write, pass 2 to read into TOC,
# pass 3+ to stabilize page numbers after TOC page count changes.
$(OUTDIR)/$(MAIN).pdf: $(MAIN).tex songbook-style.sty songs/*.tex | $(OUTDIR)
	@for i in 1 2 3 4 5; do \
	  echo "=== LaTeX pass $$i ==="; \
	  $(TEXENV) $(ENGINE) $(FLAGS) $(MAIN).tex || true; \
	  if [ -f $(OUTDIR)/$(MAIN).songtoc ]; then \
	    python3 -c "import re;lines=open('$(OUTDIR)/$(MAIN).songtoc').readlines();lines.sort(key=lambda l:re.sub(r'[^a-zäöüß ]','',re.search(r'\{(?:\\\\textit\s*\{)?([^}]+)',l).group(1).lower()) if re.search(r'\{(?:\\\\textit\s*\{)?([^}]+)',l) else '');open('$(OUTDIR)/$(MAIN).songtoc','w').writelines(lines)" ; \
	  fi; \
	  if [ $$i -ge 3 ] && ! grep -q "Rerun" $(OUTDIR)/$(MAIN).log 2>/dev/null; then \
	    echo "=== Stable after $$i passes ==="; \
	    break; \
	  fi; \
	done

clean:
	rm -f $(OUTDIR)/*.aux $(OUTDIR)/*.log $(OUTDIR)/*.out \
	      $(OUTDIR)/*.toc $(OUTDIR)/*.fls $(OUTDIR)/*.fdb_latexmk \
	      $(OUTDIR)/*.sxd $(OUTDIR)/*.sxc $(OUTDIR)/*.songtoc

distclean: clean
	rm -f $(OUTDIR)/$(MAIN).pdf
