SHELL = /bin/sh

# ━ § BASIC INFORMATION ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
override define makefileinfo
 ╭────────────────────────────╮
╔╡ ⁌ ⛩️📰 书社 ∷ GNUmakefile ╞════════════════════════════════╗
║╰────────────────────────────╯                                ║
╟┬ ¶ Prerequisites ───────────────────────────────────────────┬╢
║│                                                            │║
║│ Requires G·N·U Make, at least version 3.81, a version of   │║
║│ uuencode with base64 support, and the various programs     │║
║│ offered by libxml2 and libxslt. Beyond this, only programs │║
║│ required by Posix are used, altho there is a chance of     │║
║│ version incompatibilities. The full list of program        │║
║│ requirements is as follows :—                             │║
║│                                                            │║
║│ • awk                                                      │║
║│ • cat                                                      │║
║│ • cp                                                       │║
║│ • date                                                     │║
║│ • echo                                                     │║
║│ • file                                                     │║
║│ • find                                                     │║
║│ • mkdir (requires support for `-p´)                        │║
║│ • mv                                                       │║
║│ • od (requires support for `-t x1´)                        │║
║│ • printf                                                   │║
║│ • rm                                                       │║
║│ • sed                                                      │║
║│ • sleep                                                    │║
║│ • stat                                                     │║
║│ • test                                                     │║
║│ • touch                                                    │║
║│ • tr (requires support for `-d´)                           │║
║│ • uuencode (requires support for `-m´ and `-r´)            │║
║│ • xargs (requires support for `-0´)                        │║
║│ • xmlcatalog (provided by libxml2)                         │║
║│ • xmllint (provided by libxml2)                            │║
║│ • xsltproc (provided by libxslt)                           │║
║│                                                            │║
║│ In all cases, you can supply your own version of any       │║
║│ program `program´ by overriding the corresponding variable │║
║│ `PROGRAM´ when calling Make.                               │║
║╰────────────────────────────────────────────────────────────╯║
╟┬ ¶ Usage ───────────────────────────────────────────────────┬╢
║│                                                            │║
║│ • `make all´: Compile, but do not install, all files.      │║
║│                                                            │║
║│ • `make clean´: Remove `BUILDDIR´.                         │║
║│                                                            │║
║│ • `make gone´: Remove installed files.                     │║
║│                                                            │║
║│ • `make help´ (default): Print this message.               │║
║│                                                            │║
║│ • `make install´: Compile all files and install in         │║
║│   `DESTDIR´.                                               │║
║│                                                            │║
║│ • `make list´: List all recognized source files and their  │║
║│   classification (including media type and dependencies).  │║
║│                                                            │║
║│ Set `VERBOSE=1´ to see the text of commands as they are    │║
║│ executed.                                                  │║
║│                                                            │║
║│ See `README.markdown´ for a more involved description of   │║
║│ the capabilities and configuration of this program.        │║
║╰────────────────────────────────────────────────────────────╯║
╟┬ ¶ Copyright & License ─────────────────────────────────────┬╢
║│                                                            │║
║│ Copyright © 2023–2024 Lady [@ Lady’s Computer].            │║
║│                                                            │║
║│ This Source Code Form is subject to the terms of the       │║
║│ Mozilla Public License, v 2.0. If a copy of the M·P·L was  │║
║│ not distributed with this file, You can obtain one at      │║
║│ <http://mozilla.org/MPL/2.0/>.                             │║
║╰────────────────────────────────────────────────────────────╯║
╚══════════════════════════════════════════════════════════════╝
endef

# ━ § MAKE·FILE SETUP ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

# Programs needed to run this make·file.
#
# If these are not installed on your computer, or you need to use a
# different implementation, you can override the appropriate variable.
AWK := awk
CAT := cat
CP := cp
DATE := date
ECHO := echo
FILE := file
FIND := find
MKDIR := mkdir
MV := mv
OD := od
PRINTF := printf
RM := rm
SED := sed
SLEEP := sleep
STAT := stat
TEST := test
TOUCH := touch
TR := tr
UUENCODE := uuencode
XARGS := xargs
XMLCATALOG := xmlcatalog
XMLLINT := xmllint
XSLTPROC := xsltproc

# The directory which contains the source files.
#
# Multiple directories can be given so long as files with the same name
# do not exist in each.
SRCDIR := sources

# The directory which contains “includes”: Files which may be included
# in other files but for which no final output will be generated.
#
# Multiple directories can be given so long as files with the same name
# do not exist in each.
#
# These can be inside of `SRCDIR´ directories if desired.
INCLUDEDIR := sources/includes

# The directory in which to generate temporary buildfiles.
BUILDDIR := build

# The directory into which to output files on `make install´.
DESTDIR := public

# The location of this Makefile (and related ⛩️📰 书社 files),
# relative to the current working directory.
#
# By default, this is inferred from the variable `MAKEFILE_LIST´.
THISDIR := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))

# The location of the magic files to use when determining media types.
#
# One is provided as part of this repository, but you can override it
# if you need different media type detection.
#
# Your computer probably has a more comprehensive one installed at
# `/usr/share/file/magic´, but it is not recommended that you use this
# directly. Instead, link or copy just the files you expect to need for
# your project.
MAGICDIR := $(patsubst ./%,%,$(THISDIR)/magic)

# Configuration of `find´.
#
# By default, `find´ will not follow symlinks and will use extended
# regular expressions, ignoring hidden files and those which begin with
# a period.
FINDRULES := -flags -nohidden -and ! '(' '(' -name '[.-]*' -or -name '*[:|$$%]*' ')' -and -prune ')'
FINDINCLUDERULES := $(FINDRULES)

# The list of parsers for plaintext file types.
#
# Which parsers are provided will influence which kinds of files are
# recognized as plaintext.
#
# Each parser ⁜must⁜ have a template which matches ⁜only⁜ X·H·T·M·L
# `<script>´ elements that have a `@type´ of a plaintext type supported
# by the parser. They may have multiple.
PARSERS := $(patsubst ./%,%,$(wildcard $(THISDIR)/parsers/*.xslt))

# The list of transforms.
TRANSFORMS := $(patsubst ./%,%,$(wildcard $(THISDIR)/transforms/*.xslt))

# List of types which should be treated as X·M·L.
XMLTYPES := application/xml text/xml

# Set to a non·empty value to print all commands as they run.
VERBOSE :=

# The default target for this makefile.
#
# Print help and exit.
.DEFAULT_GOAL := help

# ━ § BEGIN MAKE·FILE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

# ─ ¶ Non‐Recipe Variable Definitions ─────────────────────────────────

# A variable with no value, usable when assigning values which contain
# whitespace.
override empty :=

# A variable which contains a newline, to allow the generation of
# multiline strings in function calls.
override define newline


endef

# A variable which contains a single space.
override space := $(empty) $(empty)

# A variable which contains a single comma.
override comma := ,

# (callable) Quote the given string for use within shell calls.
override quote = '$(subst ','"'"',$1)'

# Outputs an `@´ to silence rules, unless `VERBOSE´ is nonempty.
override silent := $(if $(VERBOSE),,@)

# (callable) Escape special characters for use in sed regular
# expressions.
override sedesc = $(subst /,[/],$(subst $$,\$$,$(subst *,\*,$(subst .,\.,$(subst [,\[,$(subst ^,\^,$(subst \,\\,$1)))))))

# (callable) Percent‐decode the given strings.
override perdec = $(foreach encoded,$1,$(shell $(PRINTF) '%s\n' $(call quote,$(encoded)) | $(SED) 's/|/|%7C|/g;s/[\]/|%5C|/g;s/%[0-9A-Fa-f]\{2\}/|&|/g' | $(TR) '|' '\n' | $(SED) '/^%[0-9A-Fa-f]\{2\}$$/!s/%/|%25|/' | $(TR) '|' '\n' | $(AWK) '$$0!~/%/{printf("%s",$$0)}/%/{sub("%","0x");printf("\\%04o",$$0)}' | $(XARGS) -0 $(PRINTF) '%b'))

# (callable) Percent‐encode the given strings.
#
# This singly‐encodes u·r·i characters and doubly‐encodes other
# characters, then calls `perdec´ to decode back to a single encoding.
# The encoding assumes the input is a “u·r·i component”; e·g that the
# resulting string should only contain `pchar´ (but can contain any
# `sub-delim´).
override perenc = $(foreach unencoded,$1,$(call perdec,$(shell $(PRINTF) '%s' $(call quote,$(unencoded)) | $(OD) -t x1 | $(SED) 's/^[0-9]*//;s/2[146-9A-Ea-e]/%&/g;s/3[0-9AaBbDd]/%&/g;s/40/%&/g;s/[46][1-9A-Fa-f]/%&/g;s/[57][0-9Aa]/%&/g;s/7[Ee]/%&/g;s/[ ][0-9A-Fa-f]\{2\}/%25&/g' | $(TR) -d ' \n' | $(TR) 'abcdef' 'ABCDEF')))

# (callable) Percent‐encode each component in the given paths.
override pathenc = $(foreach path,$1,$(subst $(space),/,$(call perenc,$(subst /, ,$(path)))))

# (overridable) Collect all of the applicable includes from the
# includes directory.
sourceincludes := $(shell $(FIND) $(FINDOPTS) $(INCLUDEDIR) -type f '(' $(FINDRULES) ')')

# (overridable) Collect all of the applicable source files from the
# source directory, removing any which are also includes.
sourcefiles := $(filter-out $(sourceincludes),$(shell $(FIND) $(FINDOPTS) $(SRCDIR) -type f '(' $(FINDRULES) ')'))

# Figure out the file type of each source file and source include.
ifneq ($(wildcard $(BUILDDIR)/magic.mgc),)
override types := $(shell $(SED) 's/^ *//;s/ *$$//;s/ {2,}/ /g' <<< $(call quote,$(sourcefiles) $(sourceincludes)) | $(TR) ' ' '\n' | $(FILE) -m $(call quote,$(BUILDDIR)/magic.mgc) --mime-type --separator '|' --files-from - | $(SED) 's/| */|/g')
endif

# Get the list of supported plaintext file types from the parser.
ifneq ($(wildcard $(BUILDDIR)/parser.xslt),)
override plaintexttypes := $(filter-out $(XMLTYPES),$(shell $(XSLTPROC) $(call quote,$(THISDIR)/lib/parser2types.xslt) $(call quote,$(BUILDDIR)/parser.xslt)))
endif

# (callable) Get all of the files (source and includes) which have the
# given types.
override filesoftype = $(foreach type,$1,$(patsubst %|$(type),%,$(filter %|$(type),$(types))))

# Build up collections of various file types.
override xmlfiles := $(call filesoftype,$(XMLTYPES))
override plaintextfiles := $(filter-out $(xmlfiles),$(call filesoftype,$(plaintexttypes)))
override assetfiles := $(filter-out $(xmlfiles) $(plaintextfiles),$(sourcefiles) $(sourceincludes))

# (callable) Get the types of the given files.
override typeoffile = $(patsubst $(foreach file,$1,$(file)|%),%,$(filter $(foreach file,$1,$(file)|%),$(types)))

# (callable) Get the identifier for the given transform.
override id = $(or $(shell $(XMLLINT) --xpath '/*/*[local-name()="id" and namespace-uri()="urn:fdc:ladys.computer:20231231:Shu1She4"]/text()[1]' $1),example:$(call pathenc,$(basename $(notdir $1))))

# (callable) Get the local path for the given source file.
override sourcepath = $(firstword $(foreach directory,$(SRCDIR),$(if $(filter $(directory)/%,$1),$(patsubst $(directory)/%,%,$1),)))

# (callable) Get the local path for the given include.
override includepath = $(firstword $(foreach directory,$(INCLUDEDIR),$(if $(filter $(directory)/%,$1),$(patsubst $(directory)/%,%,$1),)))

# (callable) Get base64 data u·r·i’s for the given files.
override datauri = $(foreach file,$1,data:$(call typeoffile,$(file));base64,$(shell $(UUENCODE) -m -r $(call quote,$(file)) _ | tr -d ' \n'))

# Pair each source file and include with its local u·r·i.
override sourcelocalpair := $(foreach file,$(sourcefiles) $(sourceincludes),$(file)|about:shushe?$(if $(filter $(file),$(sourceincludes)),include=$(call pathenc,$(call includepath,$(file))),source=$(call pathenc,$(call sourcepath,$(file)))))

# (callable) Get local uris for the given files.
override localuri = $(foreach file,$1,$(patsubst $(file)|%,%,$(filter $(file)|%,$(sourcelocalpair))))

# (callable) Get the source files for the given local uris.
override sourcefile = $(foreach local,$1,$(patsubst %|$(local),%,$(filter %|$(local),$(sourcelocalpair))))

# Adds a requirement on `$(BUILDDIR)/.update-types´ if the file is
# present.
#
# This file is created after a reload due to type changes, and is
# removed after. Requiring it ensures that file classifications are
# up‐to‐date immediately after the reload.
override typeupdates := $(wildcard $(BUILDDIR)/.update-types)

# Pair each source file and include with its parsed location.
override sourceparsedpair := $(foreach file,$(sourcefiles) $(sourceincludes),$(file)|$(BUILDDIR)/$(if $(filter $(file),$(sourceincludes)),includes/$(call includepath,$(file)),sources/$(call sourcepath,$(file))))

# (callable) Get the location of the transformed X·M·L files for the
# given source files.
override parsed = $(foreach file,$1,$(patsubst $(file)|%,%,$(filter $(file)|%,$(sourceparsedpair))))

# (callable) Get the source files for the given parsed file.
override unparsed = $(foreach file,$1,$(patsubst %|$(file),%,$(filter %|$(file),$(sourceparsedpair))))

ifneq ($(wildcard $(BUILDDIR)/dependencies),)
# Pair each file with a list of dependencies for it.
override dependenciesforfile := $(foreach file,$(sourcefiles),$(file)|$(subst $(space),|,$(shell $(CAT) $(call quote,$(BUILDDIR)/dependencies) | $(SED) $(call quote,/^$(call sedesc,$(call localuri,$(file)))$$/$(comma)/^[^	]/!d;/^	/!d;s/^	//))))

# (callable) Get the list of dependency leiris for the given source
# files.
#
# Recursive dependencies are marked with a leading `-´.
override dependencyuris = $(foreach file,$1,$(subst |, ,$(patsubst $(file)|%,%,$(filter $(file)|%,$(dependenciesforfile)))))

# (callable) Get the list of recursive dependencies for the given
# source files.
override recursives = $(foreach uri,$(filter -%,$(call dependencyuris,$1)),$(call sourcefile,$(patsubst -%,%,$(uri))))

# (callable) Get the list of (nonrecursive) dependencies for the given
# source files.
override dependencies = $(foreach uri,$(filter-out -%,$(call dependencyuris,$1)),$(call sourcefile,$(uri)))
endif

# Collect all files with recursive dependencies.
override recursivefiles := $(foreach file,$(filter-out $(assetfiles),$(sourcefiles)),$(if $(call recursives,$(file)),$(file),))

# Collect all files which should be compiled.
#
# This is all of the non·asset, nonrecursive files.
override compilablefiles := $(filter-out $(assetfiles) $(recursivefiles),$(sourcefiles))

ifneq ($(wildcard $(BUILDDIR)/destinations),)
# Get the output of the destination transform.
override destinations := $(shell $(CAT) $(BUILDDIR)/destinations)

# Pair source files and their destinations.
override sourcedestinationpair := $(foreach destination,$(destinations),$(call sourcefile,$(firstword $(subst |, ,$(destination))))|$(call perdec,$(subst $(space),|,$(wordlist 2,$(words $(subst |, ,$(destination))),$(subst |, ,$(destination))))))

# (callable) Get the destination for the given source files.
override destination = $(foreach file,$1,$(patsubst $(file)|%,%,$(filter $(file)|%,$(sourcedestinationpair))))

# Pair each source file and include with its compiled location.
override sourcecompiledpair := $(foreach file,$(sourcefiles) $(sourceincludes),$(file)|$(BUILDDIR)/public/$(call destination,$(file)))

# (callable) Get the location of the transformed X·M·L files for the
# given source files.
override compiled = $(foreach file,$1,$(patsubst $(file)|%,%,$(filter $(file)|%,$(sourcecompiledpair))))

# (callable) Get the source files for the given compiled file.
override uncompiled = $(foreach file,$1,$(patsubst %|$(file),%,$(filter %|$(file),$(sourcecompiledpair))))

# (callable) Get the installed locations for the given source files.
override installed = $(foreach file,$1,$(DESTDIR)/$(call destination,$(file)))
endif

# ─ ¶ Recipe Variable Definitions ─────────────────────────────────────

# (callable) Check to see if the given directory exists and
# create it if not.
override ensuredirectory = if $(TEST) ! -d $(call quote,$1); then $(MKDIR) -p $(call quote,$1); fi

# (callable) Sanitize and wrap the provided plaintext file in
#  X·M·L, printing to `stdout´.
override wrapplaintext = $(PRINTF) '%s\n' "$$($(PRINTF) '%b' '<?xml version=\042\061.0\042?>\n<script xmlns=\042http://www.w3.org/1999/xhtml\042 type=\042$(call typeoffile,$1)\042><![CDATA['; $(CAT) $(call quote,$1) | $(TR) '\000\013\014' '\032\011\012' | $(SED) $$($(PRINTF) '%s%b' 's/]]>/]]]]><!\[CDATA\[>/g;s/\xEF\xBF\xBE/�/g;s/\xEF\xBF\xBF/�/g;$$!s/\r$$//g;s/\r/\n/g;$$!s/\xC2\x85$$//g;s/\xC2\x85/\n/g;s/\xE2\x80\xA8/\n/g;' 's/[\0001-\0010]/�/g;s/[\0016-\0037]/�/g'); $(PRINTF) '%s' ']]></script>')"

# ─ ¶ Phony Targets ───────────────────────────────────────────────────

# Provide help.
help:
	$(silent)$(PRINTF) '%b' '$(subst $(newline),\n,$(makefileinfo))'

# Compile all files, or error if any are recursive.
all: $(call compiled,$(recursivefiles) $(compilablefiles) $(filter $(sourcefiles),$(assetfiles))) ;

# Destroy buildfiles.
clean:
	$(silent)$(RM) -rf $(BUILDDIR)/

# Destroy buildfiles and the install directory.
gone:
	$(silent)$(RM) -rf $(BUILDDIR)/ $(call compiled,$(recursivefiles) $(compilablefiles))

# Install the compiled files into `DESTDIR´.
install: $(call installed,$(recursivefiles) $(compilablefiles) $(filter $(sourcefiles),$(assetfiles))) ;

# List all source files and includes and their computed types.
list:
	$(silent)$(PRINTF) '%b' $(call quote,$(foreach file,$(sort $(sourcefiles)) $(sort $(sourceincludes)),\0033[1m$(file)\0033[22m|$(call typeoffile,$(file))|[\0033[3m$(if $(filter $(file),$(xmlfiles)),xml,$(if $(filter $(file),$(plaintextfiles)),text,asset))$(if $(filter $(file),$(sourceincludes)),|include,)\0033[23m]$(if $(call dependencies,$(file))$(call recursives,$(file)), $(strip $(foreach recursive,$(call recursives,$(file)),\0033[93;41m•|Recursive|Dependency|\0033[39;49m|$(recursive)) $(foreach dependency,$(call dependencies,$(file)),\0033[2m•|Dependency|\0033[22m|$(dependency))))$(if $(filter $(file),$(sourcefiles)), →|<\0033[4m/$(call destination,$(file))\0033[24m>,) )) | $(TR) ' |' '\n '

# Raise an error when attempting to build any files with recursive
# dependencies.
$(call compiled,$(recursivefiles)):
	@$(PRINTF) '%b\n' $(call quote,\0033[93;41mError:\0033[39;49m `$(call uncompiled,$@)´ has recursive dependencies:\n$(subst |, ,$(subst $(space),$(newline),$(foreach recursive,$(call recursives,$(call uncompiled,$@)),•|$(recursive))))) && false

# ─ ¶ Special Targets ─────────────────────────────────────────────────

# Perform secondary expansion; this enables pattern rules to determine
# their prerequisites based on the matched pattern.
.SECONDEXPANSION: ;

# Don’t use any implicit rules.
.SUFFIXES: ;

# Phony rules; always consider these out‐of‐date.
.PHONY: all default clean gone info install list $(call compiled,$(recursivefiles));

ifneq ($(wildcard $(BUILDDIR)/.update-types)$(wildcard $(BUILDDIR)/dependencies),)
# Reload this make·file if the dependency graph has changed.
#
# This graph is a dependency for some of the variables that this
# make·file uses, so it’s important to ensure that they are actually
# up‐to‐date prior to executing any later rules.
#
# This recipe only exists after types have been updated or when the
# dependency graph already exists.
$(THISDIR)/GNUmakefile:: $(BUILDDIR)/dependencies $(BUILDDIR)/destinations
	$(silent)$(TOUCH) $(THISDIR)/GNUmakefile
	$(silent)$(RM) -f $(BUILDDIR)/.update-types
	@$(PRINTF) '%b\n' '\0033[1mDependency graph and output destinations updated. Restarting…\0033[22m'
endif

ifeq ($(wildcard $(BUILDDIR)/.update-types),)
# Reload this make·file if any of the magic files or parsers have
# changed.
#
# These are used to classify source files, so if they have changed then
# the make·file must be reloaded.
#
# This recipe sleeps for one second to ensure that files built after
# the restart have a more current time·stamp.
$(THISDIR)/GNUmakefile:: $(BUILDDIR)/magic.mgc $(BUILDDIR)/parser.xslt $(THISDIR)/lib/parser2types.xslt
	$(silent)$(TOUCH) $(THISDIR)/GNUmakefile
	$(silent)$(RM) -f $(call quote,$(BUILDDIR)/dependencies)
	@$(PRINTF) '%b\n' '\0033[1mMagic file or parsers have updated. Restarting…\0033[22m'
	$(silent)$(SLEEP) 1
	$(silent)$(TOUCH) $(call quote,$(BUILDDIR)/.update-types)
endif

# ─ ¶ Build Targets ───────────────────────────────────────────────────

# Generate the compiled magic file from its sources.
#
# It must be updated if any of the files in the magic directory change.
# It ⁜also⁜ should be updated if any of the files in the magic
# directory are deleted, but this isn’t tracked presently.
$(BUILDDIR)/magic.mgc: $(wildcard $(MAGICDIR)/*)
	@$(ECHO) "Compiling new magic…"
	$(silent)$(call ensuredirectory,$(dir $@))
	$(silent)cd $(call quote,$(BUILDDIR)) && $(FILE) -C -m $(call quote,$(realpath $(MAGICDIR)))

# Generate the main parser.
$(BUILDDIR)/parser.catalog: $(PARSERS)
	@$(ECHO) "Generating catalog of parsers…"
	$(silent)$(XMLCATALOG) --create --noout $(call quote,$@)
	$(foreach parser,$(PARSERS),$(silent)$(XMLCATALOG) --add uri $(call quote,$(call id,$(parser))) $(call quote,$(call pathenc,../$(parser))) --noout $(call quote,$@)$(newline))
$(BUILDDIR)/parser.xslt: $(BUILDDIR)/parser.catalog $(THISDIR)/lib/catalog2parser.xslt
	@$(ECHO) "Generating main parser…"
	$(silent)$(XSLTPROC) -o $(call quote,$@) $(call quote,$(THISDIR)/lib/catalog2parser.xslt) $(call quote,$<)

# Parse the files.
#
# Even plain X·M·L files are parsed, because they may contain X·H·T·M·L
# `<script>´ elements which contain other kinds of data. Asset files
# are turned into H·T·M·L embeds pointing to `data:´ U·R·I’s.
$(call parsed,$(sourcefiles) $(sourceincludes)): %: $$(call unparsed,$$@) $(typeupdates)
	@$(PRINTF) '%s\n' $(call quote,Processing `$<´…)
	$(silent)$(call ensuredirectory,$(dir $@))
	$(silent)$(if $(filter $<,$(assetfiles)),$(PRINTF) '%s\n' $(call quote,<object xmlns="http://www.w3.org/1999/xhtml" type="$(call typeoffile,$<)" data="$(call datauri,$<)"/>) > $(call quote,$@),$(if $(filter $<,$(plaintextfiles)),$(call wrapplaintext,$<),$(CAT) $(call quote,$<)) | $(XSLTPROC) -o $(call quote,$@) $(call quote,$(BUILDDIR)/parser.xslt) -)

# Generate a catalog of all parsed files, for use when processing
# includes. This does not depend on actually transforming the files.
$(BUILDDIR)/catalog: $(sourcefiles) $(sourceincludes) $(typeupdates)
	@$(ECHO) "Generating catalog of parsed files…"
	$(silent)$(XMLCATALOG) --create --noout $(call quote,$@)
	$(foreach source,$(sourcefiles) $(sourceincludes),$(silent)$(XMLCATALOG) --add uri $(call quote,$(call localuri,$(source))) $(call quote,$(call pathenc,$(patsubst $(BUILDDIR)/%,%,$(call parsed,$(source))))#$(if $(filter $(source),$(assetfiles)),asset,xml)) --noout $(call quote,$@)$(newline))

# Build a list of dependencies for each parsed file.
$(BUILDDIR)/dependencies: $(BUILDDIR)/catalog $(call parsed,$(plaintextfiles) $(xmlfiles)) $(THISDIR)/lib/catalog2dependencies.xslt
	@$(ECHO) "Identifying dependencies…"
	$(silent)$(XSLTPROC) -o $(call quote,$@) $(call quote,$(THISDIR)/lib/catalog2dependencies.xslt) $(call quote,$<)

# Generate a catalog of destinations for files. This depends on parsing
# non·asset source files, but not assets or includes. It does not
# require knowing the dependencies.
$(BUILDDIR)/destinations: $(BUILDDIR)/catalog $(call parsed,$(filter-out $(assetfiles),$(sourcefiles))) $(THISDIR)/lib/catalog2destinations.xslt
	@$(ECHO) "Identifying output destinations…"
	$(silent)$(XSLTPROC) -o $(call quote,$@) $(call quote,$(THISDIR)/lib/catalog2destinations.xslt) $(call quote,$<)

# Generate the main transform.
$(BUILDDIR)/transform.catalog: $(TRANSFORMS)
	@$(ECHO) "Generating catalog of transforms…"
	$(silent)$(XMLCATALOG) --create --noout $(call quote,$@)
	$(foreach transform,$(TRANSFORMS),$(silent)$(XMLCATALOG) --add uri $(call quote,$(call id,$(transform))) $(call quote,$(call pathenc,../$(transform))) --noout $(call quote,$@)$(newline))
$(BUILDDIR)/transform.xslt: $(BUILDDIR)/transform.catalog $(THISDIR)/lib/catalog2transform.xslt
	@$(ECHO) "Generating main transform…"
	$(silent)$(XSLTPROC) -o $(call quote,$@) $(call quote,$(THISDIR)/lib/catalog2transform.xslt) $(call quote,$<)

# Generate the output files using the dependencies as necessary.
$(call compiled,$(compilablefiles)): $(BUILDDIR)/public/%: $$(call parsed,$$(call uncompiled,$$@)) $(BUILDDIR)/transform.xslt $$(call parsed,$$(call dependencies,$$(call uncompiled,$$@)))
	$(silent)$(call ensuredirectory,$(dir $@))
	@$(PRINTF) '%s\n' $(call quote,Compiling </$*>…)
	$(silent)$(XSLTPROC) -o $(call quote,$@) --stringparam catalog 'catalog' --stringparam buildtime '$(shell TZ= $(DATE) '+%Y-%m-%dT%H:%M:%SZ')' --stringparam srctime '$(shell TZ= $(STAT) -f '%Sm' -t '%Y-%m-%dT%H:%M:%SZ' $(call quote,$(call uncompiled,$@)))' --stringparam path $(call quote,/$*) $(call quote,$(BUILDDIR)/transform.xslt) $(call quote,$<)
$(call compiled,$(filter $(assetfiles),$(sourcefiles))): $(BUILDDIR)/public/%: $$(call uncompiled,$$@)
	@$(PRINTF) '%s\n' $(call quote,Compiling </$*>…)
	$(silent)$(call ensuredirectory,$(dir $@))
	$(silent)$(CP) $(call quote,$<) $(call quote,$@)

# Install compiled files (or error in the case of recursive ones).
$(call installed,$(filter $(assetfiles),$(sourcefiles)) $(recursivefiles) $(compilablefiles)): $(DESTDIR)/%: $(BUILDDIR)/public/%
	@$(PRINTF) '%s\n' $(call quote,Installing </$*>…)
	$(silent)$(call ensuredirectory,$(dir $@))
	$(silent)$(CP) $(call quote,$<) $(call quote,$@)