#!/bin/bash

label_dir="/var/www/komarix.org/paul_blogger/labels"

echo "Content-type: text/html"
echo
echo "<html>"
echo "<!--START_LABEL_OUTPUT-->"

# I use env vars to communicate with the while-loop below, because
# the while-loop is excecuted in a sub-shell (due to the pipe).
export LABEL_SEPARATOR=", "

# Controls use of label-separator.
export FIRST_ITEM=1

# Used for line-breaking.
export ACCUMULATOR=""
export MAX_CHARS=35
export NUM_CHARS=0

# We cannot return values in the accumulator, and the while-loop
# does not know which item is the last in the list.  Therefore we
# include a marker for the end of the list.
export ENDOFLIST="ENDOFLIST_MARKER"


(ls ${label_dir}/*.html; echo $ENDOFLIST) \
| while read label_file; do
    if [ "$label_file" = "$ENDOFLIST" ]; then
	echo "${ACCUMULATOR}<br />"
	break;
    fi

    bname=$(basename "$label_file" .html)
    if [ -z "$bname" ]; then continue; fi

    escbname=$(echo "$bname" | sed 's: :%20:g')
    lname="http://notes.komarix.org/labels/${escbname}.html"

    # Number of posts for this label.
    count=$(grep '<!-- Begin .post -->' "$label_file" | wc -l)

    # Create the link text.
    link_text="${bname} ($count)"

    # Create the html markup.
    markup="<a href='${lname}'>${link_text}</a>"

    # Line breaking.
    textlen=$(echo "$link_text" | wc -c)
    newlen=$(($NUM_CHARS + $textlen))
    if [ "$newlen" -le "$MAX_CHARS" ]; then
        # There's room on this line.

        # Add a preceding comma if we are not the first item on this line.
	if [ "$FIRST_ITEM" -eq 0 ]; then
	    markup="${LABEL_SEPARATOR}${markup}"
	fi
	export FIRST_ITEM=0
	export ACCUMULATOR="${ACCUMULATOR}${markup}"
	export NUM_CHARS="$newlen"
    else
        # Not enough room on this line.
	echo "${ACCUMULATOR}<br />"
	export ACCUMULATOR="$markup"
	export NUM_CHARS="$textlen"
    fi
done

# Dump final accumulator string.
if [ -n "$ACCUMULATOR" ]; then
      echo "${ACCUMULATOR}<br />"    
fi

echo "<!--STOP_LABEL_OUTPUT-->"
echo "</html>"