#!/bin/sh
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)

validate_task() {
    for argument do
        case "$argument" in
            --plan) continue ;;
            help|-h|--help|-[Hh][Ee][Ll][Pp]) cat "$root/go/build/help.txt"; exit 0 ;;
        esac
        while IFS= read -r task || [ -n "$task" ]; do
            [ "$argument" != "$task" ] || return 0
        done < "$root/go/build/tasks.txt"
        printf 'bd2w: unknown task "%s"; use --help for available commands\n' "$argument" >&2
        return 1
    done
}
if [ "$#" -eq 0 ]; then
    cat "$root/go/build/help.txt"
    exit 0
fi
validate_task "$@"

tool_dir="$root/.build/tools"
tool="$tool_dir/bd2w"

tool_is_current() {
    [ -f "$tool" ] || return 1
    newer_sources=$(find "$root/go/build" "$root/go/internal" "$root/go/go.mod" "$root/go/go.sum" -type f -newer "$tool" -print) || {
        printf 'bd2w: cannot check build tool source timestamps.\n' >&2
        exit 1
    }
    [ -z "$newer_sources" ]
}

if ! tool_is_current; then
    mkdir -p "$tool_dir"
    lock="$tool_dir/.bootstrap.lock"
    attempts=0
    while ! tool_is_current; do
        if mkdir "$lock" 2>/dev/null; then
            temporary="$tool_dir/.bd2w-$$"
            trap 'rm -f "$temporary"; rmdir "$lock" 2>/dev/null || true' 0
            trap 'exit 130' INT TERM
            if ! tool_is_current; then
                printf 'bd2w: compiling the build tool...\n'
                (
                    cd "$root/go"
                    GOCACHE="$root/go/.cache/go-build"
                    GOOS=$(go env GOHOSTOS)
                    GOARCH=$(go env GOHOSTARCH)
                    CGO_ENABLED=0
                    export GOCACHE GOOS GOARCH CGO_ENABLED
                    go build -buildvcs=false -trimpath -o "$temporary" ./build
                )
                mv "$temporary" "$tool"
            fi
            rmdir "$lock"
            trap - 0 INT TERM
            break
        fi
        attempts=$((attempts + 1))
        if [ "$attempts" -ge 120 ]; then
            printf 'bd2w: bootstrap lock still held at %s; check the first launcher.\n' "$lock" >&2
            exit 1
        fi
        sleep 1
    done
fi
exec "$tool" "$@"
