#!/usr/bin/bash

ME=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )

echo_to_err() { printf "%s\n" "$*" >&2; }

render_index() {
    if [ ! $# -eq 1 ]; then
        echo_to_err "no directory given"
        exit 1
    fi
    if [ ! -d $1 ]; then
        echo_to_err "no such directory $1"
        exit 1
    fi

    TPL=${ME}/templates/list.tl

    m4 <${TPL} \
        -D _TL_LISTING="$(tree -H 'https://wth.moe/' -I "index.html"  $1 | sed -n '/<\/h1>/,/<hr>/p' | sed '1d;$d' )" \
        -D _TL_CURDIR="${1#./}/"
}


render_recursive() {
    # I doubt whether this is necessary but just to be safe...
    echo "rendering .. $1"
    if [ ! $# -eq 1 ]; then
        return
    fi
    cur=$1
    subs=($(find $1 -mindepth 1 -maxdepth 1 -type d))
    render_index $cur > "${cur}/index.html"
    for sub in "${subs[@]}"; do
        render_recursive $sub
    done
}

if [ ! -f "./scripts/render_site.sh" ]; then
    echo "PLEASE CALL THIS FROM DOC ROOT"
    pwd
fi

render_recursive .
