#!/bin/bash -e
# PPages static site generator - requiring: fd-find, rsync
#  * Template files look like    $type.template.html
#  * Markdown files look like    $name.$type.md
#             Using 'bang' template v
#    e.g.       foo/_bar/baz/whizz.bang.md -> www/foo/baz/whizz.html
#                   ^             ^            ^
#        _* dirs are gone    suffix gone   output dir added
#
#  * The contents of the _static/ directory are copied to www/
#  * Set $HOST=me@server.xyz:/srv/www to rsync to that location
#  * Pass an argument to only build paths matching that regex
#
WWW="www"

pp () {
    local p
    while read -r L;do case $L in !!*)p="$p"$'\n'"${L#!!}";;*)eval "$p";p="";echo "$L";;esac;done;eval "$p"
}

get_output () {
    sed "s!^!$WWW/!;s!/_[^/]*/!/!g;s!\.[^./]*\.[^./]*\$!.html!" <<< "$1"
}

build () {
    for template in $(fd . -e template.html); do
        type="$(sed 's!^.*/!!;s!\..*$!!' <<< "$template")"
        echo "Template '$type':" >&2
        for page in $(fd -p "${1:-.}" -e "$type.md"); do
            echo " - processing $page" >&2
            mkdir -p "$(dirname "$(get_output "$page")")"
            PAGE="$page" pp < "$template" > "$(get_output "$page")" &
        done
    done
}

[[ $HOST ]] && rm -rf "$WWW"
build "$1"
rsync -aOci _static/ "$WWW"/ | sed 's!^! - static !' >&2
wait
echo "rsync -aOci $WWW/ \$HOST" | if [[ $HOST ]]; then bash -; else cat; fi

