#
#  Makefile for the Codingdomain website.
#  This file runs all commands to generate
#  the HTML content from the XML sources.
#
#  Custom settings can be defined in settings.mk
#


#
# Parameters for xslt processing
#
DATE     = $(shell date '+%Y-%m-%d %H:%M')
SITEMAP  =
MAINXSL  =
include resources/scripts/settings.mk



#
# Build list of files
#
DIRS    = $(shell find . -type d | grep -v resources | grep -v blog | sort)
XMLSRC  = $(foreach DIR,$(DIRS),$(wildcard $(DIR)/*.xml))
HTMLOUT = $(subst .xml,.html,$(XMLSRC))
XSLDEP  = $(wildcard resources/xsl/include/*.xsl) $(MAINXSL) resources/inc/menu.inc

SITEMAPXML = $(shell find . -type f -name '*.xml' -print0 | xargs -0 grep -l '<sitemap' )
SITEMAPDEP = $(wildcard resources/inc/sitemap.inc)



#
# Default 'make' compiles the html files
#
all: last.upload $(SITEMAP) $(HTMLOUT)



#
# sitemap target to build sitemap
#
ifdef SITEMAP
$(SITEMAP): $(XMLSRC) resources/xsl/sitemap.xsl resources/scripts/sitetree.pl
	@resources/scripts/sitetree.pl . \
	| xsltproc --nonet \
	           --nomkdir \
	           --output "$(SITEMAP).new" \
	           "resources/xsl/sitemap.xsl" \
	           "-"
	@diff -q "$(SITEMAP).new" "$(SITEMAP)" >/dev/null || ( echo Updating sitemap; mv "$(SITEMAP).new" "$(SITEMAP)"; touch -c $(SITEMAPXML); $(MAKE) --no-print-directory )
	@rm -f "$(SITEMAP).new"
endif



#
# 'make clean' removes all HTML output
#
clean:
	rm -f $(HTMLOUT) $(SITEMAP)



#
# 'make upload' to update the online website
# (special case for /errordocs/ needs to be added)
#
upload: all
	@echo "Preparing to upload:"
	@find . -type f -cnewer last.upload | sort | resources/scripts/upload.pl
	@touch last.upload



#
# compile the xml file
# automatic target using pattern matching ($< = source, $@ = dest)
#
%.html: %.xml $(XSLDEP)
ifndef MAINXSL
	@echo "No MAINXSL value defined in settings.mk" >&2
	@exit 1
endif
	@test -e "$@" && echo "Updating $@" || echo "Creating $@"
	@xsltproc \
	         --stringparam "date" "$(DATE)" \
	         --stringparam "path" "`dirname $@`" \
	         --nonet \
	         --nomkdir \
	         --output "$@" \
	         "$(MAINXSL)" \
	         "$<"
#	@sabcmd "\$$date=$(DATE)" "\$$path=`dirname $@`" "$(MAINXSL)" "$<" "$@"



#
# generate the last upload file if it didn't exist
#
last.upload:
	@touch last.upload



#
# explicitly declare a target as phony,
# if a file called "all" is ever created
#
.PHONY: all clean upload sitemap


