#!/usr/bin/env bash
# SSH shim — route every `ssh xamxam …` call made by the just deploy recipes to
# the podman test box instead of production. Put test-env/bin on PATH (i.e. run
# via `just test-env-run recipe=…`) so this shim shadows the real ssh.
set -euo pipefail

# Resolve this script's own directory robustly (BASH_SOURCE is reliable even
# when invoked via PATH as a bare name like `ssh`).
SRC="${BASH_SOURCE[0]}"
while [ -L "$SRC" ]; do SRC="$(readlink "$SRC")"; done
DIR="$(cd "$(dirname "$SRC")" && pwd)"
CONF="${XAMXAM_TEST_SSH_CONFIG:-$DIR/../ssh/config}"

# Resolve the real ssh, excluding this shim's own directory from PATH to avoid
# recursion. Entries may be relative, so canonicalise each before comparing.
_clean_path() {
  local IFS=: out=() e dir
  for e in $PATH; do
    [ -n "$e" ] || continue
    dir="$(cd "$e" 2>/dev/null && pwd)"
    if [ "$dir" = "$DIR" ]; then continue; fi
    out+=("$e")
  done
  local IFS=:; echo "${out[*]}"
}
REAL="$(PATH="$(_clean_path)" command -v ssh || echo /usr/bin/ssh)"

exec "$REAL" -F "$CONF" "$@"
