SHELL = /bin/sh
INSTALLDIR_HTML := ./public_html/eh/eh/eh/eh-eh/
INSTALLDIR_ANSI := ./public_ansi/

# The name of the stylesheet. This needs to be copied to any directory containing html files that use it.
style := style.css
images := images

# Main html template that pandoc uses to generate .html from .md files
template_html := pandoc/template.html
template_ansi := pandoc/template

# Template for extracting metadata of .md files in json format
list_template := pandoc/meta-json-template.txt

# List of articles with their metadata to be used in the creation of the article list in index.html 
article_list := articles.json

# article targets
articles_html := $(patsubst %.md,%.html,$(wildcard articles/*.md))
articles_ansi := $(patsubst %.md,%,$(wildcard articles/*.md))

all: index.html index about.html about

install:
	cp -r index.html about.html shark.js shark.png $(articles_html) $(style) $(images) $(INSTALLDIR_HTML); \
	cp -r index about $(articles_ansi) $(INSTALLDIR_ANSI);

clean:
	echo '{"articles": []}' > $(article_list); \
		rm index.html about.html $(articles_html) $(articles_ansi);

$(articles_html): %.html: %.md
	jq 'del(.articles[] | select(.filename == "$(notdir $@)"))' $(article_list) > articles.json.tmp; \
	mv ./articles.json.tmp $(article_list); \

	# Build articles using pandoc
	pandoc $< --template $(template_html) --css $(style) --highlight-style zenburn --mathml --toc --output $@; \
	
	# Extract metadata from .md file, append filename field to the article object.
	# This is used to link to the article from index.html. Append article object to the article list.
	jq '.articles += [$(shell pandoc $< --template $(list_template) | jq '. += {"filename": "$(patsubst %.html, %, $(notdir $@))"}')]' $(article_list) > articles.json.tmp; \
	mv ./articles.json.tmp $(article_list); \

$(articles_ansi): %: %.md
	pandoc $< --template $(template_ansi) --to ansi --output $@

index.html: index.md $(articles_html) 
	# Build index.html with metadata injected from articles_list
	pandoc $< --template $(template_html) --include-after-body shark.js --css $(style) --metadata-file $(article_list) --highlight-style zenburn --mathml --toc --output $@; \

index: index.md $(articles_html) $(articles_ansi)
	pandoc $< --template $(template_ansi) --metadata-file $(article_list) --to ansi --output $@

about.html: about.md
	pandoc $< --template $(template_html) --css $(style) --highlight-style zenburn --mathml --toc --output $@

about: about.md
	pandoc $< --template $(template_ansi) --to ansi --output $@
