#!/bin/sh
render() {
	mkdir -p head/${1%/*} || exit $?
	if test raw/"$1" -nt head.old/"$1".html -o '!' -e head.old/"$1".html; then
		# escaped="head/$(printf '%s\n' "$1" | sed 's/[#%|\\]/\\&/').html"
		# vim </dev/null >/dev/null 2>&1 raw/"$1" +'set modeline' +'e!' +'set nornu number fdm=manual' +TOhtml '+w! '"$escaped" '+qa!'
		# todo: HTML escape title
		{
			printf "%s\n" \
				'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' \
				'<html><head><title>'$1'</title><style>' &&
			pygmentize -f html -S colorful &&
			printf "%s\n" '</style></head>' '<body>' &&
			pygmentize -g -f html -O linenos=table,lineanchors=L,anchorlinenos=True raw/"$1" &&
			printf "%s\n" '</body></html>'
		} > head/.tmp.html &&
		touch -r raw/"$1" head/.tmp.html && \
		mv head/.tmp.html head/"$1".html
	else
		mv head.old/"$1".html head/"$1".html
	fi

}

test -d head.old && rm -rf head.old
test -d head && mv head head.old
while IFS='' read LINE; do
    FILE=${LINE%	*}
    TYPE=${LINE##*	}
    TYPE=${TYPE# }
    MIME=${TYPE%%; *}
    case $MIME in
	(text/*) render "$FILE";;
    esac
done <files.mime
true