#!/bin/bash

# Path: scripts/rust.sh

set -e

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

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}"

if [ ! -f "$CARGO_HOME/bin/rustup" ]; then
    echo -e "${BLUE}    LOG:${YELLOW} Installing Rustup to custom path...${NC}"
    mkdir -p "$RUSTUP_HOME" "$CARGO_HOME"
    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

if [ -f "$CARGO_HOME/env" ]; then
    source "$CARGO_HOME/env"
fi

if command -v cargo &> /dev/null; then
    echo -e "${BLUE}    LOG:${YELLOW} Updating toolchain...${NC}"
    rustup default stable
    rustup update
    
    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