#!/bin/sh -eu

. ./config

title() {
    [ -z "$1" ] && echo "$TITLE" && return
    echo "${1##*/} - $TITLE"
}

mkdir -p "$DIR_BUILD"

echo ">> Building content"

find "$DIR_CONTENT" -type f -name "*.$EXT_WRITINGS" | while read -r file; do
    base=${file#"$DIR_CONTENT"/}
    name=${base%."$EXT_WRITINGS"}

    case "$name" in
        index) name="" ;;
        */index) name=${name%/index} ;;
    esac

    outdir="$DIR_BUILD${name:+/$name}"
    output="$outdir/index.html"
    mkdir -p "$outdir"

    preprocess=cat
    case "$name" in
        *"${DIR_WRITINGS##*/}"*) name="$(sed -n '1s/^; //p' "$file")"
        preprocess=prewriting ;;
    esac
    echo "  $output"
    "$preprocess" < "$file" | echo "<article class=\"writing\">$(markup)</article>" | makepage "$(title "$name")" > "$output"
done

echo ">> Generating writings indexes"

mkdir -p "$DIR_WRITINGS_DST"
echo "  $DIR_WRITINGS_DST/index.html"
makewritindex | makepage "$(title writings)" > "$DIR_WRITINGS_DST/index.html"

for c in $(categories "$DIR_WRITINGS"/*/index."$EXT_WRITINGS"); do
    mkdir -p "$DIR_WRITINGS_DST/$c"
    echo "  $DIR_WRITINGS_DST/$c/index.html"
    makewritindex "$c" | makepage "$(title "#$c")" > "$DIR_WRITINGS_DST/$c/index.html"
done

echo ">> Generating atom feed"
echo "  $WRITINGS_FEED_DST"
makeatom > "$WRITINGS_FEED_DST"

echo ">> Copying static content"
cp -rv "$DIR_STATIC"/* "$DIR_BUILD" | sed -E "s/.*-> '(.*)'/  \1/"

echo ">> Copying content images"
dups=$(find "$DIR_CONTENT" -type f ! -name "*.$EXT_WRITINGS" | sed 's|.*/||' | sort | uniq -d)
if [ -n "$dups" ]; then
    echo "error: duplicate image names in $DIR_CONTENT:" $dups >&2
    exit 1
fi
mkdir -p "$DIR_IMG_DST"
find "$DIR_CONTENT" -type f ! -name "*.$EXT_WRITINGS" -exec cp -v {} "$DIR_IMG_DST" \; | sed -E "s/.*-> '(.*)'/  \1/"

gitrepo() {
    dest="$DIR_BUILD/repos/$2"
    makegitrepo "$1" "$dest" "$3"
    echo "  $dest"
}

echo ">> Generating git repos"
gitrepo ../dedit dedit "a tool for Teeworlds demo file shenanigens"
gitrepo ../site site "my personal website"
gitrepo ../lol-cal lol-cal "terminal lolesports schedule viewer"
gitrepo ../tweed tweed "a Twitch RSS feed generator"

echo ">> Copying licenses"
cp "LICENSES/AGPL-3.0.txt" "$DIR_BUILD/"
cp "LICENSES/CC-BY-SA-4.0.txt" "$DIR_BUILD/"
