#!/usr/bin/env bash
set -euo pipefail

reject() {
  printf 'pre-push: rejected — %s\n' "$1" >&2
  cat >&2 <<'GUARD'
'main' is guarded: it has a single serialized writer (trunk-ownership).
Do NOT push to main directly and do NOT --force. Land your branch via the harness lander:
    ship.sh land        (routes through workflows/lib/finish-branch.sh)
It enqueues a land ticket; the conductor gates a candidate and fast-forwards main while
holding the conductor lock. Raw pushes to main are rejected by design — this is not an
error to work around.
GUARD
  exit 1
}

while read -r local_ref local_sha remote_ref remote_sha; do
  if [[ "$remote_ref" != 'refs/heads/main' ]]; then
    continue
  fi

  if [[ "$local_sha" =~ ^0+$ ]]; then
    reject 'main deletion'
  fi
  if [[ "$remote_sha" =~ ^0+$ ]] || ! git merge-base --is-ancestor "$remote_sha" "$local_sha"; then
    reject 'non-fast-forward main update'
  fi

  land_token="${HARNESS_LAND_TOKEN:-}"
  if [[ -z "$land_token" ]]; then
    reject 'unauthorized main update'
  fi

  common_dir="$(git rev-parse --path-format=absolute --git-common-dir)"
  authority_path="$common_dir/harness/land-authority"
  # The pusher is the land-queue conductor, and it holds this lock across the whole drain.
  lock_path="$common_dir/harness/landq/conductor.lock"
  if [[ ! -f "$authority_path" ]]; then
    reject 'unauthorized main update'
  fi
  authority_token="$(<"$authority_path")"
  if [[ "$authority_token" != "$land_token" ]]; then
    reject 'unauthorized main update'
  fi

  if [[ ! -d "${lock_path%/*}" ]]; then
    reject 'main update with no land queue'
  fi
  exec {lock_probe_fd}>"$lock_path"
  if flock -n "$lock_probe_fd"; then
    flock -u "$lock_probe_fd"
    exec {lock_probe_fd}>&-
    reject 'main update outside an active land-queue conductor'
  else
    flock_status=$?
    exec {lock_probe_fd}>&-
    if (( flock_status != 1 )); then
      reject 'conductor lock verification failure'
    fi
  fi
done
