#!/bin/sh

. ./config

DOMAIN="jhhm.no"
DIR="$DIR_CONTENT/writings"
FEED_ID="https://jhhm.no/writings/"
FEED_TITLE="JHHM's Writings"
LINK="https://jhhm.no/writings/"
FEED_LINK="https://jhhm.no/writings/atom.xml"

now="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"

echo '<?xml version="1.0" encoding="utf-8"?>'
echo '<feed xmlns="http://www.w3.org/2005/Atom">'
echo "<title>$FEED_TITLE</title>"
echo "<author><name>JHHM</name></author>"
echo "<link rel=\"self\" type=\"application/atom+xml\" href=\"$FEED_LINK\"/>"
echo "<link href=\"$LINK\"/>"
echo "<id>$FEED_ID</id>"
echo "<updated>$now</updated>"

tmp="$(mktemp)"

for file in "$DIR"/*/index.md; do
    [ -f "$file" ] || continue

    date_line=$(sed -n '3p' "$file" | sed 's/^; *//')
    iso_date=$(date -u -d "$date_line" +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null)

    [ -z "$iso_date" ] && iso_date="$now"

    printf "%s|%s\n" "$iso_date" "$file" >> "$tmp"
done

sort -r "$tmp" | while IFS="|" read -r iso_date file; do
    title="$(sed -n '1p' "$file" | sed 's/^; *//')"
    content="$(markup < "$file")"

    base="$(basename "$(dirname "$file")")"
    url="https://$DOMAIN/writings/$base"

    echo "<entry>"
    echo "<title>$title</title>"
    echo "<id>$url</id>"
    echo "<link rel=\"alternate\" href=\"$url\"/>"
    echo "<published>$iso_date</published>"
    echo "<updated>$iso_date</updated>"
    echo "<content type=\"html\"><![CDATA[$content]]></content>"
    echo "</entry>"
done

rm -f "$tmp"

echo '</feed>'
