#!/usr/bin/env bash
# install-git-guard-real — pin the real git binary for _git-guard-shim.sh.
#
# The shim reads ONLY this pin at run time. Resolution happens here, once, and every
# candidate is rejected unless it is an ELF binary that carries no shim marker, so the
# pin can never name a copy of the shim (the fork-loop that took the machine down).
#
# Usage: install-git-guard-real [--status]
set -uo pipefail

PIN_DIR="$HOME/.local/state/overdeck/shim-real"
PIN="$PIN_DIR/git"
SHIM_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

fail() {
  echo "install-git-guard-real: $1" >&2
  exit 1
}

is_elf() { # $1=path → 0 when the file starts with the ELF magic
  local magic
  magic=$(head -c 4 -- "$1" 2>/dev/null | od -An -tx1 | tr -d ' \n') || return 1
  [[ "$magic" == "7f454c46" ]]
}

carries_shim_marker() { # $1=path
  head -c 8192 -- "$1" 2>/dev/null | grep -qF 'OD_PATH_SHIM_MARKER'
}

candidate_ok() { # $1=path
  local p="$1"
  [[ -n "$p" && "$p" == /* && -f "$p" && -x "$p" ]] || return 1
  is_elf "$p" || return 1
  ! carries_shim_marker "$p"
}

if [[ "${1:-}" == "--status" ]]; then
  [[ -r "$PIN" ]] || fail "no pin at $PIN"
  IFS= read -r pinned <"$PIN" || true
  candidate_ok "$pinned" || fail "pinned git is not a usable ELF binary: '$pinned' ($PIN)"
  echo "git-guard pin: $pinned"
  exit 0
fi
[[ $# -eq 0 ]] || fail "usage: install-git-guard-real [--status]"

resolved=""
IFS=':' read -ra parts <<<"$PATH:/usr/bin:/bin"
for d in "${parts[@]}"; do
  [[ -n "$d" && "$d" == /* ]] || continue
  [[ "$d" == "$SHIM_DIR" ]] && continue
  if candidate_ok "$d/git"; then
    resolved="$d/git"
    break
  fi
done

[[ -n "$resolved" ]] || fail "no real git found on PATH (every candidate was missing, non-ELF, or a shim copy) — install git, then re-run"

mkdir -p "$PIN_DIR" || fail "cannot create $PIN_DIR"
tmp="$PIN.$$"
printf '%s\n' "$resolved" >"$tmp" || fail "cannot write $tmp"
mv -f "$tmp" "$PIN" || fail "cannot install $PIN"
echo "git-guard pin: $resolved -> $PIN"
