#!/bin/bash
# Install Bun and make it available system-wide
set -e

echo "==========================================
  Bun Installation for Raspberry Pi
==========================================
"

# Check if already installed
if command -v bun >/dev/null 2>&1; then
    echo "✓ Bun is already installed at: $(which bun) $(bun --version)"
    exit 0
fi

echo "Step 1: Installing Bun..."
echo "Running official Bun installer..."
curl -fsSL https://bun.sh/install | bash

echo ""
echo "Step 2: Finding Bun installation..."
BUN_PATH="$HOME/.bun/bin/bun"

if [ ! -f "$BUN_PATH" ]; then
    echo "❌ Error: Bun not found at $BUN_PATH"
    echo "Installation may have failed."
    exit 1
fi

echo "✓ Found Bun at: $BUN_PATH"
$BUN_PATH --version

echo ""
echo "Step 3: Creating system-wide symlink..."
sudo ln -sf "$BUN_PATH" /usr/local/bin/bun
echo "✓ Symlinked to /usr/local/bin/bun"

echo ""
echo "Step 4: Verifying installation..."
which bun
bun --version

echo "
==========================================
✓ Bun installation complete!
==========================================

Bun is now available system-wide:
  Location: /usr/local/bin/bun -> $BUN_PATH
  Version: $(bun --version)

You can now run bootstrap:
  sudo bun bootstrap.ts
"
