MAKEFILE_PROGRAMS = atangle cpif hangman horde pong bullsandcows monstersweeper
DOCUMENT_ONLY=db2html asciimaze
SUBDIRS = balls balls-android balls-ios
MAKEFILES = $(MAKEFILE_PROGRAMS:%=Makefile.%)
HTMLFILES = $(MAKEFILE_PROGRAMS:%=%.html) $(SUBDIRS:%=%.html) $(DOCUMENT_ONLY:%=%.html) README.html
PDFFILES = $(MAKEFILE_PROGRAMS:%=%.pdf) $(SUBDIRS:%=%.pdf) $(DOCUMENT_ONLY:%=%.pdf)
XSL_STYLESHEET = xhtml.xsl
ASCIIDOC_OPTIONS =

.PHONY: all clean html pdf $(SUBDIRS)

all: $(MAKEFILES) db2html.py subdirs html pdf

subdirs: $(SUBDIRS)

$(SUBDIRS):
	$(MAKE) -C $@

html: $(HTMLFILES) sitemap.xml

pdf: $(PDFFILES)

db2html.py: db2html.txt
	atangle $< > $@
	chmod +x $@

Makefile.%: %.txt
	atangle -r Makefile $< > $@
	$(MAKE) -f $@

%.html: $(XSL_STYLESHEET) %.xml
	db2html.py $^ > $@

%.pdf: %.xml
	dblatex -t pdf $< -o $@

README.xml: README.txt
	asciidoc -a toc! -a numbered! -b docbook -o $@ $<

%.xml: %.txt %-docinfo.xml
	asciidoc $(ASCIIDOC_OPTIONS) -b docbook -a docinfo -o $@ $<

%.xml: %/README.txt %/code.txt %/docinfo.xml
	asciidoc $(ASCIIDOC_OPTIONS) -b docbook -a docinfo1 -o $@ $<

%-docinfo.xml: %.txt
	hg log --style revhistory.style $< > $@

%/docinfo.xml: %/README.txt %/code.txt
	hg log --style revhistory.style $+ > $@

sitemap.xml: $(HTMLFILES)
	echo '<?xml version="1.0" encoding="UTF-8"?>' > $@
	echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' >> $@
	for page in $(HTMLFILES); do \
		echo ' <url>' >> $@ ; \
		echo "  <loc>$(SITE_URL)literate/$$page</loc>" >> $@ ; \
		(echo -n '  <lastmod>'; date -ur $$page +%FT%T%:z | tr -d '\n' ; echo '</lastmod>') >> $@ ; \
		echo '  <changefreq>monthly</changefreq>' >> $@ ; \
		echo '  <priority>0.8</priority>' >> $@ ; \
		echo ' </url>' >> $@ ; \
	done
	echo '</urlset>' >> $@

clean:
	for make in $(MAKEFILES); do $(MAKE) -f $$make clean ; done
	rm -f $(MAKEFILES) $(HTMLFILES) $(PDFFILES) sitemap.xml
