#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."

# Lists the tracked and the new, not ignored files that match a pattern.
files() {
  git ls-files --cached --others --exclude-standard -- "$@"
}

unformatted=$(golangci-lint fmt --diff)
if [ -n "$unformatted" ]; then
  printf 'golangci-lint fmt: unformatted files:\n%s\n' "$unformatted" >&2
  exit 1
fi

# Comment lines stay within the width of bin/reflow, with tabs as 8 columns.
long=$(files '*.go' | while read -r file; do
  expand -t8 "$file" | awk -v file="$file" 'length > 80 && /^[[:space:]]*\/\//{print file ":" FNR}'
done)
if [ -n "$long" ]; then
  printf 'comment lines over 80 columns, run bin/reflow:\n%s\n' "$long" >&2
  exit 1
fi

golangci-lint run
go test -race ./...
files '*.nix' | xargs nixfmt --check
files '*.rst' | xargs rstfmt --check
files '*.md' | xargs mdformat --check
shellcheck bin/check bin/format bin/reflow .githooks/commit-msg
