#!/bin/sh
# script/fmt-check: check formatting (read-only). Same scope as
# script/fmt, but fails instead of writing. gofmt and prettier both run
# every time and each reports its own failure, so the output says which
# one failed.
set -eu

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"

main() {
    cd "$ROOT"
    status=0

    # Under set -e a bare assignment would end the script when gofmt
    # fails (a Go file it cannot parse), and prettier would never run.
    if ! files="$(gofmt -s -l .)"; then
        echo "gofmt: failed; see its errors above" >&2
        status=1
    fi
    if [ -n "$files" ]; then
        echo "gofmt: files not formatted:" >&2
        echo "$files" >&2
        status=1
    fi

    # Same image as script/fmt; see there.
    image="$("$SCRIPT_DIR/projectname")-prettier"
    docker build -q --target prettier -t "$image" . >/dev/null
    if ! docker run --rm -v "$ROOT:/src:ro" "$image" \
        prettier --check '**/*.md' --tab-width 4 --prose-wrap always; then
        echo "prettier: Markdown not formatted; run make fmt" >&2
        status=1
    fi

    exit "$status"
}

main "$@"
