#!/usr/bin/env bash
# Shared companions: make/rust-format.mk scripts/ci/prepare-script-fixture.sh scripts/ci/check-pipe-jobserver.pl scripts/ci/fixture-lifecycle.sh
set -euo pipefail
unset MAKEFLAGS MFLAGS MAKEOVERRIDES GNUMAKEFLAGS MAKEFILES
root="${BASH_SOURCE[0]}"
[[ "$root" == /* ]] || root="$PWD/$root"
root="$(cd -P "${root%/*}/../.." && printf '%s/.' "$PWD")"
root="${root%/.}"
# shellcheck source=scripts/ci/fixture-lifecycle.sh
source "$root/scripts/ci/fixture-lifecycle.sh"
fixture="$(fixture_create "${TMPDIR:-/tmp}/make-format.XXXXXX")"
fixture_complete=false
trap 'fixture_finish "$?" "$fixture" "Formatting Make fixture retained"' EXIT
consumer="$fixture/consumer with spaces"
mkdir -p "$consumer/vendor/make" "$consumer/vendor/scripts/ci" "$consumer/ci" "$consumer/vendor/ci" "$consumer/.tools/rust/common/bin"
printf '[package]\nname = "fixture"\nversion = "0.0.0"\n' > "$consumer/Cargo.toml"
bash "$root/scripts/ci/prepare-script-fixture.sh" "$root" "$consumer/vendor" make/rust-format.mk
printf 'export TOKO_TOOLING_CARGO_SORT_VERSION=2.1.4\nTOKO_TOOLING_CARGO_SORT_DERIVES_VERSION=0.1.3\n' > "$consumer/vendor/ci/tool-versions.env"
cat > "$consumer/Makefile" <<'MAKE'
TOKO_TOOLING_ROOT ?= $(CURDIR)/vendor
FORMAT_CARGO := format-fixture-cargo
FORMAT_RUST_ARGS := --no-cache
include vendor/make/tools.mk vendor/make/rust-format.mk
format-tools-check fmt fmt-check: override TOKO_TOOLING_ROOT := $(CURDIR)/vendor
.PHONY: help
help:
	@echo harmless
MAKE
export JOBSERVER_PROBE="$root/scripts/ci/check-pipe-jobserver.pl"
cat > "$consumer/.tools/rust/common/bin/format-fixture-cargo" <<'CARGO'
#!/usr/bin/env bash
set -eu
if [[ "${JOBSERVER_TEST_REQUIRED:-0}" == 1 ]]; then
    perl "$JOBSERVER_PROBE"
fi
[[ "$CARGO_NET_OFFLINE" == true && "$RUSTUP_AUTO_INSTALL" == 0 ]] || exit 1
case "$*" in
    metadata*) perl -MJSON::PP -MCwd=getcwd -e '$p=getcwd(); print encode_json({workspace_root=>$p,workspace_members=>["fixture"],packages=>[{id=>"fixture",name=>"fixture",manifest_path=>"$p/Cargo.toml"}]})'; exit 0 ;;
    'sort --version') echo "cargo-sort ${FORMAT_TEST_VERSION:-2.1.4}"; exit 0 ;;
    'fmt --version') exit 0 ;;
esac
printf '%s\n' "$*" >> "$FORMAT_TEST_EVENTS"
echo 'Finished: Cargo.toml is sorted already, no changes made'
echo 'fixture stderr details' >&2
[[ "$*" != "${FORMAT_TEST_FAIL:-}" ]] || exit 1
CARGO
chmod +x "$consumer/.tools/rust/common/bin/format-fixture-cargo"
export FORMAT_TEST_EVENTS="$fixture/events"
export RUNNER_TEMP="$fixture"
[[ "$(make --no-print-directory -C "$consumer")" == harmless ]] || exit 1
[[ ! -e "$FORMAT_TEST_EVENTS" ]] || exit 1
for target in fmt fmt-check; do
    : > "$FORMAT_TEST_EVENTS"
    PATH=/usr/bin:/bin make --no-print-directory -C "$consumer" "$target" > "$fixture/$target.log" 2>&1
    if [[ "$target" == fmt ]]; then
        printf 'sort --workspace --grouped\nfmt --package fixture\n' > "$fixture/expected"
    else
        printf 'sort --workspace --grouped --check\nfmt --package fixture -- --check\n' > "$fixture/expected"
    fi
    cmp "$fixture/expected" "$FORMAT_TEST_EVENTS"
    [[ "$(wc -l < "$fixture/$target.log")" -eq 2 ]]
    grep -E '^Manifest sorting \[\.\]\.\.\. ok \([0-9]+\.[0-9]+s\)$' "$fixture/$target.log"
    grep -E '^Rust formatting \[\.\]\.\.\. ok \([0-9]+\.[0-9]+s\)$' "$fixture/$target.log"
done
# Ambient roots cannot select the parse-time helper, including for harmless help.
mkdir -p "$fixture/unselected/scripts/ci"
cat > "$fixture/unselected/scripts/ci/check-make-execution.sh" <<'SENTINEL'
#!/usr/bin/env bash
echo escaped >> "$FORMAT_TEST_EVENTS"
exit 23
SENTINEL
for target in help fmt fmt-check; do
    for source in environment command; do
        : > "$FORMAT_TEST_EVENTS"
        if [[ "$source" == environment ]]; then
            TOKO_TOOLING_ROOT="$fixture/unselected" make --no-print-directory -C "$consumer" "$target" > "$fixture/root-$source.log" 2>&1
        else
            make --no-print-directory -C "$consumer" "$target" "TOKO_TOOLING_ROOT=$fixture/unselected" > "$fixture/root-$source.log" 2>&1
        fi
        case "$target" in
            help) : > "$fixture/expected" ;;
            fmt) printf 'sort --workspace --grouped\nfmt --package fixture\n' > "$fixture/expected" ;;
            fmt-check) printf 'sort --workspace --grouped --check\nfmt --package fixture -- --check\n' > "$fixture/expected" ;;
        esac
        cmp "$fixture/expected" "$FORMAT_TEST_EVENTS"
    done
done
# A failed prerequisite or sorter must not run the later formatting operation.
cp "$consumer/vendor/ci/tool-versions.env" "$fixture/catalog"
for invalid in duplicate executable; do
    cp "$fixture/catalog" "$consumer/vendor/ci/tool-versions.env"
    if [[ "$invalid" == duplicate ]]; then
        printf 'TOKO_TOOLING_CARGO_SORT_VERSION=2.1.4\n' >> "$consumer/vendor/ci/tool-versions.env"
    else
        # shellcheck disable=SC2016 # The forbidden catalog would expand this if sourced.
        printf 'echo executed >> "$FORMAT_TEST_EVENTS"\n' >> "$consumer/vendor/ci/tool-versions.env"
    fi
    : > "$FORMAT_TEST_EVENTS"
    if make --no-print-directory -C "$consumer" fmt > "$fixture/catalog-$invalid.log" 2>&1; then exit 1; fi
    [[ ! -s "$FORMAT_TEST_EVENTS" ]] || exit 1
done
cp "$fixture/catalog" "$consumer/vendor/ci/tool-versions.env"
for failure in wrong missing sort; do
    : > "$FORMAT_TEST_EVENTS"
    case "$failure" in
        wrong) export FORMAT_TEST_VERSION=0.0.0 ;;
        missing) mv "$consumer/.tools/rust/common/bin/format-fixture-cargo" "$fixture/cargo" ;;
        sort) export FORMAT_TEST_FAIL='sort --workspace --grouped' ;;
    esac
    if PATH=/usr/bin:/bin make --no-print-directory -C "$consumer" fmt > "$fixture/$failure.log" 2>&1; then exit 1; fi
    if [[ "$failure" == sort ]]; then
        printf 'sort --workspace --grouped\n' > "$fixture/expected"
        cmp "$fixture/expected" "$FORMAT_TEST_EVENTS"
        grep -E '^Manifest sorting \[\.\]\.\.\. FAILED \(exit 1, [0-9]+\.[0-9]+s\)$' "$fixture/$failure.log"
        logs=("$fixture"/formatting.*)
        [[ ${#logs[@]} == 1 ]] || exit 1
        log="${logs[0]}"
        grep -Fx 'fixture stderr details' "$log"
        grep -Fx 'Finished: Cargo.toml is sorted already, no changes made' "$log"
        if grep -F 'Finished: Cargo.toml' "$fixture/$failure.log"; then exit 1; fi
    else
        [[ ! -s "$FORMAT_TEST_EVENTS" ]] || exit 1
    fi
    [[ "$failure" != missing ]] || mv "$fixture/cargo" "$consumer/.tools/rust/common/bin/format-fixture-cargo"
    unset FORMAT_TEST_VERSION FORMAT_TEST_FAIL
done
# Outer Make must reject unsafe modes, even when a prerequisite fails and Make
# would otherwise ignore it. No formatter may run, directly or via inherited flags.
for target in fmt fmt-check; do
    for mode in -i --ignore-errors -n --dry-run --just-print --recon -t --touch -q --question -kin; do
        for source in direct inherited cleared replaced both-hidden; do
            : > "$FORMAT_TEST_EVENTS"
            status=0
            if [[ "$source" == direct ]]; then
                FORMAT_TEST_VERSION=0.0.0 make -C "$consumer" "$mode" "$target" > "$fixture/mode.log" 2>&1 || status=$?
            elif [[ "$source" == inherited ]]; then
                _toko_make_execution_defined=yes MAKEFLAGS="$mode" FORMAT_TEST_VERSION=0.0.0 make -C "$consumer" "$target" > "$fixture/mode.log" 2>&1 || status=$?
            else
                flags=(MAKEFLAGS=)
                [[ "$source" != replaced ]] || flags=(MAKEFLAGS=--no-print-directory)
                [[ "$source" != both-hidden ]] || flags+=(MFLAGS=)
                make -C "$consumer" "$mode" "$target" "${flags[@]}" > "$fixture/mode.log" 2>&1 || status=$?
            fi
            if [[ "$status" != 2 || -s "$FORMAT_TEST_EVENTS" ]]; then
                echo "Formatting admission failed: $target $mode $source (status $status)" >&2
                exit 1
            fi
        done
    done
done
# Normal parallel mode and quoted command variables still reach the formatter.
parallel=(-j2)
if make --help | grep -q -- --jobserver-style; then parallel+=(--jobserver-style=pipe); fi
for target in format-tools-check fmt fmt-check; do
    JOBSERVER_TEST_REQUIRED=1 make "${parallel[@]}" --no-print-directory -C "$consumer" "$target" \
        "AUDIT_SELECTION=owner's selection" > "$fixture/parallel-$target.log" 2>&1
done
# Custom workspace/frontend adapters share presentation without giving this
# wrapper their formatter policy. Arguments and nonzero statuses remain exact.
status=0
bash "$root/scripts/ci/run-formatting.sh" --check bash -c 'printf "%s\n" "$1"; echo formatter-error >&2; exit 23' -- 'selected path with spaces' \
    > "$fixture/custom-output" 2>&1 || status=$?
[[ "$status" == 23 && "$(wc -l < "$fixture/custom-output")" -eq 2 ]] || exit 1
grep -Fx 'Checking formatting... FAILED (exit 23)' "$fixture/custom-output"
logs=("$fixture"/formatting.*)
[[ ${#logs[@]} == 2 ]] || exit 1
grep -Fx 'selected path with spaces' "$fixture"/formatting.*
grep -Fx formatter-error "$fixture"/formatting.*
# Successful standalone formatting removes only its own log, preserving the
# exact failed-command evidence retained above.
mkdir "$fixture/retained-logs"
for log in "${logs[@]}"; do cp "$log" "$fixture/retained-logs/${log##*/}"; done
bash "$root/scripts/ci/run-formatting.sh" --write \
    bash -c 'echo successful-formatter-detail' > "$fixture/success"
printf 'Formatting... ok\n' > "$fixture/expected-output"
cmp "$fixture/expected-output" "$fixture/success"
remaining=("$fixture"/formatting.*)
[[ ${#remaining[@]} == 2 ]] || exit 1
for log in "${logs[@]}"; do cmp "$log" "$fixture/retained-logs/${log##*/}"; done
echo 'Shared formatting Make commands passed (substitute Cargo; no installation)'
fixture_complete=true
