#!/usr/bin/env bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ENTRY="cli.js"

# Prefer bun, then node; otherwise install Bun
if command -v bun >/dev/null 2>&1; then
  RUNNER=bun
  RUN_CMD=(bun run "$ENTRY")
elif command -v node >/dev/null 2>&1; then
  RUNNER=node
  RUN_CMD=(node "$ENTRY")
else
  # Install Bun (automated, non-interactive)
  if [[ "$(uname -s)" == "Linux" ]] && ! command -v unzip >/dev/null 2>&1; then
    if command -v apt-get >/dev/null 2>&1; then
      sudo apt-get update -qq && sudo apt-get install -y unzip || { echo "Linux: install unzip first, e.g. sudo apt install unzip"; exit 1; }
    elif command -v dnf >/dev/null 2>&1; then
      sudo dnf install -y unzip || { echo "Linux: install unzip first, e.g. sudo dnf install unzip"; exit 1; }
    elif command -v yum >/dev/null 2>&1; then
      sudo yum install -y unzip || { echo "Linux: install unzip first, e.g. sudo yum install unzip"; exit 1; }
    else
      echo "Linux: unzip is required. Install with: sudo apt install unzip (or equivalent)."
      exit 1
    fi
  fi
  curl -fsSL https://bun.sh/install | bash
  export PATH="$HOME/.bun/bin:$PATH"
  RUNNER=bun
  RUN_CMD=(bun run "$ENTRY")
fi

exec "${RUN_CMD[@]}" "$@"
