#!/usr/bin/env bash
# Cerebro prereq installer for macOS and Linux.
# Hosted at https://nathanphinney.com/rag/install.sh
# Run with:  curl -fsSL https://nathanphinney.com/rag/install.sh | bash

set -e

say() { printf "\033[1m==>\033[0m %s\n" "$*"; }

OS="$(uname -s)"

install_mac() {
  if ! command -v brew >/dev/null 2>&1; then
    say "Installing Homebrew"
    NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    eval "$(/opt/homebrew/bin/brew shellenv 2>/dev/null || /usr/local/bin/brew shellenv)"
  fi
  command -v git >/dev/null 2>&1    || { say "Installing git";    brew install git; }
  command -v python3 >/dev/null 2>&1 || { say "Installing python3"; brew install python@3.12; }
  command -v node >/dev/null 2>&1   || { say "Installing node";   brew install node; }
}

install_linux() {
  SUDO=""
  [ "$(id -u)" -ne 0 ] && SUDO="sudo"
  if   command -v apt-get >/dev/null 2>&1; then
    $SUDO apt-get update -y
    $SUDO apt-get install -y git python3 nodejs npm curl
  elif command -v dnf >/dev/null 2>&1; then
    $SUDO dnf install -y git python3 nodejs npm curl
  elif command -v pacman >/dev/null 2>&1; then
    $SUDO pacman -Sy --noconfirm git python nodejs npm curl
  elif command -v apk >/dev/null 2>&1; then
    $SUDO apk add git python3 nodejs npm curl bash
  else
    echo "I don't recognize this package manager. Install git, python3, node, and npm manually, then re-run." >&2
    exit 1
  fi
}

case "$OS" in
  Darwin) say "Detected macOS"; install_mac   ;;
  Linux)  say "Detected Linux"; install_linux ;;
  *)      echo "Unsupported OS: $OS" >&2; exit 1 ;;
esac

if ! command -v claude >/dev/null 2>&1; then
  say "Installing Claude Code"
  npm install -g @anthropic-ai/claude-code
fi

say "Everything installed. Launching Claude Code to set up your vault."
echo ""

exec claude "Fetch https://nathanphinney.com/rag/prompt.txt and follow its instructions to set up my second brain."
