#!/bin/sh

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

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

escape() {
	sed 's/\\/\\\\\\\\/g;s/"/\\"/g'
}

value() {
	printf '%.*s"%s": "%s",\n' "$1" '		' "$2" "$3"
}

echo '{'
value 1 'version' "https://jsonfeed.org/version/1.1"
echo '	"authors": [{"name": "Tobias Bengfort"}],'
value 1 'title' 'Ξ'
value 1 'home_page_url' "$base_url"
if [ "$1" = '-a' ]; then
	value 1 'feed_url' "${base_url}feed-archive.json"
	select='tail -n +11'
else
	value 1 'feed_url' "${base_url}feed.json"
	value 1 'next_url' "${base_url}feed-archive.json"
	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

	if [ -z "$loop" ]; then
		echo '	"items": [{'
		loop=1
	else
		echo '	}, {'
	fi

	html="_content/posts/$l/index.html"
	url="${base_url}posts/$l/"
	value 2 'title' "$(getyml 'title' "$yml" | escape)"
	value 2 'url' "$url"
	value 2 'id' "$url"
	value 2 'summary' "$(getyml 'description' "$yml" | escape)"
	value 2 'date_published' "$(getyml 'date' "$yml" | escape)"
	echo "		\"content_html\": \"$(cat "$html" | escape | sed 's/$/\\\\n/' | tr -d '\n')\""
done
echo '	}]'

echo '}'
