#!/usr/bin/bash
# SCLS Environment Activation Script
# Flavor: gcc
# Generated by scls-environment

# Determine SCLS root from script location
SCLS="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
export SCLS

# Function to remove specific paths from a colon-separated variable
_scls_remove_from_var() {
    local var_name=$1
    local pattern=$2
    if [[ -n "${!var_name}" ]]; then
        IFS=':' read -ra paths <<< "${!var_name}"
        local new_paths=()
        for path in "${paths[@]}"; do
            if [[ ! $path =~ $pattern ]]; then
                new_paths+=("$path")
            fi
        done
        export "$var_name"="$(IFS=:; echo "${new_paths[*]}")"
    fi
}

# Function to safely prepend to any colon-separated variable
_scls_add_to_var() {
    local var_name=$1
    local new_path=$2
    if [[ ":${!var_name}:" != *":$new_path:"* ]]; then
        if [[ -z "${!var_name}" ]]; then
            export "$var_name"="$new_path"
        else
            export "$var_name"="$new_path:${!var_name}"
        fi
    fi
}

# Remove any existing SCLS paths (allows switching between flavors)
_scls_remove_from_var PATH '^/opt/scls/'
_scls_remove_from_var PKG_CONFIG_PATH '^/opt/scls/'
_scls_remove_from_var CMAKE_PREFIX_PATH '^/opt/scls/'
_scls_remove_from_var LD_LIBRARY_PATH '^/opt/scls/'
_scls_remove_from_var DYLD_LIBRARY_PATH '^/opt/scls/'

# Core paths (always set if directories exist)
[[ -d "$SCLS/bin" ]] && _scls_add_to_var PATH "$SCLS/bin"
[[ -d "$SCLS/lib/pkgconfig" ]] && _scls_add_to_var PKG_CONFIG_PATH "$SCLS/lib/pkgconfig"
[[ -d "$SCLS/lib/cmake" ]] && _scls_add_to_var CMAKE_PREFIX_PATH "$SCLS"

# Package-specific environment variables (only if package is installed)
# Check registry for installed packages

# PETSc
if [[ -f "$SCLS/share/scls/registry/petsc.yaml" ]]; then
    export PETSC_DIR="$SCLS"
    export PETSC_ARCH=""
fi

# SLEPc (depends on PETSc)
if [[ -f "$SCLS/share/scls/registry/slepc.yaml" ]]; then
    export SLEPC_DIR="$SCLS"
fi

# MPI (OpenMPI or MPICH)
if [[ -f "$SCLS/share/scls/registry/openmpi.yaml" ]]; then
    export MPI_HOME="$SCLS"
    export PRTE_MCA_hwloc_default_binding_policy=none
elif [[ -f "$SCLS/share/scls/registry/mpich.yaml" ]]; then
    export MPI_HOME="$SCLS"
    export HYDRA_BINDING=none
fi

# Read flavor from config
_scls_config="$SCLS/share/scls/config.yaml"
if [[ -f "$_scls_config" ]]; then
    SCLS_FLAVOR=$(grep '^flavor:' "$_scls_config" | cut -d' ' -f2)
    export SCLS_FLAVOR
fi

# Clean up internal functions (keep them available for deactivate)
# Users shouldn't call these directly
clear
echo "     ▜"
echo " ▛▘▛▘▐ ▛▘    Scientific Core Library Stack 2026 [${SCLS_FLAVOR:-unknown}]"
echo " ▄▌▙▖▐▖▄▌    Type 'scls help' for commands and environment details."
echo ""
