# shellcheck shell=bash

# Reference:
# - Documentation of direnv special commands:
#   https://github.com/direnv/direnv/blob/master/stdlib.sh

# Add to PATH
PATH_add bin

# Read in .env file, which may contain ANSIBLE_GALAXY_API_KEY
dotenv_if_exists

if [[ -z "$ANSIBLE_GALAXY_API_KEY" ]]; then
    # Get Ansible Galaxy API key
    # NOTE: secret-from-first is my own script for pulling from a secret manager,
    # e.g. HashiCorp Vault
    if has secret-from-first; then
        ANSIBLE_GALAXY_API_KEY="$(secret-from-first "galaxy.ansible.com/huyz/api_key")" || return 1
        export ANSIBLE_GALAXY_API_KEY
    else
        echo "${BASH_SOURCE[0]}: Warning: secret-from-first not found. Cannot set ANSIBLE_GALAXY_API_KEY." >&2
    fi
fi

# 2023-01-27 Copied from open PR https://github.com/direnv/direnv/issues/592
# https://github.com/direnv/direnv/blob/4f14b5455a55709114720c4febba8399fdcb897c/stdlib.sh
#
# Usage: layout poetry
#
# Similar to layout_python, but uses Poetry [1] to build a virtualenv from the
# pyproject.toml [2] located in the same directory.
#
# Poetry by default will create a virtual environment under
# {cache-dir}/virtualenvs where cache-dir equates to $XDG_CACHE_HOME/pypoetry
# or use the {project-dir}/.venv directory when one is available.
#
# [1]: https://python-poetry.org/
# [2]: https://peps.python.org/pep-0518/
#
layout_poetry() {
    PYPROJECT_TOML="${PYPROJECT_TOML:-pyproject.toml}"
    if [[ ! -f "$PYPROJECT_TOML" ]]; then
        log_status "No pyproject.toml found. Executing \`poetry init\` to create a \`$PYPROJECT_TOML\` first."
        poetry init
    fi

    local REPLY
    if [[ -n "${VIRTUAL_ENV:-}" ]]; then
        realpath.absolute "$VIRTUAL_ENV"
        VIRTUAL_ENV="$REPLY"
        [[ ! -d "$VIRTUAL_ENV" ]] && unset VIRTUAL_ENV
    fi
    if [[ -z "${VIRTUAL_ENV:-}" ]]; then
        if [[ -d ".venv" ]]; then
            realpath.absolute "$VIRTUAL_ENV"
            VIRTUAL_ENV="$REPLY"
        else
            VIRTUAL_ENV="$(poetry env info --path 2>/dev/null; true)"
        fi
    fi

    if [[ -z "$VIRTUAL_ENV" || ! -d "$VIRTUAL_ENV" ]]; then
        log_status "No virtual environment exists. Executing \`poetry install\` to create one."
        poetry install
        VIRTUAL_ENV="$(poetry env info --path)"
    fi

    PATH_add "$VIRTUAL_ENV/bin"
    export POETRY_ACTIVE=1
    export VIRTUAL_ENV
}

export VIRTUAL_ENV=venv
layout pyenv 3.11.1
layout poetry
