# Tier 2: the real gate. Whole project. Budget < 90s.
# Takes a cross-worktree lock so parallel agents queue instead of thrashing.

# The publish step below re-enters git push. Without this, that inner push would
# fire this hook again, run the gate again, and publish again, forever.
if [ "${AF_PUBLISHING:-0}" = '1' ]; then
  exit 0
fi

.agents/scripts/gate.sh || exit 1

# Publishing to `pages` overwrites the live site. It happens here, on a push of
# main to origin, and nowhere else.
#
# Set AF_NO_PUBLISH=1 to push main without republishing:
#   AF_NO_PUBLISH=1 git push
[ "${AF_NO_PUBLISH:-0}" = '1' ] && exit 0

remote_name=$1
[ "$remote_name" = 'origin' ] || exit 0

# stdin gives one line per ref being pushed:
#   <local ref> <local sha> <remote ref> <remote sha>
zero='0000000000000000000000000000000000000000'
while read -r local_ref local_sha remote_ref remote_sha; do
  [ "$remote_ref" = 'refs/heads/main' ] || continue
  # A deletion has no build to publish.
  [ "$local_sha" = "$zero" ] && continue

  # This hook runs before the push lands, so `pages` would go live ahead of
  # `main` if the push then failed. Publish only when the push cannot be
  # rejected as a non-fast-forward: the remote tip must already be an ancestor.
  if [ "$remote_sha" != "$zero" ] && ! git merge-base --is-ancestor "$remote_sha" "$local_sha"; then
    echo "pre-push: main is not a fast-forward; not publishing." >&2
    echo "          Push main first, then run .agents/scripts/publish-pages.sh" >&2
    continue
  fi

  .agents/scripts/publish-pages.sh --pending "$local_sha" || exit 1
done
