#!/bin/bash
# Generates/Updates Gopher maps for new Phlog entries.
# Specifically, replaces gophermap in current ("/phlog")
# directory, and adds latest post name to home gophermap in "../".
#
# Use -wraplatest to automatically wrap text in the latest file.
# Generates RSS 2.0 feed if a rsshead file is in the current
# directory (should contain channel headers except for pubDate).
#
# Version 2 (RSS feed generation added)
# By The Free Thinker ( gopher://aussies.space/1/%7efreet/ ), 2022.

##### Config. Options

#Line wrapping width:
WRAPWIDTH=68

#location of home gophermap (without trailing "/"):
HOMEGOPHERMAPDIR=".."

#Line to replace containing name of latest post in home gophermap:
REPLACEHOMEMAPLINE=14
#Set to 0 to disable modifying home gophermap

#Text preceeding post filename on that line:
LATESTPOSTPREFIX=" - Latest post:"

#Maximum number of entries to include in RSS feed
RSSMAX=3

#Base URL for RSS feed item links:
RSSROOT="gopher://aussies.space/0/~freet/phlog/"

#File Name of RSS feed:
RSSNAME=freet.rss

##### End of Config.

lineno=1
firstline=0
rssgen=0
title=
rsscount=0

addposttohomemap ()
{
 if ((REPLACEHOMEMAPLINE!=0)); then
  cat ../gophermap | while IFS= read -r line; do
   if((lineno==REPLACEHOMEMAPLINE)); then
    echo -e "$LATESTPOSTPREFIX $i" >> "$HOMEGOPHERMAPDIR/gophermap.new"
   else
     echo "$line" >> "$HOMEGOPHERMAPDIR/gophermap.new"
   fi
   ((lineno++))
  done
  mv "$HOMEGOPHERMAPDIR/gophermap.new" "$HOMEGOPHERMAPDIR/gophermap"
  chmod u+rw,go-wx,go+r "$HOMEGOPHERMAPDIR/gophermap"
 fi
}

cp phloghead gophermap.new

if [ -f rsshead ]; then
 rssgen=1
 cp rsshead $RSSNAME.new
 echo "    <pubDate>`date -R`</pubDate>" >> $RSSNAME.new
fi

for i in `ls -r *.txt`
do
 echo -e "0$i\t" >> gophermap.new
 if ((firstline==0)); then
  addposttohomemap
  if [ "$1" = "-wraplatest" ]; then
   fold -s -w $WRAPWIDTH "$i" > "$i,f"
   mv "$i,f" "$i"
  fi
  firstline=1
 fi

 if ((rssgen)) && ((rsscount < RSSMAX)); then
  ((rsscount++))
  title="${i#????-??-??}"
  title="`echo \"${title%.txt}\" | tr _ ' '`"
  echo -e "    <item>\n" \
  "    <title>$title</title>\n" \
  "    <link>${RSSROOT}${i}</link>\n" \
  "    <description>\n" \
  "`sed -e 's/&/\&amp;/g' -e 's/>/\&amp;gt;/g' -e 's/</\&amp;lt;/g' \"$i\"`\n" \
  "    </description>\n" \
  "   </item>" >> $RSSNAME.new
 fi
done

if ((rssgen)); then
 echo -e "</channel>\n</rss>" >> $RSSNAME.new
 mv $RSSNAME.new $RSSNAME
 chmod u+rw,go-wx,go+r $RSSNAME
fi

mv gophermap.new gophermap
chmod u+rw,go-wx,go+r gophermap