#!/bin/dash

# exclude mdview's %% directives
grep -v '^%%[[:alpha:]]' - |

lowdown -s -T html - |

gawk \
	-v LOGO="<img src=\"fatdog.png\" height=\"100\">" \
	-v MAP_MD_TO_HTML="./md--html.tsv" \
'#{{{gawk
# Load table that maps .md files to .html files
# It is not a perfect one-to-one mapping.
BEGIN {
	fs = FS
	FS = "\t"
	while(0 < (getline < MAP_MD_TO_HTML))
		md_to_html[$1] = $2
	close(MAP_MD_TO_HTML)
	FS = fs
}
/<\/head>/ && !did_head{
	print "<link rel=\"stylesheet\" type=\"text/css\" href=\"fatdog.css\">"
	print
	did_head++
	next
}
/<body>/ && !did_body {
	print
	print "<div id=\"container\">"
	next
}
/<\/body>/ && !did_body {
	print "</div>"
	print
	did_body++
	next
}
/<h1 / && !did_h1 {
	sub(/>/, ">"LOGO)
	print
	did_h1++
	next
}
# <a> tag: replace .md targets with .html targets
# (lowdown prints an <a> tag on a single line)
/<a[^>]+href="[^"]+\.md"[^>]*>/ {
	n = patsplit($0, tag, /<a[^>]+>/, sep)
	s = sep[0]
	for (i = 1; i <= n; i++) {
		t = tag[i]

		# extract href value
		p = index(t, "href=\"")
		q = index(substr(t, p + 6), "\"")
		href = substr(t, p + 6, q - 1)

		# map .md filename to .html filename
		if (href in md_to_html)
			href = md_to_html[href]

		# rebuild the tag
		tag[i] = substr(t, 1, p + 5) href substr(t, p + q + 5)

		s = s tag[i] sep[i]
	}
	print s
	next
}
{
	print
}
#gawk}}}'

