#!/bin/sh
# script/prettier: run prettier over this repo with the repo's own
# .prettierrc. Helper, not an entrypoint: script/fmt and
# script/fmt-check call it.
#
# Prettier from PATH if it is there, otherwise a hash-pinned node image
# via docker, so a checkout with neither node nor a global prettier
# still formats identically. If neither is available the caller is told
# and the markdown pass is skipped rather than silently passing — a
# formatter that is not present cannot certify formatting.
#
# Exit status: prettier's own, 2 when it was skipped for lack of a
# runner. script/fmt-check treats 2 as a warning, not a failure, so
# that `make check` still works on a machine without docker.
set -eu

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

# node:24-alpine, 2026-08-22. Bumping the pin is a deliberate edit.
NODE_IMAGE="node:24-alpine@sha256:d32cdf619f63fe0471182d08996dd516c6275bb5fd31ae06e55a570bd9e1ad43"

# Pinned exactly: prettier's default formatting changes between minor
# releases, so an unpinned version turns fmt-check into a coin flip.
PRETTIER_VERSION="3.9.6"

main() {
    cd "$ROOT"

    if command -v prettier >/dev/null 2>&1; then
        prettier "$@"
        return $?
    fi

    if command -v docker >/dev/null 2>&1; then
        # --user keeps written files owned by the invoking user rather
        # than root; the container only ever touches the bind mount.
        docker run --rm \
            --user "$(id -u):$(id -g)" \
            -v "$ROOT:/work" \
            -w /work \
            "$NODE_IMAGE" \
            npx --yes "prettier@$PRETTIER_VERSION" "$@"
        return $?
    fi

    echo "script/prettier: neither prettier nor docker found;" >&2
    echo "script/prettier: skipping markdown/CSS/JS formatting." >&2

    return 2
}

main "$@"
