#!/bin/sh
# Repo pre-push hook: run the exact rustfmt gates CI runs, so a push can never fail on
# formatting alone. Enable once per clone:
#
#     git config core.hooksPath scripts/git-hooks
#
# Kept to the CHEAP checks on purpose (rustfmt only parses — a couple of seconds): clippy/tests
# stay in CI and the per-box verify recipes. Runs regardless of how the commits were made
# (plain `git commit`, amends, or plumbing like commit-tree — pre-push sees them all).
#
# Escape hatch for a genuine emergency: `git push --no-verify`.

set -eu
root=$(git rev-parse --show-toplevel)

fail() {
    echo "pre-push: $1" >&2
    echo "pre-push: fix with: $2" >&2
    echo "pre-push: (bypass in an emergency with: git push --no-verify)" >&2
    exit 1
}

# 1. Main workspace — mirrors ci.yml "Format": cargo fmt --all --check.
if ! (cd "$root" && cargo fmt --all --check >/dev/null 2>&1); then
    fail "main workspace is not rustfmt-clean (ci.yml would fail)" \
         "cargo fmt --all"
fi

# 2. UMDF driver workspace — mirrors windows-drivers.yml's gate (the shipped drivers + the
# audited safe layer; pf-vdisplay is deliberately NOT gated there, so not here either).
if ! (cd "$root/packaging/windows/drivers" \
      && cargo fmt -p pf-umdf-util -p pf-xusb -p pf-dualsense --check >/dev/null 2>&1); then
    fail "driver workspace is not rustfmt-clean (windows-drivers.yml would fail)" \
         "(cd packaging/windows/drivers && cargo fmt -p pf-umdf-util -p pf-xusb -p pf-dualsense)"
fi

exit 0
