#!/bin/sh
# gophatom.sh -- Atom feeds for gopher
set -e

REPO=$(dirname "$(dirname "$0")")

if [ -z "$1" ] || [ ! -d "$REPO/$1" ]; then
   echo "usage: gophatom.sh phlog|yis" 1>&2
   exit 1
fi

dir=$1
case "$dir" in
   phlog)
       title="Alex Karle's phlog"
       prefix=""
       ;;
   yis)
       title="This Year in Songs"
       prefix="Song of the Week: "
       ;;
esac

cat <<HEADER
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 <title>$title</title>
 <id>gopher://alexkarle.com/1/$dir</id>
 <link rel="self" type="application/atom+xml" href="gopher://alexkarle.com/0/$dir/atom.xml"/>
 <link rel="alternate" href="gopher://alexkarle.com/1/$dir"/>
 <author>
   <name>Alex Karle</name>
 </author>
HEADER

IFS='
'
for p in $(grep '^\[0|\[' "$REPO/$dir/index.gph"); do
   if [ -z "$printed_update" ]; then
       printed_update=1
       last=$(git log --pretty="%aI" -- $dir/*.txt | head -n 1)
       printf "  %s\n" "<updated>${last}</updated>"
   fi
   stripped=${p#\[0\|\[}
   stripped=${stripped#*\] }
   title=${stripped%%\|*}
   stripped=${stripped#*\|}
   file=$(basename "${stripped%%\|*}")
   updated=$(git log --pretty="%aI" -- $dir/$file | head -n 1)
   published=$(git log --pretty="%aI" -- $dir/$file | tail -n 1)
   cat <<ENTRY
 <entry>
   <title>${prefix}${title}</title>
   <link rel="alternate" href="gopher://alexkarle.com/0/$dir/${file}"/>
   <id>gopher://alexkarle.com/0/$dir/${file}</id>
   <updated>${updated}</updated>
   <published>${published}</published>
   <content type="text">
   <![CDATA[
ENTRY
   cat "$REPO/$dir/${file}"
   cat <<EOENTRY
   ]]>
   </content>
 </entry>
EOENTRY
done
printf "</feed>\n"