# This stage is responsible for holding onto
# your config without copying it directly into
# the final image
{%- if self::files_dir_exists() %}
FROM scratch AS stage-files
COPY ./files /files
{%- else if self::config_dir_exists() %}
FROM scratch AS stage-config
COPY ./config /config
{%- else %}
FROM scratch AS stage-files
WORKDIR /files
{% endif %}

{%~ if self::modules_exists() %}
# Copy modules
# The default modules are inside blue-build/modules
# Custom modules overwrite defaults
FROM scratch AS stage-modules
COPY ./modules /modules
{% endif %}

{%- if recipe.should_install_bins() %}
# Bins to install
# These are basic tools that are added to all images.
# Generally used for the build process. We use a multi
# stage process so that adding the bins into the image
# can be added to the ostree commits.
FROM scratch AS stage-bins
  {%- if let Some(version) = recipe.get_cosign_version() %}
COPY --from={{ blue_build_utils::constants::COSIGN_IMAGE_REF }}:{{ version }} \
  /ko-app/cosign /bins/cosign
  {%- endif %}
  {%- if let Some(version) = recipe.get_bluebuild_version() %}
COPY --from={{ blue_build_utils::constants::BLUE_BUILD_IMAGE_REF }}:{{ version }} \
  /out/bluebuild /bins/bluebuild
  {%- endif %}
{%- endif %}

# Keys for pre-verified images
# Used to copy the keys into the final image
# and perform an ostree commit.
#
# Currently only holds the current image's
# public key.
FROM scratch AS stage-keys
{%- if self::has_cosign_file() %}
COPY cosign.pub /keys/{{ recipe.get_name()|replace('/', "_") }}.pub
{% endif %}

{%- include "modules/akmods/akmods.j2" %}

{%- for stage in recipe.get_processed_stages() %}
# {{ stage.name|capitalize }} stage
FROM \
  {%- if let Some(platform) = stage.platform %}
  --platform={{ platform }} \
    {%- endif %}
  {{ stage.from }} AS {{ stage.name }}

ARG TARGETARCH
  {%- if self::should_color() %}
ARG FORCE_COLOR=1
ARG CLICOLOR_FORCE=1
ARG RUST_LOG_STYLE=always
  {%- endif %}

  {%- if stage.from != "scratch" %}
    {%- if let Some(version) = recipe.get_nushell_version() %}
COPY --from={{ blue_build_utils::constants::NUSHELL_IMAGE }}:{{ version }} /nu/* /usr/libexec/bluebuild/nu/
    {%- endif %}
# Add compatibility for modules
RUN {{ scripts_mount("/tmp/scripts/") }} \
  /tmp/scripts/setup.sh

    {%- if self::config_dir_exists() %}
ARG CONFIG_DIRECTORY="/tmp/config"
    {%- else %}
ARG CONFIG_DIRECTORY="/tmp/files"
    {%- endif %}
ARG MODULE_DIRECTORY="/tmp/modules"

    {%- if let Some(shell_args) = stage.shell %}
SHELL [{% for arg in shell_args %}"{{ arg }}"{% if !loop.last %}, {% endif %}{% endfor %}]
    {%- else %}
SHELL ["bash", "-c"]
    {%- endif %}
  {%- endif %}

{{ modules::modules_run(stage.get_processed_modules(), stage.name) }}
{%- endfor %}
