{%- macro mount_cache(target, extra_args="") -%}--mount=type=cache,target={{ target }}{{ extra_args }}{%- endmacro -%}

{%- macro RUN(enable_buildkit=True) -%}
{% if not enable_buildkit %}RUN {% else -%}RUN {{ caller() }} {%- endif -%}
{%- endmacro -%}

{%- macro setup_conda(python_version, bento_path, conda_path=None, enable_buildkit=True) -%}
{% set environment_yml=expands_bento_path("env", "conda", "environment.yml", bento_path=bento_path) %}
{% if conda_path is none -%}
{% set conda_path = ["/opt", "conda"] | join("/") -%}
{% endif -%}
{% set __conda_exec__ = [conda_path, "bin", "conda"] | join("/") %}
{% set __conda_pkg__ = [conda_path, "pkg"] | join("/") %}

{% call RUN(enable_buildkit) -%} {{ mount_cache(__conda_pkg__) }} {% endcall -%} set -eux && \
    echo "Installing Python {{ python_version }} with conda..." && \
    {{ __conda_exec__ }} install -y -n base pkgs/main::python={{ python_version }} pip

{% call RUN(enable_buildkit) -%} {{ mount_cache(__conda_pkg__) }} {% endcall -%} set -eux && \
    if [ -f {{ environment_yml }} ]; then \
      # set pip_interop_enabled to improve conda-pip interoperability. Conda can use
      # pip-installed packages to satisfy dependencies.
      echo "Updating conda base environment with environment.yml"; \
      {{ __conda_exec__ }} config --set pip_interop_enabled True; \
      {{ __conda_exec__ }} env update -n base -f {{ environment_yml }}; \
      {{ __conda_exec__ }} clean --all; \
    fi

{%- endmacro -%}
