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

SELF=$0
while [ -h "$SELF" ]; do
  DIR=$(CDPATH= cd -P -- "$(dirname -- "$SELF")" && pwd)
  TARGET=$(readlink "$SELF")
  case "$TARGET" in
    /*) SELF=$TARGET ;;
    *) SELF=$DIR/$TARGET ;;
  esac
done

ROOT=$(CDPATH= cd -P -- "$(dirname -- "$SELF")/.." && pwd)
BIN="$ROOT/target/release/claude-exec"

if [ "${CLAUDE_EXEC_BIN:-}" != "" ] && [ -x "$CLAUDE_EXEC_BIN" ]; then
  exec "$CLAUDE_EXEC_BIN" "$@"
fi

if [ -x "$BIN" ]; then
  exec "$BIN" "$@"
fi

if ! command -v cargo >/dev/null 2>&1; then
  echo "claude-exec native binary is not built and cargo is not available." >&2
  echo "Run npm rebuild claude-e, cargo build --release --locked, or set CLAUDE_EXEC_BIN to a built binary." >&2
  exit 127
fi

exec cargo run --quiet --manifest-path "$ROOT/Cargo.toml" --bin claude-exec -- "$@"
