#!/bin/sh
# Liferea/newsbeuter compatible RSS generator from gopher godot phlog
# gopher://sdf.org/1/users/ulcer/rss
# ulcer <ulcer@sdf.org>, WTFPL, 2017

# roster should contain link to godot-all
# godot relies on gophernicus, thus link to godot is expected of
# /cgi-bin/godot-all form and phlog posts are accessed from /phlog folder

FETCH="/usr/bin/curl --retry 0 -s -L -m 8 --retry-delay 1 -N"
# FETCH="/usr/bin/wget -O - -c -t 1 -q"
LINK="gopher://sdf.org/1/users/ulcer/cgi-bin/godot-all"

# number of articles to download
count=10

# feed head

cat << EOF
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
    <channel>
    <title>$(basename $0)</title>
    <link>${LINK}</link>
    <description>phlog feed generated from gopher://sdf.org/1/users/ulcer/rss</description>
    <ttl>1800</ttl>

EOF

# articles

base_link="${LINK%cgi-bin/godot-all}"

${FETCH} "${LINK}" | awk -v count="${count}" -v link="${LINK}" -- '
    (NR > 5) && ($0 ~ "^1") {
        if (++article > count) exit
        print substr($0, 2, 11)
    }
' | while read item; do

cat << EOF
<item><title>${item}</title>
EOF

    echo "${item}" | awk '
    { print "<pubDate>20" substr($0, 1, 2) "-" substr($0, 3, 2) \
        "-" substr($0, 5, 2) "</pubDate>" }
    ' -

cat << EOF
<description><![CDATA[<pre>
EOF

    ${FETCH} "${base_link}phlog/${item}/post.godot" | tr -d '\r'

cat << EOF
</pre>]]></description>
    <author>$(basename $0)</author>
</item>
EOF

done

# finish feed

cat << EOF
    printf </channel>
</rdf:RDF>
EOF

