#!/usr/bin/env bash
# bxc — thin wrapper around src/cli/serve.ts.
#
# Resolves the script relative to this file so the wrapper works whether it is
# called via an absolute path, a $PATH entry, or a symlink.

set -e

# Resolve symlinks so SCRIPT_DIR points at the real bin/ directory.
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
BXC_ROOT="$(cd -P "$SCRIPT_DIR/.." && pwd)"

BUN_BIN="${BUN_BIN:-bun}"

# Optimize: execute compiled standalone binary directly if available
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
BINARY=""

case "$OS" in
  linux)
    if [ "$ARCH" = "x86_64" ]; then
      BINARY="bxc-linux-x64"
    elif [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
      BINARY="bxc-linux-arm64"
    fi
    ;;
  darwin)
    if [ "$ARCH" = "x86_64" ]; then
      BINARY="bxc-darwin-x64"
    elif [ "$ARCH" = "arm64" ]; then
      BINARY="bxc-darwin-arm64"
    fi
    ;;
  msys*|mingw*|cygwin*|windows*)
    BINARY="bxc-windows-x64.exe"
    ;;
esac

# BXC_FROM_SOURCE=1 force le passage par les sources : les binaires construits
# avec un renommage d'identifiants cassent les eval CDP qui referencent des
# fonctions par nom (ex. `awaitPromise`). Cf. scripts/build-standalone.ts.
if [ -z "${BXC_FROM_SOURCE:-}" ] && [ -n "$BINARY" ] && [ -x "$BXC_ROOT/dist/standalone/$BINARY" ]; then
  exec "$BXC_ROOT/dist/standalone/$BINARY" "$@"
fi

if ! command -v "$BUN_BIN" >/dev/null 2>&1; then
  echo "bxc: \`bun\` not found on PATH. Install from https://bun.sh" >&2
  exit 127
fi

exec "$BUN_BIN" run "$BXC_ROOT/src/cli/index.ts" "$@"
