#!/usr/bin/env bash
# rsync shim — route every `rsync … xamxam:/…` from the just recipes to the
# podman test box instead of production.
#
# Safety: it ALWAYS forces the transport to the real ssh with the test SSH
# config (-F). Any caller-supplied `-e`/`--rsh` is REPLACED, and when the recipe
# passes NO -e, we still inject ours so rsync never falls back to the host's
# real ~/.ssh/config (which maps `xamxam` → PRODUCTION).
set -euo pipefail

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}"

_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[*]}"
}
REALRSYNC="$(PATH="$(_clean_path)" command -v rsync || echo /usr/sbin/rsync)"
REALSSH="$(PATH="$(_clean_path)" command -v ssh || echo /usr/sbin/ssh)"

RCLIENT="$REALSSH -F $CONF"

args=()
skipnext=0
for a in "$@"; do
  if [ "$skipnext" = 1 ]; then
    skipnext=0
    continue
  fi
  case "$a" in
    -e|--rsh|-e=*|--rsh=*)
      case "$a" in -e|--rsh) skipnext=1 ;; esac
      ;;
    *)
      args+=("$a")
      ;;
  esac
done

exec "$REALRSYNC" -e "$RCLIENT" "${args[@]}"
