#!/usr/bin/env bash
# spark-shell compatibility launcher.
#
# Apache Spark's spark-shell is a JVM-hosted Scala REPL. spark-rust supplies the
# Spark Connect engine but does not bundle scala-compiler or claim a native Rust
# replacement for that REPL. This launcher delegates to an installed Apache
# Spark client distribution and points it at spark-rust over Spark Connect.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
APACHE_SPARK_HOME="${APACHE_SPARK_HOME:-}"
NATIVE_SHELL="${APACHE_SPARK_HOME:+$APACHE_SPARK_HOME/bin/spark-shell}"

if [[ -z "$NATIVE_SHELL" || ! -x "$NATIVE_SHELL" ]]; then
  cat >&2 <<'EOF'
spark-shell requires an Apache Spark client distribution because the Scala
REPL and scala-compiler are JVM components, not part of the Rust engine.

Install a compatible Apache Spark distribution, then run:

  export APACHE_SPARK_HOME=/opt/spark
  export SPARK_REMOTE=sc://spark-rust.example.com:15002
  spark-shell

For a JVM-free interactive shell, use spark-sql. For Python DataFrames, install
pyspark[connect] and connect to the same SPARK_REMOTE endpoint.
EOF
  exit 2
fi

if [[ -n "${SPARK_REMOTE:-}" ]]; then
  exec "$NATIVE_SHELL" --remote "$SPARK_REMOTE" "$@"
fi

# No remote was supplied: launch the packaged local Connect server.
SERVER_BIN="$ROOT/bin/spark-connect-server"
[[ -x "$SERVER_BIN" ]] || SERVER_BIN="$ROOT/target/release/spark-connect-server"
[[ -x "$SERVER_BIN" ]] || SERVER_BIN="$ROOT/target/debug/spark-connect-server"
if [[ ! -x "$SERVER_BIN" ]]; then
  echo "spark-shell: spark-connect-server not found; set SPARK_REMOTE to an administrator endpoint" >&2
  exit 2
fi
PORT="${SPARK_CONNECT_PORT:-$(python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close()')}"
"$SERVER_BIN" --port "$PORT" >"${TMPDIR:-/tmp}/spark-connect-spark-shell.log" 2>&1 &
SERVER_PID=$!
trap 'kill "$SERVER_PID" 2>/dev/null || true' EXIT INT TERM
for _ in $(seq 1 100); do
  (echo >/dev/tcp/127.0.0.1/"$PORT") >/dev/null 2>&1 && break
  sleep 0.1
done
exec "$NATIVE_SHELL" --remote "sc://127.0.0.1:$PORT" "$@"
