#!/bin/sh

base_url='https://blog.ce9e.org/'

getyml() {
	grep "^$1:" "$2" | head -n 1 | sed "s/$1"': //;s/^"\(.*\)"$/\1/'
}

escape() {
	sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g'
}

echo '<?xml version="1.0" encoding="utf-8"?>'
echo '<feed xmlns="http://www.w3.org/2005/Atom">'
echo '	<author><name>Tobias Bengfort</name></author>'
echo '	<title>Ξ</title>'
echo "	<id>$base_url</id>"
echo "	<updated>$(date '+%Y-%m-%d')T00:00:00Z</updated>"
echo "	<link href=\"$base_url\" rel=\"alternate\" />"
if [ "$1" = '-a' ]; then
	echo "	<link href=\"${base_url}feed.xml\" rel=\"current\" />"
	echo "	<link href=\"${base_url}feed-archive.xml\" rel=\"self\" />"
	select='tail -n +11'
else
	echo "	<link href=\"${base_url}feed.xml\" rel=\"self\" />"
	echo "	<link href=\"${base_url}feed-archive.xml\" rel=\"prev-archive\" />"
	select='head -n 10'
fi

ls _content/posts | tac | $select | while read -r l; do
	yml="_content/posts/$l/index.md"
	if grep -q 'draft: true' "$yml"; then
		continue
	fi

	html="_content/posts/$l/index.html"
	url="${base_url}posts/$l/"

	echo '	<entry>'
	echo "		<title>$(getyml 'title' "$yml" | escape)</title>"
	echo "		<link href=\"$url\" />"
	echo "		<id>$url</id>"
	echo "		<updated>$(getyml 'date' "$yml" | escape)T00:00:00Z</updated>"
	echo "		<summary>$(getyml 'description' "$yml" | escape)</summary>"
	echo '		<content type="html">'
	cat "$html" | escape
	echo '		</content>'
	echo '	</entry>'
done

echo '</feed>'
