#!/bin/sh

if [ "$1" = "-h" ];
then
	printf "usage: %s [archivefile]\n" "$(basename "$0")" >&2
	exit 1
fi

baseuri="http://vr-55.net"
blogbase="$HOME/vhosts/vr-55"
archivedir="blog"
blogarchive="$blogbase/$archivedir"
blogindex="$blogbase/README.txt"
atomfile="index.atom"
blogatom="$blogbase/$atomfile"

newpost="$1"
if [ -z "$newpost" ];
then
	newpost="$(ls -t1 "$blogarchive" | grep -v README.txt | head -n 1)"
fi
newpostfile="$blogarchive/$newpost"


exec 1> "$blogatom"
printf "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<feed xmlns=\"http://www.w3.org/2005/Atom\">
	<title>vr-55.net</title>
	<subtitle>Blog</subtitle>
	<id>%s/%s</id>
	<link href=\"%s/%s\" rel=\"self\" />
	<link href=\"%s\" />
	<updated>%s</updated>\n" \
		"$baseuri" "$atomfile" "$baseuri" "$atomfile" \
		"$baseuri" "$(date +%Y-%m-%dT%H:%M:%S%:z)"

for item in $(ls -t1 "$blogarchive" | grep -v README.txt | head -n 10);
do
	title="$(cat "$blogarchive/$item" | head -n 3 | tail -n 1)"
	href="$baseuri/$archivedir/$item"
	updatedstr="$(cat "$blogarchive/$item" | head -n 1 | cut -b 3-)"
	updated="$(date -d "$updatedstr" +%Y-%m-%dT%H:%M:%S%:z)"
	printf "
		<entry>
		<id>%s</id>
		<title>%s</title>
		<link href=\"%s\" />
		<author><name>feedbot</name></author>
		<updated>%s</updated>
		<content><![CDATA[%s]]></content>
		</entry>\n" \
			"$href" \
			"$title" \
			"$href" \
			"$updated" \
			"$(cat "$blogarchive/$item" | sed 's,$,<br />,g')"
done
printf "</feed>\n"

exec 1> "$blogindex"
printf "We were here. See the archive.\n\n\n"
cat $newpostfile

