#!/bin/bash
set -e

function help-table() {
    CMD_WIDTH=40
    OPT_WIDTH=6
    DESC_WIDTH=42
    COLUMN="| %-${CMD_WIDTH}s | %-${OPT_WIDTH}s | %-${DESC_WIDTH}s |\n"

    printf "$COLUMN" "Command" "Option" "Description"
    echo "|$(printf '%*s' $((CMD_WIDTH + 2)) '' | tr ' ' '-')|$(printf '%*s' $((OPT_WIDTH + 2)) '' | tr ' ' '-')|$(printf '%*s' $((DESC_WIDTH + 2)) '' | tr ' ' '-')|"
    printf "$COLUMN" "all" "" "Run all tasks."
    printf "$COLUMN" "build-11ty" "" "Build the 11ty website."
    printf "$COLUMN" "build-image" "" "Build Docker image."
    printf "$COLUMN" "commit-with-llm" "" "Commit with llm generated commit message."
    printf "$COLUMN" "dev-11ty" "" "Run 11ty server."
    printf "$COLUMN" "help" "[grep]" "Show help for commands."
    printf "$COLUMN" "install" "" "Install node packages."
    printf "$COLUMN" "lint" "" "Lint code with prettier."
    printf "$COLUMN" "run" "" "Run Docker image."
    printf "$COLUMN" "run-tests" "" "Test with shellcheck."
    printf "$COLUMN" "serve-11y" "" "Serve the 11ty output folder."
    printf "$COLUMN" "version" "" "Show version of required tools."
}

function help() {
    echo
    if [ -n "$1" ]; then
        help-table | grep -i "$1" | column -t -s'|'
    else
        echo "task <command> [options]"
        echo
        echo "commands:"
        echo
        help-table
    fi
    echo
}

# Static vars

BUILDX_PLATFORM="linux/amd64"
CONTAINER_REGISTRY="janikvonrotz"
CONTAINER_TAG="taskfile.build:latest"
DOCKERFILE="image/Dockerfile"

# Import commands

if [ -d "$HOME/taskfile.build/bin" ]; then
    for file in "$HOME/taskfile.build/bin/"*; do
        if [ -f "$file" ]; then
            source "$file"
        fi
    done
fi

# Project commands

function run() {
    echo "Open http://localhost:8080 in your browser"
    docker run -p 8080:80 \
        -e GIT_URL="https://git.taskfile.build" \
        -e TASK_COMMANDS="install,build-11ty" \
        -e CADDY_ROOT="_site" \
        janikvonrotz/taskfile.build:latest
}

function install() {
    pnpm install
}

function dev-11ty() {
    pnpm dlx @11ty/eleventy --serve
}

function lint() {
    pnpm exec prettier . --write
}

function run-tests() {
    echo "Test with shellcheck."
    shellcheck task
}

function build-11ty() {
    pnpm dlx @11ty/eleventy
}

function serve-11ty() {
    pnpx serve ./_site
}

function version() {
    echo "eleventy: $(pnpm dlx @11ty/eleventy --version)"
}

if declare -f "$1" > /dev/null; then
    "$1" "${@:2}"
else
    case "$1" in
        all)
            install
            build-11ty
            ;;
        *)
            echo "Unknown command: $1"
            help
            exit 1
            ;;
    esac
fi
