# Reference module image on the CAPTF OpenTofu base (see
# module-author/base-images.md). Run from your module's root
# directory:
#
#   podman build -f Containerfile.opentofu \
#     --build-arg BASE=ghcr.io/captf-io/opentofu-base:1.12.7@sha256:<digest> \
#     --build-arg ROLE=machine \
#     --build-arg IMAGE_SOURCE=https://github.com/<org>/<repo> \
#     --build-arg IMAGE_REVISION="$(git rev-parse HEAD)" \
#     --build-arg IMAGE_VERSION=<tag> -t <registry>/<repo>:<tag> .
#
# The image tag is the module version. Lint the module first and the image
# after:
#   tfcapi-lint module . --role machine --strict
#   tfcapi-lint image <registry>/<repo>:<tag> --role machine --strict
#
# Add a .dockerignore (podman reads it too) with at least `.terraform/`,
# `*.tfstate*` and the Containerfile itself, so none of them lands in
# /captf/module.
#
# BASE has no default, so a build never silently uses a stale base: pass it,
# pinned by digest for reproducible builds (find the digest with
# `skopeo inspect --format '{{.Digest}}' docker://<image>:<version>`):
#   --build-arg BASE=ghcr.io/captf-io/opentofu-base:1.12.7@sha256:<digest>
# Dependabot bumps a pin of this form.
ARG BASE

# Optional but recommended: hermetic provider mirror for every platform the
# image publishes. Needs registry egress at build time; drop this stage (and
# the COPY --from=mirror below) for an image whose `init` downloads
# providers at run time.
FROM ${BASE} AS mirror
# The base runs as 65532; writing /captf/providers needs root in this stage,
# which is not shipped.
USER root
WORKDIR /src
COPY . .
# get: `providers mirror` refuses a module whose nested local modules are not
# installed; get installs them (no providers), in this stage only.
# mkdir: `providers mirror` does not create the target when the module
# requires no providers, and the COPY --from=mirror below needs it.
RUN tofu get \
 && mkdir -p /captf/providers \
 && tofu providers mirror -platform=linux_amd64 -platform=linux_arm64 /captf/providers

# The final stage starts from the base again, so it runs as the base's
# non-root user (captf, 65532:65532).
FROM ${BASE}
ARG ROLE
ARG IMAGE_SOURCE=""
ARG IMAGE_REVISION=""
ARG IMAGE_VERSION=""
COPY --from=mirror --chown=65532:65532 /captf/providers /captf/providers
COPY --chown=65532:65532 . /captf/module
# io.captf.contract, io.captf.runtime and io.captf.runtime.version come from
# the base.
LABEL io.captf.role="${ROLE}" \
      org.opencontainers.image.source="${IMAGE_SOURCE}" \
      org.opencontainers.image.revision="${IMAGE_REVISION}" \
      org.opencontainers.image.version="${IMAGE_VERSION}"
