#!/usr/bin/env bash
# Generated by OpenOrchestrate.
# Full checks before a push: the pre-commit checks plus the test suite.
#
# Format and lint are scoped to the commits being pushed, not the whole tree.
# The range is handed to scripts/verify.sh as OO_PUSH_RANGES (base..head, space
# separated):
#   explicit: pre-push <base> <head>  (both resolve to commits) -> base..head
#   from git: refs arrive on stdin as <lref> <lsha> <rref> <rsha>
#   fallback: @{u}..HEAD
set -euo pipefail

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

ZERO=0000000000000000000000000000000000000000
is_commit() { git rev-parse --verify --quiet "$1^{commit}" >/dev/null 2>&1; }

RANGES=''

if [ "$#" -eq 2 ] && is_commit "$1" && is_commit "$2"; then
  # Explicit range, so the hook can be run by hand and by the tautology check.
  RANGES="$1..$2"
else
  REMOTE="${1:-origin}"
  if [ ! -t 0 ]; then
    while read -r _lref lsha _rref rsha; do
      [ -n "${lsha:-}" ] || continue
      if [ -z "${rsha:-}" ] || [ "$rsha" = "$ZERO" ]; then
        # New branch: everything not already on the remote.
        oldest="$(git rev-list "$lsha" --not --remotes="$REMOTE" 2>/dev/null | tail -1 || true)"
        [ -n "$oldest" ] || continue
        base="$(git rev-parse "$oldest^" 2>/dev/null || printf '%s' "$oldest")"
      else
        base="$rsha"
      fi
      RANGES="${RANGES}${RANGES:+ }$base..$lsha"
    done || true
  fi
  # No refs on stdin (run by hand with no arguments): compare with upstream.
  [ -n "$RANGES" ] || RANGES='@{u}..HEAD'
fi

OO_PUSH_RANGES="$RANGES"
export OO_PUSH_RANGES
exec bash "$ROOT/scripts/verify.sh" pre-push
