#!/usr/bin/env bash
# Copyright 2026 Rhett Creighton - Apache License 2.0
#
# Pre-push LOCAL CI gate.
#
# This project runs CI ONLY locally on the maintainer's own server — never
# GitHub Actions (Actions cost money). `make ci` (lint + test_zcl + the MVP
# slice-gates + bench-regress) is the gate; this hook makes it AUTOMATIC so
# nothing unverified reaches origin, instead of relying on a human to remember.
#
# Activate:  make install-hooks   (sets core.hooksPath=tools/githooks)
# Bypass once:  git push --no-verify     OR     ZCL_SKIP_PREPUSH=1 git push
# Override the command (e.g. a faster subset):  ZCL_PREPUSH_CMD='make lint'
#
# Pushes are infrequent in this repo, so a full `make ci` per push is cheap
# relative to the cost of shipping a regression to origin.
set -euo pipefail

if [ "${ZCL_SKIP_PREPUSH:-0}" = "1" ]; then
    echo "pre-push: ZCL_SKIP_PREPUSH=1 — skipping the local CI gate." >&2
    exit 0
fi

# git feeds '<local ref> <local sha> <remote ref> <remote sha>' lines on stdin.
# If every ref is a deletion (local sha all-zero) there is nothing new to
# verify — allow the push without running CI.
z="0000000000000000000000000000000000000000"
have_update=0
while read -r _lref lsha _rref _rsha; do
    [ -n "${lsha:-}" ] || continue
    [ "$lsha" = "$z" ] || have_update=1
done
if [ "$have_update" = "0" ]; then
    exit 0
fi

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

CMD="${ZCL_PREPUSH_CMD:-make ci}"
echo "pre-push: running local CI gate ($CMD) before push to origin…" >&2
echo "pre-push: bypass one push with 'git push --no-verify' if you must." >&2
if ! $CMD; then
    echo "" >&2
    echo "pre-push: LOCAL CI FAILED — push BLOCKED." >&2
    echo "pre-push: fix it, or override this one push with 'git push --no-verify'." >&2
    exit 1
fi
echo "pre-push: local CI green — allowing push." >&2
exit 0
