#!/usr/bin/env bash
# shellcheck shell=bash
#
# Sources `.env` (auto-generates via `python -m cli.meta.env` if missing)
# with setdefault semantics: caller-set values win over `.env` defaults.
# Idempotent (INFINITO_ENV_LOADED). INFINITO_ENV_GENERATING short-circuits
# re-entry from generator subshells (BASH_ENV would otherwise recurse).
# PYTHON/PATH are re-resolved on every source so a venv created mid-chain wins;
# caller-set values are snapshotted and restored after the bulk .env source.
# INFINITO_CONTAINER, INFINITO_PARENT_IMAGE and INFINITO_IMAGE derive from the
# distro: a caller INFINITO_DISTRO other than the one `.env` was generated for
# loads a set generated for that distro instead, and `.env` stays untouched.

# zsh cannot run this loader's bash-isms (BASH_SOURCE, ${!indirect}, assoc-array
# key expansion). When sourced from zsh, delegate to bash and import the
# resulting INFINITO_*/PYTHON/VENV/PATH back into the current shell. The zsh-only
# ${(%):-%x} (this file's path) is hidden behind eval so bash still parses fine.
if [ -n "${ZSH_VERSION:-}" ]; then
	_infinito_zsh_self=""
	eval '_infinito_zsh_self=${(%):-%x}'
	_infinito_zsh_root="$(cd "$(dirname "${_infinito_zsh_self}")/../../.." && pwd)"
	while IFS= read -r _infinito_zsh_line; do
		case "${_infinito_zsh_line}" in
		INFINITO_*=* | PYTHON=* | VENV=* | PATH=*)
			_infinito_zsh_key="${_infinito_zsh_line%%=*}"
			_infinito_zsh_val="${_infinito_zsh_line#*=}"
			export "${_infinito_zsh_key}=${_infinito_zsh_val}"
			;;
		esac
	done < <(bash -c "source '${_infinito_zsh_root}/scripts/meta/env/load.sh' >/dev/null 2>&1; env") # nocheck: self-path-reference
	unset _infinito_zsh_self _infinito_zsh_root _infinito_zsh_line \
		_infinito_zsh_key _infinito_zsh_val
	return 0
fi

_infinito_env_repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
_infinito_env_dotenv="${_infinito_env_repo_root}/.env"

# shellcheck source=scripts/meta/env/python.sh
source "${_infinito_env_repo_root}/scripts/meta/env/python.sh"

if [[ -n "${VENV:-}" && -d "${VENV%/}/bin" ]]; then
	case ":${PATH:-}:" in
	*:"${VENV%/}/bin":*) ;;
	*) export PATH="${VENV%/}/bin${PATH:+:${PATH}}" ;;
	esac
fi

_infinito_env_mtime="$(stat -c %Y "${_infinito_env_dotenv}" 2>/dev/null || echo 0)"
if [[ "${INFINITO_ENV_LOADED:-}" == "1" && "${INFINITO_ENV_LOADED_MTIME:-}" == "${_infinito_env_mtime}" && "${INFINITO_ENV_LOADED_DISTRO:-}" == "${INFINITO_DISTRO:-}" ]]; then # nocheck: env-loader-internal-guard
	unset _infinito_env_repo_root _infinito_env_dotenv _infinito_env_mtime
	return 0
fi
if [[ "${INFINITO_ENV_GENERATING:-}" == "1" ]]; then # nocheck: env-loader-internal-guard
	unset _infinito_env_repo_root _infinito_env_dotenv _infinito_env_mtime
	return 0
fi

if [[ -n "${INFINITO_ENV_LOADED_DISTRO:-}" && "${INFINITO_ENV_LOADED_DISTRO}" != "${INFINITO_DISTRO:-}" ]]; then # nocheck: env-loader-internal-guard
	unset INFINITO_CONTAINER INFINITO_PARENT_IMAGE INFINITO_IMAGE
fi

_infinito_env_source="${_infinito_env_dotenv}"
_infinito_env_scratch=""
_infinito_env_distro="${INFINITO_DISTRO:-}"
if [[ -f "${_infinito_env_dotenv}" && -n "${_infinito_env_distro}" && "${_infinito_env_distro}" != "$(sed -n 's/^INFINITO_DISTRO=//p' "${_infinito_env_dotenv}")" ]]; then
	_infinito_env_scratch="$(mktemp -d)"
	_infinito_env_source="${_infinito_env_scratch}/env"
fi

if [[ ! -f "${_infinito_env_source}" ]]; then
	(
		cd "${_infinito_env_repo_root}" || exit 1
		export INFINITO_ENV_GENERATING=1
		"${PYTHON}" -m cli.meta.env --output "${_infinito_env_source}"
	) >&2
fi

declare -A _infinito_env_preserved=()
while IFS= read -r _infinito_env_line; do
	case "${_infinito_env_line}" in
	"" | "#"*) continue ;;
	esac
	_infinito_env_key="${_infinito_env_line%%=*}"
	if [[ "${_infinito_env_key}" == "${_infinito_env_line}" ]]; then
		continue
	fi
	if [[ -n "${!_infinito_env_key:-}" ]]; then
		_infinito_env_preserved["${_infinito_env_key}"]="${!_infinito_env_key}"
	fi
done <"${_infinito_env_source}"
unset _infinito_env_line _infinito_env_key

set -a
# shellcheck disable=SC1090
source "${_infinito_env_source}"
set +a

if [[ -n "${_infinito_env_scratch}" ]]; then
	rm -rf "${_infinito_env_scratch}"
fi
unset _infinito_env_source _infinito_env_scratch _infinito_env_distro

for _infinito_env_key in "${!_infinito_env_preserved[@]}"; do
	declare -gx "${_infinito_env_key}=${_infinito_env_preserved[${_infinito_env_key}]}"
done
unset _infinito_env_key _infinito_env_preserved

if [[ -z "${REQUESTS_CA_BUNDLE:-}" ]]; then
	for _infinito_env_ca in ${INFINITO_CA_BUNDLE_CANDIDATES}; do
		if [[ -r "${_infinito_env_ca}" ]]; then
			export REQUESTS_CA_BUNDLE="${_infinito_env_ca}"
			export SSL_CERT_FILE="${SSL_CERT_FILE:-${_infinito_env_ca}}"
			break
		fi
	done
	unset _infinito_env_ca
fi

export INFINITO_ENV_LOADED="1"
_infinito_env_mtime="$(stat -c %Y "${_infinito_env_dotenv}" 2>/dev/null || echo 0)"
export INFINITO_ENV_LOADED_MTIME="${_infinito_env_mtime}"
export INFINITO_ENV_LOADED_DISTRO="${INFINITO_DISTRO:-}"
unset _infinito_env_repo_root _infinito_env_dotenv _infinito_env_mtime
