#!/bin/sh
# script/fmt: format all files (writes). Go with gofmt and goimports on
# the host, markdown with prettier in the Dockerfile's fmt stage.
#
# goimports runs with `go run` at a pinned commit, never from PATH, so
# every machine formats with the same version and nothing installs it.
#
# The markdown pass is a `docker build --output type=local` rather than a
# `docker run -v`, so it needs no bind mount and behaves the same against
# a remote daemon; the formatted documents come back out of the build and
# are copied over the tree here. --output writes files and makes no
# image, so there is nothing to tag.
set -eu

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

# goimports v0.42.0, 2026-08-07. Must match script/fmt-check.
GOIMPORTS_REF="golang.org/x/tools/cmd/goimports@009367f5c17a8d4c45a961a3a509277190a9a6f0"

die() {
    echo "script/fmt: $*" >&2
    exit 1
}

main() {
    cd "$ROOT"
    gofmt -s -w .
    go run "$GOIMPORTS_REF" -w .

    tmp="$(mktemp -d "${TMPDIR:-/tmp}/dnswatcher-fmt.XXXXXX")"
    trap 'rm -rf "$tmp"' EXIT INT TERM

    docker build --no-cache \
        --target fmt-out \
        --output "type=local,dest=$tmp/out" .

    # An empty export means prettier was handed nothing, which must not
    # read as "already formatted".
    (cd "$tmp/out" && find . -type f -name '*.md') |
        sed 's|^\./||' | LC_ALL=C sort >"$tmp/files"

    [ -s "$tmp/files" ] ||
        die "the formatting build produced no markdown; the build" \
            "context reached prettier empty"

    # Copied only where the bytes differ, so an already-formatted tree
    # keeps its timestamps and says nothing.
    while IFS= read -r f; do
        [ -n "$f" ] || continue
        if [ -f "$f" ] && cmp -s "$tmp/out/$f" "$f"; then
            continue
        fi
        cp "$tmp/out/$f" "$f"
        echo "prettier: reformatted $f"
    done <"$tmp/files"
}

main "$@"
