#!/usr/bin/env bash

cf_create_venv() {
    # Creates a new virtual environment inside $CF_VENV_BASE and makes it relocatable.
    #
    # Arguments:
    #   1. name
    #       The name of the virtual env inside $CF_VENV_BASE.
    #
    # Required environment variables:
    #   CF_VENV_BASE:
    #       The base path where CF virtual environments are stored.

    # zsh options
    local shell_is_zsh="$( [ -z "${ZSH_VERSION}" ] && echo "false" || echo "true" )"
    if ${shell_is_zsh}; then
        emulate -L bash
        setopt globdots
    fi

    # check arguments
    local name="$1"
    if [ -z "${name}" ]; then
        >&2 echo "argument 0 (venv name) must not be empty"
        return "1"
    fi

    # check environment variables
    if [ -z "${CF_VENV_BASE}" ]; then
        >&2 echo "environment variable CF_VENV_BASE must not be empty"
        return "2"
    fi

    # create the venv the usual way, use symlinks with those pointing outside the venv being
    # transformed into copies when making it relocatable
    python3 -m venv --symlinks --upgrade-deps "${CF_VENV_BASE}/${name}" || return "$?"

    # make it relocatable, loosing all relations to the outer env
    cf_make_venv_relocatable "${name}"
}

cf_create_venv "$@"
