#!/usr/bin/env bash
#
# termscp pre-commit hook.
#
# Runs two gates before a commit is recorded:
#   1. dprint      -- check formatting (Markdown, TOML, YAML, Rust)
#   2. cargo-deny  -- advisories, licenses, bans, and sources
#
# Install with `just setup_githooks` (sets core.hooksPath to .githooks).
# Bypass in an emergency with `git commit --no-verify`.

set -euo pipefail

fail() {
    echo "pre-commit: $1" >&2
    exit 1
}

command -v just >/dev/null 2>&1 || fail "just not found; install it to run the pre-commit checks"

if ! git diff --cached --quiet --diff-filter=ACMR --; then
    # Check the exact tree that will be committed, not possibly different
    # working-tree contents. The trailing slash is required by checkout-index.
    index_tree="$(mktemp -d)"
    cleanup() {
        rm -rf -- "$index_tree"
    }
    trap cleanup EXIT
    git checkout-index --all --prefix="$index_tree/"

    echo "pre-commit: checking staged-tree formatting"
    (
        cd "$index_tree"
        just fmt_check
    )

    echo "pre-commit: checking staged-tree dependencies"
    (
        cd "$index_tree"
        just deny
    )
fi

echo "pre-commit: all checks passed"
