# shellcheck shell=bash
# Shared helpers for tersler scripts. Source, don't execute.

JR_ETC=${JR_ETC:-/etc/tersler}

jr_log()  { printf '\033[1;34m[tersler]\033[0m %s\n' "$*" >&2; }
jr_warn() { printf '\033[1;33m[tersler] WARN:\033[0m %s\n' "$*" >&2; }
jr_die()  { printf '\033[1;31m[tersler] ERROR:\033[0m %s\n' "$*" >&2; exit 1; }

# Load config: explicit JR_CONF, else /etc/tersler, else the repo copy next to us.
jr_load_config() {
    local here repo_conf
    here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
    repo_conf="$here/../install/tersler.conf"
    if [[ -n ${JR_CONF:-} ]]; then
        # shellcheck source=/dev/null
        source "$JR_CONF"
    elif [[ -f $JR_ETC/tersler.conf ]]; then
        # shellcheck source=/dev/null
        source "$JR_ETC/tersler.conf"
        # shellcheck source=/dev/null
        [[ -f $JR_ETC/tersler.local.conf ]] && source "$JR_ETC/tersler.local.conf"
    elif [[ -f $repo_conf ]]; then
        # shellcheck source=/dev/null
        source "$repo_conf"
        # shellcheck source=/dev/null
        [[ -f ${repo_conf%.conf}.local.conf ]] && source "${repo_conf%.conf}.local.conf"
    else
        jr_die "no configuration found (looked in \$JR_CONF, $JR_ETC, $repo_conf)"
    fi
    : "${MODEL_FILE:=${MODEL_URL##*/}}"
    MODEL_FILE=${MODEL_FILE%%\?*}
    : "${MMPROJ_FILE:=${MMPROJ_URL##*/}}"
    MMPROJ_FILE=${MMPROJ_FILE%%\?*}
}

jr_model_path() { printf '%s/%s' "$JR_MODEL_DIR" "$MODEL_FILE"; }

jr_p2p_enabled() {
    case ${LLAMA_P2P:-auto} in
        1) return 0 ;;
        0) return 1 ;;
        *) grep -qw 'iommu=pt' /proc/cmdline ;;
    esac
}

jr_nvsmi() { command -v nvidia-smi >/dev/null || jr_die "nvidia-smi not found (driver not installed?)"; nvidia-smi "$@"; }
