#!/bin/bash
set -e
# Path: scripts/rust.sh

BLUE='\033[1;34m'
YELLOW='\033[1;33m'
GREEN='\033[1;32m'
NC='\033[0m'

# 1. Define Custom Paths (The Black Box)
export RUSTUP_HOME="$HOME/.programming/rust/multirust"
export CARGO_HOME="$HOME/.programming/rust/cargo"

echo -e "${BLUE}    LOG:${YELLOW} Setting up Rust (Rustup) in ${CARGO_HOME}...${NC}"

# 2. Install Rustup (if missing)
if [ ! -f "$CARGO_HOME/bin/rustup" ]; then
    echo -e "${BLUE}    LOG:${YELLOW} Installing Rustup to custom path...${NC}"
    
    # Create parent dirs to be safe
    mkdir -p "$RUSTUP_HOME" "$CARGO_HOME"
    
    # Install: --no-modify-path keeps your .zshrc clean (we manage it manually)
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --no-modify-path
else
    echo -e "${GREEN}    LOG: Rustup already installed in custom path.${NC}"
fi

# 3. Source Environment
# This loads cargo into the PATH for the rest of this script
if [ -f "$CARGO_HOME/env" ]; then
    source "$CARGO_HOME/env"
fi

# 4. Verify and Update
if command -v cargo &> /dev/null; then
    echo -e "${BLUE}    LOG:${YELLOW} Updating toolchain...${NC}"
    rustup default stable
    rustup update
    
    # CRITICAL FOR LEARNING: Install source code for the standard library
    # This allows you to inspect 'std' code in your IDE (VS Code/Neovim)
    echo -e "${BLUE}    LOG:${YELLOW} Installing rust-src for 'Go to Definition'...${NC}"
    rustup component add rust-src

    echo -e "${GREEN}    LOG: Rust setup complete. $(cargo --version)${NC}"
else
    echo -e "${RED}    ERROR: Cargo not found in PATH. Check CARGO_HOME.${NC}"
    exit 1
fi