#!/bin/bash

set -ex

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "${script_dir}"

echo "Docs directory: $script_dir"

# Check if Bun is installed
if ! command -v bun &> /dev/null; then
    echo "Bun is not installed. Installing..."
    curl -fsSL https://bun.sh/install | bash
else
    echo "Bun is already installed."
fi

# Variables to add to the appropriate profile
CONTENT='
# Bun installation
export BUN_INSTALL="$HOME/.bun"
export PATH="$BUN_INSTALL/bin:$PATH"
'

# Determine the user's shell and appropriate profile file
if [[ "$SHELL" == *"zsh"* ]]; then
    PROFILE="$HOME/.zshrc"
elif [[ "$SHELL" == *"bash"* ]]; then
    PROFILE="$HOME/.bashrc"
else
    echo "Unsupported shell. Please add the following content manually to your shell profile:"
    echo "$CONTENT"
    exit 1
fi

# Add the content if it doesn't already exist
if grep -q 'export BUN_INSTALL="$HOME/.bun"' "$PROFILE"; then
    echo "Bun environment variables already exist in $PROFILE."
else
    echo "$CONTENT" >> "$PROFILE"
    echo "Bun environment variables added to $PROFILE. Please restart your shell or run 'source $PROFILE' to apply the changes."
fi

# Run 'bun install'
source "$PROFILE"
echo "Running 'bun install'..."
bun install
