#!/usr/bin/env bash
# Install/refresh the guarded-trunk pre-push hook in a repository. Idempotent: the marker block is
# replaced in place, anything else in the hook is preserved.
# Usage: install-land-guard.sh [repo] [--trunk <branch>]
set -euo pipefail

here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
guard="$here/land-guard.pre-push"
[[ -f "$guard" ]] || { echo "install-land-guard: guard source missing: $guard" >&2; exit 3; }

repo=$PWD trunk=""
while [[ $# -gt 0 ]]; do case "$1" in
  --trunk) trunk=$2; shift 2;;
  *) repo=$1; shift;;
esac; done
common=$(git -C "$repo" rev-parse --path-format=absolute --git-common-dir) || exit 3

# The guard reads harness.landGuardRef to know which ref is the guarded trunk. Sniff it from
# origin's default branch, else the sole main/master local branch; ambiguity fails closed.
if [[ -z "$trunk" ]]; then
  trunk=$(git -C "$repo" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's#^origin/##' || true)
fi
if [[ -z "$trunk" ]]; then
  for c in main master; do
    if git -C "$repo" show-ref -q --verify "refs/heads/$c"; then
      [[ -n "$trunk" ]] && { echo "install-land-guard: both main and master exist and origin/HEAD is unset — pass --trunk" >&2; exit 3; }
      trunk=$c
    fi
  done
fi
[[ -n "$trunk" ]] || { echo "install-land-guard: cannot resolve the trunk branch — pass --trunk" >&2; exit 3; }
git -C "$repo" check-ref-format "refs/heads/$trunk" || { echo "install-land-guard: invalid trunk branch: $trunk" >&2; exit 3; }
git -C "$repo" config --local harness.landGuardRef "refs/heads/$trunk"

# The land guard belongs to this repository. Never inherit or modify the machine-global hook
# dispatcher: local core.hooksPath deliberately overrides it for overdeck repositories.
hooks="$common/harness/hooks"
git -C "$repo" config --local core.hooksPath "$hooks"
mkdir -p "$hooks"

hook="$hooks/pre-push"
tmp=$(mktemp "$hooks/.pre-push.XXXXXX")
trap 'rm -f "$tmp"' EXIT

if [[ -f "$hook" ]]; then
  awk '/^# harness-land-guard v[0-9]+ BEGIN$/{skip=1} !skip{print} /^# harness-land-guard v[0-9]+ END$/{skip=0}' \
    "$hook" > "$tmp"
else
  printf '#!/usr/bin/env bash\nset -euo pipefail\n' > "$tmp"
fi
head -1 "$tmp" | grep -q '^#!' || { echo "install-land-guard: $hook has no interpreter line" >&2; exit 3; }
cat "$guard" >> "$tmp"
chmod 0755 "$tmp"
mv "$tmp" "$hook"
trap - EXIT

printf '{"stage":"install-land-guard","status":"installed","hook":"%s","trunk":"%s"}\n' "$hook" "$trunk"
