#!/bin/sh

set -e

base="$(cd "$(dirname "$0")"; pwd)" # We are here.
domain="synthe.ist"                 # Prepended to all URLs.
index_page="$base/log/index.gmi"    # Log index page.
front_page="$base/index.gmi"        # Site front page.

# Files containing '^* 20' (timestamp) are log entries.
index="$(grep -EH '^\*\ 20' log/*.gmi | sed 's/\*\ //'| sort -r -t: -k2)"

tmpindex="$(mktemp /tmp/$domain.XXXXXXXXXX)" || exit 1

# Create tab separated file with URL\tTITLE\tDATE.
for g in $index; do
    file="${g%%:*}"
    date="${g##*:}"
    printf 'gemini://%s/%s\t%s\t%s\n' \
        "$domain" \
        "$file" \
        "$(head -n3 "$file" | grep -E '^#\ ' | sed 's/^#\ //')" \
        "$date" >> "$tmpindex"
done

# Create log index page.
rm -f "${index_page:?}"
printf "# Syntheist's Gemlog\n\n" > "$index_page"

# Create gemfeed file.
while read line; do
    url="$(echo "$line" | cut -f1)"
    title="$(echo "$line" | cut -f2)"
    date="$(echo "$line" | cut -f3)"
    printf '=> %s %s %s\n' "$url" "$date" "$title" >> "$index_page"
done < "$tmpindex"

printf "\nLast updated: %s\n" "$(date +%Y-%m-%d)" >> "$index_page"

# Edit the front page.
tmp_front_page="$(mktemp $base/index.gmi.XXXXXXXXXX)" || exit 1
sed -e '1,/^##\ Latest/!d' index.gmi >> "$tmp_front_page"
printf '\n' >> "$tmp_front_page"
grep -E '^=>\ ' "$index_page" | head -n5 >> "$tmp_front_page"
printf '\n' >> "$tmp_front_page"
sed -n  '/^##\ About/,$p' index.gmi >> "$tmp_front_page"
mv "$tmp_front_page" "$front_page" && chmod 0644 "$front_page"

rm -f "$tmp_front_page"

printf 'All files generated, git status:\n\n' && git status

rm -f "$tmpindex"