# Disable pre-existing implicit rules and suffix rules for easier dep debugging.
%.o : %.s
% : RCS/%,v
% : RCS/%
% : %,v
% : s.%
% : SCCS/s.%
.SUFFIXES:
SUFFIXES :=

TOP := $(realpath $(dir $(firstword $(MAKEFILE_LIST))))

INFRA_JS = $(patsubst %,js/%.js,jquery-3.6.0.min noconflict prototype-1.7 emphasis-src searchbox)
# js/MathJax
INFRA_CSS = $(patsubst %,css/%.css,main searchbox)
INFRA_MEDIA = robots.txt favicon.ico images/feed-icon-14x14.png
INFRA_CODE = Makefile thumbnails.sh atom.py gen_urn.py jsonify.py template.html render_page.sh list_posts.py fixup.py
INFRA = $(INFRA_CODE) $(INFRA_JS) $(INFRA_CSS) $(INFRA_MEDIA)
POSTS = $(shell find posts -mindepth 2 -name 'index.txt' | xargs ls -t1)
PAGES_TXT = index.txt posts/index.txt $(POSTS)
PAGES_HTML = $(patsubst %.txt,%.html,$(PAGES_TXT))
PAGES_URN = $(patsubst %.txt,%.urn,$(PAGES_TXT))
PAGES_EXTRA = $(shell cat $(patsubst %.txt,%.rsync,$(POSTS)) 2>/dev/null)
PAGES = site.json \
	site.css \
	site.min.css \
	site.js \
	site.min.js \
	posts/atom.xml \
	$(PAGES_HTML) \
	$(PAGES_TXT) \
	$(PAGES_URN) \
	$(PAGES_EXTRA)

pages: $(PAGES)

serve:
	@echo "sudo python -m SimpleHTTPServer 80 &>/dev/null &"

index.txt.tmp: index.txt posts/index.txt Makefile
	cat index.txt | head -n 6 > index.txt.tmp
	cat posts/index.txt | tail -n +7 | head -n 3 >> index.txt.tmp
	cat index.txt | tail -n +10 >> index.txt.tmp
	sed -i -e "s/) <.*/)*/" index.txt.tmp
	sed -i -e "s/1. /1. */" index.txt.tmp
	sed -i -e "s,\./,./posts/," index.txt.tmp

posts/index.txt: list_posts.py $(POSTS)
	./list_posts.py $(POSTS) > $@

posts/atom.xml: atom.py $(POSTS)
	python ./atom.py $(POSTS) > $@

%.html: %.txt template.html render_page.sh fixup.py
	@[ -d $(@D) ] || mkdir -p $(@D)
	./render_page.sh $@ $<

%.urn:
	if ! [ -f $@ ]; then ./gen_urn.py > $@; fi

site.json: $(filter-out index.txt posts/index.txt,$(PAGES_TXT)) jsonify.py Makefile
	./jsonify.py $(filter %.txt,$^) > $@

site.js: $(filter-out js/MathJax,$(INFRA_JS))
	cat $^ > $@

site.min.js: site.js
	yuicompressor --type=js -o $@ $<

site.css: $(INFRA_CSS)
	cat $^ > $@

site.min.css: site.css
	yuicompressor --type=css -o $@ $<

rsync:
	#rsync -PRaizc $(INFRA) $(PAGES) alpha:/var/www-mstone.info
	rsync -PRaizc $(INFRA) $(PAGES) beta:/var/www-mstone.info
	#rsync -PRaizc $(INFRA) $(PAGES) /var/www-mstone.info

reverse:
	rsync -Paizcn alpha:/var/www-mstone.info/. .

AWS_HOST=ec2-54-245-30-61.us-west-2.compute.amazonaws.com

rsync2: $(INFRA) $(PAGES_TXT) $(PAGES_URN)
	rsync -e "ssh -i $$HOME/mstone-pandoc.pem" -PRaizc $^ ubuntu@$(AWS_HOST):site
	ssh -i $$HOME/mstone-pandoc.pem ubuntu@$(AWS_HOST) '/bin/sh -c "cd site && make"'

rsync3:
	rsync -e "ssh -i $$HOME/mstone-pandoc.pem" -PRaizc ubuntu@$(AWS_HOST):site $$HOME/

dev:
	nix develop path:$(TOP)/flake

watch:
	find . -name '*.txt' | entr make

update:
	(cd flake; nix flake update --update-input nixpkgs)

.PHONY: update
