#!/usr/bin/env bash
# format-all: the formatting check of the nix flake, runnable locally, and the fix for it.
#
# Usage: tools/format-all [--check | --apply] [--root DIR]
#   --check  (default) fails if any file is not formatted; prints the diff
#   --apply  formats the files in place (do it LAST on a candidate: it touches many files)
#   --root   the repository (default: the one this script is in; the nix check passes its source)
#
# Every .rs file of the repository is formatted with the root rustfmt.toml, one file at a time with
# skip_children (the entry files of a crate name modules of other platforms, and a cfg_select! arm that is
# not compiled is not a module rustfmt can follow), by the nightly rustfmt and edition 2024, the edition of
# every manifest.
# The nightly rustfmt is $RUSTFMT if set, else the one of the dev shell of the root flake (`nix develop`),
# which is the nightly of the pinned rust-overlay that the nix check uses (another nightly may format
# differently and may not follow cfg_select), else a nightly `rustfmt` on PATH.
set -uo pipefail

orig_args=("$@")
mode=check
root=$(cd "$(dirname "$0")/.." && pwd)
while [ $# -gt 0 ]; do
  case $1 in
    --check) mode=check ;;
    --apply) mode=apply ;;
    --root) root=$2; shift ;;
    -h | --help) sed -n 2,16p "$0"; exit 0 ;;
    *) echo "format-all: unknown argument $1" >&2; exit 2 ;;
  esac
  shift
done
root=$(cd "$root" && pwd)

if [ -z "${RUSTFMT:-}" ]; then
  if [ -n "${FORMAT_ALL_IN_SHELL:-}" ]; then
    RUSTFMT=rustfmt
  elif command -v nix >/dev/null; then
    FORMAT_ALL_IN_SHELL=1 exec nix develop "$root" --command "$0" "${orig_args[@]}" --root "$root"
  elif rustfmt --version 2>/dev/null | grep -q nightly; then
    RUSTFMT=rustfmt
  else
    echo "format-all: no nightly rustfmt (set RUSTFMT)" >&2; exit 2
  fi
fi
export RUSTFMT
cd "$root" || exit 2

flag=--check
[ "$mode" = apply ] && flag=

echo "format-all: all"
mapfile -t files < <(find . -name '*.rs' -not -path '*/target/*' -not -path './.git/*' -not -path './.jj/*' | sed 's|^\./||' | sort)
[ ${#files[@]} -eq 0 ] && { echo "format-all: no files" >&2; exit 1; }
"$RUSTFMT" --edition 2024 --config-path rustfmt.toml --config skip_children=true $flag "${files[@]}"
