#!/bin/sh -e
# -*- mode: Shell-script; tab-width: 8; fill-column: 70; -*- 

export LC_ALL=C LANGUAGE=C LANG=C

t_dir="$1" && shift
cd "$t_dir"

unset f prev_f list

for f in $(find -H -mindepth 1 -maxdepth 1 -type d ! -name '.' ! -name '..' ! -name '*\.up' | sort); do
    list="$list ${f##*/}"
    rm -rf "$f.prev" "$f.next"

    if [ ! -d "$f.up" ]; then
	mkdir "$f.up"
	cat >"$f.up/index.html"<<EOF
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
	<meta http-equiv="refresh" content="0; URL=../index.html">
    </head>
    <body></body>
</html>
EOF
    fi
    
    if [ -z "$prev_f" ]; then
	ln -s "$f.up" "$f.prev"
	prev_f="$f"
	continue
    fi

    ln -s "$prev_f" "$f.prev"
    ln -s "$f" "$prev_f.next"
    prev_f="$f"
done

if [ -n "$f" -a ! -L "$f.next" ]; then
    ln -s "$f.up" "$f.next"
fi

find -H -mindepth 1 -maxdepth 1 -type l | 
while read f; do
    [ "$f" != "${f%.next}" -o "$f" != "${f%.prev}" ] || continue
    [ ! -d "${f%.next}" -o ! -d "${f%.prev}" ] || continue
    rm -f "$f"
done

find -H -mindepth 1 -maxdepth 1 -type d -name '*\.up' | 
while read f; do
    [ -d "${f%.up}" ] || rm -rf "$f"
done

echo "<html><head>" > "index.html"
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=koi8-r\">" >> "index.html"
echo "<title>Modules List</title></head><body><table>" >> "index.html"
for f in $list; do
    name="$(sed -ne 's,^Title:[[:space:]]*\(.*\)$,\1,p' "$f/docinfo" 2>/dev/null)" || 
	{ echo "ERROR: docinfo not found!">&2; continue; }
    [ -n "$name" ] || name="No name"

    info="$(sed -ne 's,^Abstract:[[:space:]]*\(.*\)$,\1,p' "$f/docinfo" 2>/dev/null)" || 
	{ echo "ERROR: docinfo not found!">&2; continue; }
    [ -n "$info" ] || info="No description"
    
    printf '\t%s\n' "<tr>" >> "index.html"
    printf '\t\t%s\n' "<td style=\"border-bottom: 2px solid #ccccdd;\"><a href=\"$f/index.html\">$name</a></td>" >> "index.html"
    printf '\t\t%s\n' "<td style=\"border-bottom: 2px solid #ccccdd;\">$info</td>" >> "index.html"
    printf '\t%s\n' "</tr>" >> "index.html"
done
echo "</table></body></html>" >> "index.html"
