SHELL = /bin/sh

CMSROOT = ""
#CMSURL = http://keks.upful.org/p/
CMSURL = http://pyropeter.eu/

.SUFFIXES: .md .txt .htmlpart .htmlsum .html
.PHONY: clean watch

INS    := $(shell find . -regextype posix-extended -iregex '.*\.(md|txt)' \
                         -printf '%TY%Tm%Td%TH%TM %P\n' | sort -r \
			 | cut -b14- | grep -v robots.txt)
OUTS   := $(INS:.txt=.htmlpart)
OUTS   := $(OUTS:.md=.htmlpart)
SUMS   := $(OUTS:.htmlpart=.htmlsum)
HTMLS  := $(OUTS:.htmlpart=.html) blog/index.html
LAYOUT := layout.pre layout.post
INPUT  := $(INS) $(LAYOUT)

all: $(HTMLS) list.html listlong.html index.json sitemap.lst
	@echo "DONE"

%.htmlpart: %.md
	@echo "ART MD  $<"
	@echo "<article>" > $@
	@markdown_py -eutf-8 -ohtml4 $< >> $@
	@printf "\n</article>" >> $@

%.htmlpart: %.txt
	@echo "ART TXT $<"
	@echo "<article><h1>$<</h1><pre>" > $@
	@sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g' $< >> $@
	@echo "</pre></article>" >> $@

%.htmlsum: %.md
	@echo "SUM MD  $<"
	@echo "<article>" > $@
	@head -n12 $< | markdown_py -sremove -eutf-8 -ohtml4 /dev/stdin | sed '0,/<h1>/s!<h1>\(.*\)</h1>!<h1><a href="%root%/$(@:.htmlsum=.html)">\1</a></h1>!' >> $@
	@echo >> $@
	@echo "<p><a href='%root%/$(@:.htmlsum=.html)'>Read more…</a></p>" >> $@
	@echo "</article>" >> $@

%.htmlsum: %.txt
	@echo "SUM TXT $<"
	@echo "<article><h1><a href='%root%/$(@:.htmlsum=.html)'>$<</a></h1><pre>" >>$@
	@head -n12 $< | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g' >> $@
	@printf "\n</pre>" >> $@
	@echo "<p><a href='%root%/$(@:.htmlsum=.html)'>Read more…</a></p>" >> $@
	@echo "</article>" >> $@

%.html: %.htmlpart $(LAYOUT)
	@echo "HTML    $<"
	@sed "s!\(<title>\)\(.*</title>\)!\1$(shell grep /h1 $< | sed 's/<[^>]*>//g; s!\\!\\\\!g; s/!/\\!/g')\2!" layout.pre > $@
	@cat $< >> $@
	@cat layout.post >> $@
	@sed -i "s %root% $(CMSROOT) g" $@

list.html: $(SUMS) $(LAYOUT)
	@echo "LIST"
	@cp layout.pre $@
	@cat $(SUMS) >> $@
	@cat layout.post >> $@
	@sed -i "s %root% $(CMSROOT) g" $@

blog/index.html: $(filter blog/%,$(SUMS)) $(LAYOUT)
	@echo "BLOG"
	@sed "s!\(<title>\)\(.*</title>\)!\1Blog\2!" layout.pre > $@
	@echo "<article><p>" >> $@
	@echo "My <a href='/oldblog/blog.xhtml'>old blog</a> still exists, but I also imported the old entries into this page." >> $@
	@echo "</p></article><hr>" >> $@
	
	@cat $(filter blog/%,$(SUMS)) >> $@
	
	@cat layout.post >> $@
	@sed -i "s %root% $(CMSROOT) g" $@

listlong.html: $(OUTS) $(LAYOUT)
	@echo "LISTLNG"
	@cp layout.pre $@
	@cat $(OUTS) >> $@
	@cat layout.post >> $@
	@sed -i "s %root% $(CMSROOT) g" $@

index.json: $(INS)
	@echo "INDEX"
	@./createindex $(INS) > index.json

sitemap.lst: FORCE
	@echo "SITEMAP"
	@echo "$(HTMLS)" | tr ' ' '\n' | sed 's!^!$(CMSURL)!; s!/index.html$$!/!' > $@

watch:
	$(SHELL) -c 'while sleep 1 ; inotifywait -emodify -ecreate -emove $(INPUT) ; true ; do make ; done'

clean:
	@echo "CLEAN"
	@$(RM) $(OUTS) $(SUMS) $(HTMLS) index.json sitemap.lst

FORCE:

