#!/usr/bin/env sh
set -eu

script_path="$0"

# If invoked via PATH (`mpcr`), resolve to an absolute path so we can find `mpcr-src/`.
case "$script_path" in
  */*) : ;;
  *)
    resolved="$(command -v -- "$script_path" 2>/dev/null || true)"
    case "$resolved" in
      */*) script_path="$resolved" ;;
    esac
    ;;
esac

# If the script is symlinked (common for shims in `$PATH`), resolve links so relative
# paths (like `mpcr-src/`) are found next to the real script file.
if command -v readlink >/dev/null 2>&1; then
  while [ -L "$script_path" ]; do
    link="$(readlink "$script_path" 2>/dev/null || true)"
    [ -n "$link" ] || break
    case "$link" in
      /*) script_path="$link" ;;
      *) script_path="$(dirname -- "$script_path")/$link" ;;
    esac
  done
fi

script_dir="$(CDPATH='' cd -- "$(dirname -- "$script_path")" && pwd)"
src_dir="${script_dir}/mpcr-src"
bin="${src_dir}/target/release/mpcr"

if [ ! -f "${src_dir}/Cargo.lock" ]; then
  echo "error: missing ${src_dir}/Cargo.lock (skill is expected to be shipped with a lockfile)" >&2
  exit 2
fi

needs_build=0
if [ ! -x "${bin}" ]; then
  needs_build=1
elif [ "${src_dir}/Cargo.toml" -nt "${bin}" ] || [ "${src_dir}/Cargo.lock" -nt "${bin}" ]; then
  needs_build=1
elif find "${src_dir}/src" "${src_dir}/tests" "${src_dir}/protocols" -type f -newer "${bin}" -print -quit 2>/dev/null | grep -q .; then
  needs_build=1
fi

if [ "${needs_build}" -eq 1 ]; then
  if ! command -v cargo >/dev/null 2>&1; then
    echo "error: mpcr is not built and 'cargo' was not found in PATH" >&2
    echo "hint: install a Rust toolchain (rustc + cargo) to build ${src_dir}" >&2
    exit 127
  fi
  cargo build --manifest-path "${src_dir}/Cargo.toml" --locked --release
fi

# Suppress pagers in non-interactive (agent) sessions.
if [ ! -t 1 ]; then
  export PAGER=cat
  export GIT_PAGER=cat
  export NO_PAGER=1
fi

# Keep agent-facing errors concise by default.
if [ -z "${RUST_BACKTRACE+x}" ]; then
  export RUST_BACKTRACE=0
fi

exec "${bin}" "$@"
