#!/usr/bin/env bash
# Always use the repository's toolchain; never silently choose an older compiler.
set -euo pipefail
root="$(cd "$(dirname "$0")/.." && pwd)"
version="$(python3 "$root/scripts/rust-version.py")"
minor="${version%.*}"

run_toolchain() {
  local selected="$1" toolchain_home="$2" toolchain_path="$3"
  export RUSTUP_HOME="$toolchain_home" PATH="$toolchain_path/bin:$PATH"
  export LD_LIBRARY_PATH="$toolchain_path/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
  if [[ "$toolchain_home" = "$root/.tools/rust" ]]; then
    export CARGO_HOME="$root/.tools/cargo"
  fi
  # Cargo configuration can name an absolute system compiler even with this PATH.
  # Environment overrides keep build scripts and nested Cargo invocations pinned too.
  export RUSTC="$toolchain_path/bin/rustc" RUSTDOC="$toolchain_path/bin/rustdoc"
  export RUSTUP_TOOLCHAIN="$selected"
  shift 3
  if [[ "${1:-}" = --compiler-version ]]; then
    exec "$root/scripts/rustup" run "$selected" rustc -Vv
  fi
  exec "$root/scripts/rustup" run "$selected" cargo "$@"
}

# Prefer the official version downloaded by rustup, including over cached custom tools.
for toolchain_home in "$root/.tools/rust" "${RUSTUP_HOME:-$HOME/.rustup}"; do
  for toolchain in "$toolchain_home/toolchains/$version"-*; do
    if [[ -x "$toolchain/bin/rustc" ]] && "$toolchain/bin/rustc" --version >/dev/null 2>&1; then
      run_toolchain "$version" "$toolchain_home" "$toolchain" "$@"
    fi
  done
done

# Optional offline Void repair must match the exact repository version.
custom="$root/.tools/void-rust-$minor/usr"
if [[ -x "$custom/bin/rustc" && -d "$root/.tools/rust/toolchains/image-sparrow-$minor" ]]; then
  actual="$(LD_LIBRARY_PATH="$custom/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" "$custom/bin/rustc" --version)"
  if [[ "$actual" = "rustc $version "* ]]; then
    run_toolchain "image-sparrow-$minor" "$root/.tools/rust" "$custom" "$@"
  fi
fi
printf 'Rust %s is required. Run ./scripts/bootstrap.sh to download it with rustup.\n' "$version" >&2
exit 1
