SHELL = /bin/bash

# ~~~ Variables used by rules ~~~
#

core-module-sources := render-page.rkt main.rkt
core-modules        := $(patsubst %.rkt, compiled/%_rkt.zo, $(core-module-sources))

pages-sources  := $(wildcard writing/*.page.rkt)
pages-compiled := $(patsubst writing/%.page.rkt, writing/compiled/%.page_rkt.zo, $(pages-sources))
pages-html     := $(patsubst writing/%.page.rkt, publish/%.html, $(pages-sources))

static-sources := $(wildcard static/*.*) $(wildcard static/**/*.*) static/.htaccess
static         := $(patsubst static/%, publish/%, $(static-sources))

webpage-sources   := $(wildcard web-pages/*.rkt)
webpages          := $(patsubst web-pages/%.rkt, publish/%.html, $(webpage-sources))

# ~~~ Rules ~~
#

# The order of these dependencies is important. They will be processed left to right.
web: publish/res/style.css $(pages-html) publish/feed.atom $(webpages) 
web: ## Rebuild all web pages

$(core-modules): compiled/%_rkt.zo: %.rkt
	raco make $<

$(pages-html): $(core-modules)
$(pages-html): publish/%.html: writing/compiled/%.page_rkt.zo
	racket -t render-page.rkt -- $(patsubst publish/%.html, writing/%.page.rkt, $@) > $@

$(pages-compiled): writing/compiled/%.page_rkt.zo: writing/%.page.rkt
	raco make $<

publish/feed.atom: $(pages-html) feed.rkt
	racket -tm feed.rkt

$(webpages): render-page.rkt
$(webpages): publish/%.html: web-pages/%.rkt
	racket $< > $@

publish/res/style.css: $(static-sources) 
	rm -rf publish && cp -pR static publish

zap: ## Clear Racket compile cache, and remove all HTML output
	rm -rf compiled || true
	rm -rf writing/compiled || true
	rm publish/*.html || true
	rm publish/feed.atom || true

publish: check-env
publish: ## Sync all content to the web server (does not rebuild any files)
	rsync -av --delete --exclude-from='publish_excludes.txt' publish/ $(JDCOM_SRV)

# Self-documenting makefile (http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html)
help: ## Displays this help screen
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}'

.PHONY: web help zap publish check-env

.DEFAULT_GOAL := help

check-env:
ifndef JDCOM_SRV
	$(error JDCOM_SRV env variable not set, should be a destination valid for rsync)
endif
