#!/bin/bash
set -e

if [[ -a ".env" ]]; then
    source .env
fi

function help() {
    echo
    echo "task <command> [options]"
    echo
    echo "commands:"
    echo

    # Define column widths
    cmd_width=10
    opt_width=6
    desc_width=40

    # Print table header
    printf "| %-${cmd_width}s | %-${opt_width}s | %-${desc_width}s |\n" "Command" "Option" "Description"
    echo "|$(printf '%*s' $((cmd_width + 2)) '' | tr ' ' '-')|$(printf '%*s' $((opt_width + 2)) '' | tr ' ' '-')|$(printf '%*s' $((desc_width + 2)) '' | tr ' ' '-')|"

    # Print table rows
    printf "| %-${cmd_width}s | %-${opt_width}s | %-${desc_width}s |\n" "all" "" "Run all tasks."
    printf "| %-${cmd_width}s | %-${opt_width}s | %-${desc_width}s |\n" "install" "" "Setup the local environment."
    printf "| %-${cmd_width}s | %-${opt_width}s | %-${desc_width}s |\n" "lint" "" "Run pre-commit and update index.html."
    printf "| %-${cmd_width}s | %-${opt_width}s | %-${desc_width}s |\n" "source" "" "Source the Python virtual env."
    printf "| %-${cmd_width}s | %-${opt_width}s | %-${desc_width}s |\n" "version" "" "Show version of required tools."

    echo
}

function version() {
    uv --version
}

function install() {
    echo "Setup venv and install python dependencies"
    uv venv env
    source env/bin/activate
    uv pip install pre-commit rst2html5
}

function lint() {
    source env/bin/activate

    echo "Run pre-commit"
    pre-commit run --all-files # --show-diff-on-failure --color=always

    echo "Update index.html for all modules"
    for MODULE in ./*; do
        if [ -f "$MODULE/README.rst" ]; then
            cd "$MODULE" || exit
            rst2html5 README.rst static/description/index.html
            cd .. || exit
        fi
    done

}

case "$1" in
    help)
        help
        ;;
    all)
        install
        lint
        ;;
    install)
        install
        ;;
    lint)
        lint
        ;;
    source)
        source env/bin/activate
        ;;
    version)
        version
        ;;
    *)
        help
        exit 1;
esac
