#!/bin/bash

# Ensure ~/.local/bin is on PATH
export PATH=$PATH:$HOME/.local/bin

CBDEP=~/.local/bin/cbdep

install_cbdep() {
    # Use uv to install/upgrade cbdep
    uv tool install --python-preference=only-managed --reinstall --quiet cbdep
}

# If cbdep isn't already installed, ensure uv is installed and then use
# it to install cbdep
if [ ! -x ${CBDEP} ]; then

    # If uv isn't already installed, install it - use curl or wget
    if ! command -v uv 2>&1 >/dev/null; then
        if command -v curl 2>&1 >/dev/null; then
            curl -qLsSf https://astral.sh/uv/install.sh | INSTALLER_PRINT_QUIET=1 sh
        elif command -v wget 2>&1 >/dev/null; then
            wget -qO- https://astral.sh/uv/install.sh | INSTALLER_PRINT_QUIET=1 sh
        else
            echo "Either curl or wget is required to install cbdep"
            exit 1
        fi
    fi

    install_cbdep

else

    # If cbdep is installed but more than a couple days old, update it
    if [[ $(find ${CBDEP} -mtime +2 -print) ]]; then
        install_cbdep
    fi

fi

# Invoke cbdep
exec ~/.local/bin/cbdep "$@"
