#!/usr/bin/env bash
# Configure the environment for MVGAL Vulkan aggregation.
#
# Primary path: MVGAL Vulkan ICD (single virtual VkPhysicalDevice).
# Secondary:    VK_LAYER_MVGAL for submit-time scheduling (AFR/SFR/hybrid).
#
# Usage:
#   source scripts/mvgal-vulkan-env.sh
#   # or
#   eval "$(scripts/mvgal-vulkan-env.sh --export)"
#
# SPDX-License-Identifier: MIT

set -euo pipefail

MVGAL_PREFIX="${MVGAL_PREFIX:-/usr/local}"
EXPORT_MODE=0

if [[ "${1:-}" == "--export" ]]; then
    EXPORT_MODE=1
fi

_emit() {
    if [[ "$EXPORT_MODE" -eq 1 ]]; then
        printf '%s\n' "$1"
    else
        eval "$1"
    fi
}

_find_icd_json() {
    local candidate
    for candidate in \
        "${MVGAL_ICD_JSON:-}" \
        "$MVGAL_PREFIX/share/vulkan/icd.d/mvgal_icd.json" \
        "/usr/local/share/vulkan/icd.d/mvgal_icd.json" \
        "/usr/share/vulkan/icd.d/mvgal_icd.json" \
        "$HOME/.local/share/vulkan/icd.d/mvgal_icd.json"; do
        if [[ -n "$candidate" && -f "$candidate" ]]; then
            echo "$candidate"
            return 0
        fi
    done
    return 1
}

_find_layer_json() {
    local candidate
    for candidate in \
        "${MVGAL_LAYER_JSON:-}" \
        "$MVGAL_PREFIX/share/vulkan/implicit_layer.d/VK_LAYER_MVGAL.json" \
        "/usr/local/share/vulkan/implicit_layer.d/VK_LAYER_MVGAL.json" \
        "/usr/share/vulkan/implicit_layer.d/VK_LAYER_MVGAL.json" \
        "$HOME/.local/share/vulkan/implicit_layer.d/VK_LAYER_MVGAL.json"; do
        if [[ -n "$candidate" && -f "$candidate" ]]; then
            echo "$candidate"
            return 0
        fi
    done
    return 1
}

_emit 'export ENABLE_MVGAL=1'
_emit 'export MVGAL_USE_ICD=1'
_emit 'export MVGAL_VULKAN_ENABLE=1'
# Pass-through by default; set MVGAL_STRATEGY=afr (etc.) or MVGAL_AGGREGATE=1 to enable multi-GPU.
_emit "export MVGAL_STRATEGY=\"\${MVGAL_STRATEGY:-single}\""

if icd_json="$(_find_icd_json)"; then
    _emit "export VK_ICD_FILENAMES=\"$icd_json\""
    _emit "export VK_DRIVER_FILES=\"$icd_json\""
else
    echo "[mvgal-vulkan-env] warning: mvgal_icd.json not found; using vendor ICDs + layer" >&2
fi

if layer_json="$(_find_layer_json)"; then
    _emit "export VK_LAYER_PATH=\"$(dirname "$layer_json")\""
fi

# Preserve vendor ICDs as fallback when MVGAL_ICD_ONLY is unset
if [[ "${MVGAL_ICD_ONLY:-1}" == "1" ]]; then
    _emit 'export MVGAL_ICD_ONLY=1'
fi
