#!/usr/bin/env bash

HEADING='Posts'
TITLE="Andrea's blog"
BASENAME=${BASENAME-blog}
BASE_URL=${BASE_URL-https://sqt.wtf}
DESCRIPTION="Andrea's personal blog."
N_DESC_CHARS=500

articles=( $BASENAME/*.md )

cat <<HDR
<div class="inner">
	<h1>$HEADING</h1>
	<dl> <!-- no longer me -->
HDR

cat > blog/feed.xml <<RSSHDR
<rss version="2.0">
	<channel>
		<title>$TITLE</title>
		<link>$BASE_URL/$BASENAME.html</link>
		<description>$DESCRIPTION</description>
RSSHDR

for ((i=${#articles[@]}-1; i>=0; i--)); do
	post_md=${articles[$i]}
	date=$(grep -o '[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}' <<<"$post_md")
	title=$(grep -m 1 '^#\s\+' "$post_md" | sed 's/^#\s\+//')
	html=$(sed 's/\.md$/.html/' <<<"$post_md")
	rss_desc=$(grep -v '^\s*$' "$post_md" | grep -v '^\s*\*by' | grep -v '^#' | grep -v '^\s*!\[' | grep -v '<.\+>'| head -c $N_DESC_CHARS)'...'

	cat <<INNIE
		<dt>$date</dt>
			<dd><a href="$html">$title</a></dd>
INNIE

	cat >> $BASENAME/feed.xml <<RSSINNIE
		<item>
			<title>$title</title>
			<link>$BASE_URL/~targetdisk/$html</link>
			<description>$rss_desc</description>
      <pubDate>$(date -d "$date" '+%a, %d %b %Y %H:%M:%S %Z')</pubDate>
		</item>
RSSINNIE
done

cat <<FTR # Short for Fetterman
	</dl> <!-- no longer on the dl -->
	<p><a href="/~targetdisk/$BASENAME/feed.xml">RSS</a></p>
</div>
FTR

#
#  <h2>Other People's Posts</h2>
#  {{range .Articles}}
#  <div>
#    <h4 class="title" dir="auto">
#      <a href="{{.Link}}" target="_blank" rel="noopener">{{.Title}}</a>
#    </h4>
#    <p class="summary" dir="auto">{{.Summary}}</p>
#    <small class="source">
#      via <a href="{{.SourceLink}}">{{.SourceTitle}}</a>
#    </small>
#    <small class="date">{{.Date | datef "January 2, 2006"}}</small>
#  </div>
#  {{end}}
#
#  </br></br>
#  <small>
#    <p>
#      Generated by
#      <a href="https://git.sr.ht/~sircmpwn/openring">openring</a>
#    </p>
#  </small>
#</div>
#
#<style>
#.webring .title {
#  margin: 0;
#}
#.webring .summary {
#  font-size: 0.8rem;
#  flex: 1 1 0;
#}
#</style>
#FTR

cat >> $BASENAME/feed.xml <<RSSFTR
	</channel>
</rss>
RSSFTR
