#!/usr/bin/env bash
set -euo pipefail
# harness-land-guard v3 BEGIN
# Only a process holding a live land authority may move main. The authority is a file NAMED by
# the pushing process's nonce, so concurrent landers cannot overwrite one another's slot and a
# leaked file authorizes nothing — the name is the secret.
#
# A lander predating the per-nonce authority writes a single shared file instead. That form is
# still accepted while such landers exist, but only from a process holding the land-queue
# conductor lock, which is the only serialization the shared form has.
_lg_guard_ref="$(git config --get harness.landGuardRef 2>/dev/null || printf 'refs/heads/main')"
while read -r _lg_local_ref _lg_local_sha _lg_remote_ref _lg_remote_sha; do
  [[ "$_lg_remote_ref" == "$_lg_guard_ref" ]] || continue

  _lg_reject() {
    _lg_guidance="pre-push: rejected — $1. The trunk branch is guarded (single serialized writer). Land via the harness lander: ship.sh land / ship.sh submit (routes through workflows/lib/finish-branch.sh), never a raw push."
    printf 'pre-push: rejected — %s\n' "$1" >&2
    cat >&2 <<'GUARD'
The trunk branch is guarded: it has a single serialized writer (trunk-ownership).
Do NOT push to it 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, gates a candidate, then fast-forwards the trunk under a land authority.
Raw pushes to the trunk are rejected by design — this is not an error to work around.
GUARD
    # Fail-open structured record, same shape/log the queue conductor writes to — a logging
    # failure here must never mask or alter the refusal above.
    {
      _lg_qdir="$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)/harness/landq"
      mkdir -p "$_lg_qdir" 2>/dev/null
      _lg_who="$(git config --get user.email 2>/dev/null)"
      [[ -n "$_lg_who" ]] || _lg_who="$(id -un 2>/dev/null)@$(hostname 2>/dev/null)"
      _lg_esc() { local s=${1//\\/\\\\}; s=${s//\"/\\\"}; s=${s//$'\n'/ }; printf '%s' "$s"; }
      printf '{"event":"violation","kind":"%s","branch":"%s","who":"%s","guidance":"%s","pid":%s,"at":"%s"}\n' \
        "$(_lg_esc "pre-push-trunk-rejected")" "$(_lg_esc "$_lg_remote_ref")" "$(_lg_esc "$_lg_who")" \
        "$(_lg_esc "$_lg_guidance")" "$$" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$_lg_qdir/log" 2>/dev/null
    } || true
    exit 1
  }

  if [[ "$_lg_local_sha" =~ ^0+$ ]]; then
    _lg_reject 'trunk deletion'
  fi
  if [[ "$_lg_remote_sha" =~ ^0+$ ]] || ! git merge-base --is-ancestor "$_lg_remote_sha" "$_lg_local_sha"; then
    _lg_reject 'non-fast-forward trunk update'
  fi

  _lg_token="${HARNESS_LAND_TOKEN:-}"
  if [[ ! "$_lg_token" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ ]]; then
    _lg_reject 'unauthorized trunk update'
  fi
  _lg_common="$(git rev-parse --path-format=absolute --git-common-dir)"
  _lg_authority="$_lg_common/harness/land-authority.$_lg_token"
  if [[ -f "$_lg_authority" ]]; then
    if [[ "$(stat -c '%a %u' "$_lg_authority")" != "600 $(id -u)" ]]; then
      _lg_reject 'unauthorized trunk update'
    fi
    _lg_authority_lock="$(<"$_lg_authority")"
    if [[ "$_lg_authority_lock" != /* || "${_lg_authority_lock##*/}" != conductor.lock \
      || ! -e "$_lg_authority_lock" ]]; then
      _lg_reject 'invalid land authority lock'
    fi
    exec {_lg_fd}>"$_lg_authority_lock"
    if flock -n "$_lg_fd"; then
      flock -u "$_lg_fd"; exec {_lg_fd}>&-
      _lg_reject 'stale land authority'
    else
      _lg_flock_rc=$?
      exec {_lg_fd}>&-
      if (( _lg_flock_rc != 1 )); then
        _lg_reject 'land authority lock verification failure'
      fi
    fi
  else
    _lg_shared="$_lg_common/harness/land-authority"
    if [[ ! -f "$_lg_shared" ]] || [[ "$(<"$_lg_shared")" != "$_lg_token" ]]; then
      _lg_reject 'unauthorized trunk update'
    fi
    _lg_lock="$_lg_common/harness/landq/conductor.lock"
    if [[ ! -e "$_lg_lock" ]]; then
      _lg_reject 'shared land authority with no land queue'
    fi
    exec {_lg_fd}>"$_lg_lock"
    if flock -n "$_lg_fd"; then
      flock -u "$_lg_fd"; exec {_lg_fd}>&-
      _lg_reject 'shared land authority outside an active land-queue conductor'
    else
      _lg_flock_rc=$?
      exec {_lg_fd}>&-
      if (( _lg_flock_rc != 1 )); then
        _lg_reject 'conductor lock verification failure'
      fi
    fi
  fi
done
# harness-land-guard v3 END
