#! /usr/bin/env nix-shell
#! nix-shell --pure -i bash
#! nix-shell --pure -p nodejs_24 bash harfbuzz soupault woff2 jotdown python3 recode perl538Packages.LaTeXML minify

if ! [[ -d pgvv/ ]]; then
    python3 -m venv pgvv
    source ./pgvv/bin/activate
    python3 -m pip install --upgrade pip
    pip install --upgrade pygments
    deactivate
fi

function soup_config {
    rm soupault.toml
    cp ../soupault.toml soupault.toml
    cat soupault.frag*.toml >>soupault.toml
}

source ./pgvv/bin/activate

if ! [[ -f lexers.out ]] || [[ "$(head -1 lexers.out)" != "$(pygmentize -V)" ]]; then
    pygmentize -L lexer >lexers.out
    echo "Created pygments lexer cache at lexers.out"
fi

find acl.cool/site/ ytheleus.org/site/ -type f \( -name '*.dj' -o -name '*.html' \) -exec cat {} + >all_chars.txt
cat common_chars.txt >>all_chars.txt

for font in fonts/LiterataTT/LiterataTT-Subhead{Regular,Italic,Semibold,SemiboldItalic,Bold,BoldItalic}.woff2 \
    fonts/JuliaMono/*{-Light,-Regular,-SemiBold}{,Italic}.woff2; do
    woff2_decompress "$font"
    ttf_font="${font%.woff2}.ttf"

    subset_ttf="${ttf_font%.ttf}-Subset.ttf"
    hb-subset "$ttf_font" \
        --output-file="$subset_ttf" \
        --text-file=all_chars.txt \
        --layout-features='*' \
        --passthrough-tables

    woff2_compress "$subset_ttf"

    rm "$subset_ttf" "$ttf_font"
done

for font in \
    fonts/Alegreya/static/Alegreya-{Regular,Italic,Bold,BoldItalic}.ttf \
    fonts/Alegreya_Sans/AlegreyaSans-{Regular,Italic,Bold,BoldItalic}.ttf; do
    subset_ttf="${font%.ttf}-Subset.ttf"
    hb-subset "$font" \
        --output-file="$subset_ttf" \
        --text-file=all_chars.txt \
        --layout-features='*' \
        --passthrough-tables \
        --unicodes+="0x0435" # this is the cyrillic e. For some reason, alegreya's ff calt breaks without it

    woff2_compress "$subset_ttf"

    rm "$subset_ttf"
done

rm css/code.css
pygmentize -f html -S algol_nu | grep -v 'line-height' >css/code.css

for site in acl.cool ytheleus.org; do
    pushd "$site"
    soup_config
    rm -rf serve/
    soupault
    pushd serve/
    find -type f -name '*.html' -o -name '*.css' -o -name '*.svg' | xargs -0 -d\\n -I{} minify -o {} {}
    popd
    NEXT_DIR="serve_$(date +%s)"
    CUR_DIR=$(find . -maxdepth 1 -type d -regex './serve_[0-9]+')
    echo "$PREV_DIR"
    cp -a serve "$NEXT_DIR"
    ln -sfn "$NEXT_DIR" serve_
    for d in $CUR_DIR; do
        rm -r $d
    done
    popd
done

deactivate
