#!/usr/bin/env bash
# Generated by OpenOrchestrate.
# Full checks before a push: the push approval gate, then the pre-commit checks
# and the test suite.
#
# The gate is the part that is not skippable with OO_SKIP. Every ref on stdin
# needs an approved row for push/<remote>/<branch>. The one bypass is
# `git push --no-verify`; it leaves no approval row, which is the audit gap this
# hook exists to close.
set -euo pipefail

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

# Resolve the CLI. OO_APPROVAL_CLI may include arguments, e.g.
# "bun /path/to/openorchestrate/src/cli.ts"; it exists for tests and unusual
# installs. The normal path is the `oo` binary.
run_cli() {
  if [ -n "${OO_APPROVAL_CLI:-}" ]; then
    # shellcheck disable=SC2086
    $OO_APPROVAL_CLI "$@"
  elif command -v oo >/dev/null 2>&1; then
    oo "$@"
  elif command -v openorchestrate >/dev/null 2>&1; then
    openorchestrate "$@"
  elif [ -x "$ROOT/node_modules/.bin/oo" ]; then
    "$ROOT/node_modules/.bin/oo" "$@"
  elif command -v bun >/dev/null 2>&1 && [ -f "$ROOT/src/cli.ts" ]; then
    bun "$ROOT/src/cli.ts" "$@"
  else
    return 127
  fi
}

# `git push` passes each ref on stdin:
#   <local ref> <local sha> <remote ref> <remote sha>
# Check every ref before running the expensive suite. A deletion (all-zero local
# sha) still needs a push approval: deleting a remote branch is a push.
blocked=0
while read -r local_ref local_sha remote_ref remote_sha; do
  [ -z "${local_ref:-}" ] && continue

  case "$remote_ref" in
    refs/heads/*) branch="${remote_ref#refs/heads/}" ;;
    refs/tags/*) branch="${remote_ref#refs/tags/}" ;;
    *) branch="$remote_ref" ;;
  esac
  resource="push/${1:-remote}/${branch}"

  set +e
  output="$(run_cli approval check --action push --resource "$resource" 2>&1)"
  status=$?
  set -e

  if [ "$status" -eq 127 ]; then
    printf '\npush blocked: cannot find the oo CLI to check %s\n' "$resource" >&2
    printf '  Install OpenOrchestrate or set OO_APPROVAL_CLI, then retry.\n' >&2
    printf '  Bypass this one push with: git push --no-verify\n\n' >&2
    blocked=1
    break
  fi

  if [ "$status" -ne 0 ]; then
    printf '\npush blocked: no approved approval for %s\n\n' "$resource" >&2
    printf '%s\n' "$output" >&2
    printf '\nThis hook is the push gate. Bypass this one push with:\n' >&2
    printf '  git push --no-verify\n\n' >&2
    blocked=1
  else
    printf 'push approved: %s\n' "$resource" >&2
    printf '%s\n' "$output" >&2
  fi
done

if [ "$blocked" -ne 0 ]; then
  exit 1
fi

exec bash "$ROOT/scripts/verify.sh" pre-push
