#!/usr/bin/env bash
# Source this script to set up and activate the Python venv.
# Installs crudini into the venv if not already present.
#
# Requires: BASEDIR set, bash-helpers loaded (log, end available)
#
# Usage:
#   . $BASEDIR/libexec/venv-setup || exit 1

_venv="$BASEDIR/venv"

# A system crudini (e.g. the Debian package) needs no venv
if [ ! -f "$_venv/bin/activate" ] && command -v crudini >/dev/null 2>&1; then
	unset _venv
	return 0
fi

_python=$(which python3 || which python 2>/dev/null) ||
	end $? "Python not found — install python3"

if [ ! -f "$_venv/bin/activate" ]; then
	debug "Creating Python venv at $_venv"
	"$_python" -m venv --prompt "$("$_python" --version 2>&1 | tr -d ' ')" "$_venv" ||
		end $? "Could not create Python venv"
fi

. "$_venv/bin/activate" ||
	end $? "Could not activate Python venv at $_venv"

if ! which crudini >/dev/null 2>&1; then
	debug "Installing crudini in venv"
	pip install crudini ||
		end $? "Could not install crudini in venv"
fi

unset _venv _python
