#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Authoritative local gate: run the full test suite before a push. The remote will run the same
# suite once a forge is in place.
#
# A push whose every ref changes only prose nothing reads (see scripts/hooks/prose-only) runs the
# documentation check instead. Anything this hook cannot classify -- a new branch, a remote commit
# this clone does not have, a ref it cannot read -- runs the full suite. A push that sends no content
# (only deletions, or refs already up to date) runs nothing.

set -eu

PROJECT_ROOT=$(git rev-parse --show-toplevel)
cd "$PROJECT_ROOT"

# Run by hand from a terminal there is no ref list to read: run the full suite.
if [ -t 0 ]; then
    exec "$PROJECT_ROOT/scripts/check-tests"
fi

zero=0000000000000000000000000000000000000000
prose_only=1
pushing=0

# stdin: <local ref> <local sha> <remote ref> <remote sha>, one line per ref being pushed.
while read -r _local_ref local_sha _remote_ref remote_sha; do
    [ "$local_sha" = "$zero" ] && continue        # a deletion pushes no content
    [ "$local_sha" = "$remote_sha" ] && continue  # already up to date
    pushing=1
    if [ "$remote_sha" = "$zero" ] || ! git cat-file -e "$remote_sha^{commit}" 2>/dev/null; then
        prose_only=0
        break
    fi
    if ! git diff --name-only --no-renames "$remote_sha" "$local_sha" |
        "$PROJECT_ROOT/scripts/hooks/prose-only"; then
        prose_only=0
        break
    fi
done

if [ "$pushing" -eq 0 ]; then
    exit 0   # only deletions or up-to-date refs: no content leaves this clone
fi

if [ "$prose_only" -eq 1 ]; then
    printf '%s\n' "pre-push: prose-only change; running the documentation check instead of the suite."
    exec "$PROJECT_ROOT/scripts/check-docs"
fi

exec "$PROJECT_ROOT/scripts/check-tests"
