#!/bin/sh

# makros binary
MAKROS=makros

if ! find $MAKROS 2>/dev/null >/dev/null; then
    echo "couldn't find the makros binary"
    exit 1
fi

# Strip the CSS file of whitespace to reduce file size
echo "Generating CSS"
$MAKROS resources/style-formatted.css | tr -d " \t\n\r" > resources/style.css

# Generate HTML pages from Writan sources
echo "Generating pages"
for file in site-src/*; do
    bn=$(basename $file .wtn)
    echo "  $file -> site/$bn.html"
    # if the file has macros, expand them
    if grep "#makro" $file >/dev/null; then
        tmp=$(mktemp)
        $MAKROS $file > $tmp
        ./format $tmp site/$bn.html
        rm $tmp
    else
        ./format $file site/$bn.html
    fi
done

# Generate the site index
indexfile=site/site-index.html
cat resources/header.html > $indexfile
echo "Generating full site index"
echo "<h1>Site index</h1>" >> $indexfile
for file in site/*; do
    bn=$(basename $file .html)
    echo "<p><a href=\"$bn.html\">$bn</a>" >> $indexfile
done
cat resources/footer.html >> $indexfile

# Generate list of last changed files
lastchanged=site/last-changed.html
cat resources/header.html > $lastchanged
echo "Generating last changed page"
echo "<h1>Last changed pages</h1>" >> $lastchanged
echo "<p>Times are relative to the date the site was last generated, $(date -I)." >> $lastchanged
sorted=$(mktemp)
for file in site-src/*; do
    printf "%s %s\n" $(git log -n 1 --pretty=format:%ct $file) $file
done | sort -r > $sorted

while read line; do
    file=$(echo $line | awk '{print $2}')
    relative=$(git log -n 1 --pretty=format:%cr $file)
    # instead of showing "x hours/minutes/seconds ago", show "today"
    if echo $relative | grep "hour" >/dev/null \
       || echo $relative | grep "minute" >/dev/null \
       || echo $relative | grep "second" >/dev/null; then
        relative="today"
    fi
    bn=$(basename $file .wtn)
    echo "<p><a href=\"$bn.html\">$bn</a> - $relative"
done < $sorted >> $lastchanged

rm $sorted
cat resources/footer.html >> $lastchanged
