# A special form of Containerfile for composefs-enabled UKI images
# This file must have:
#
#  - a stage called 'base' which contains all of the
#    files of the final image, but not the kernel
#
#  - further stages, ultimately resulting in the final container image.  In
#    this image, the kernel must be present in /boot and otherwise no other
#    changes may be made vs. the base image.  This is best-accomplished with a
#    multi-stage build.
#
#  - during the build stages following 'base', the `COMPOSEFS_KARG` build
#    arg will be set to the composefs kernel argument string (e.g.
#    composefs.digest=v1-sha256-12:<hex>).  This should be baked into the UKI.

FROM fedora:43 AS base
RUN --mount=type=cache,target=/var/cache/libdnf5 <<EOF
    set -eux

    mkdir -p /etc/dracut.conf.d
    echo export DRACUT_NO_XATTR=1 > /etc/dracut.conf.d/no-xattr.conf

    dnf --setopt keepcache=1 install --allowerasing -y \
        btrfs-progs \
        composefs \
        dosfstools \
        kernel \
        openssh-server \
        policycoreutils-python-utils \
        selinux-policy-targeted \
        skopeo \
        strace \
        systemd \
        systemd-boot-unsigned \
        systemd-ukify \
        util-linux
EOF

# --- Everything above this line should hopefully stay cached ---

COPY cfsctl /usr/bin
COPY extra /
COPY test-thing.fedora-42 /
RUN <<EOF
    set -eux

    systemctl enable systemd-networkd

    checkmodule -M -m -o /etc/composefs_workarounds.mod /etc/composefs_workarounds.te
    semodule_package -o /etc/composefs_workarounds.pp -m /etc/composefs_workarounds.mod
    semodule -i /etc/composefs_workarounds.pp

    passwd -d root
    mkdir /sysroot
EOF

FROM base AS kernel
ARG COMPOSEFS_KARG
RUN --mount=type=cache,target=/var/cache/libdnf5 <<EOF
    set -eux

    mkdir -p /etc/kernel /etc/dracut.conf.d
    echo "${COMPOSEFS_KARG} rw" > /etc/kernel/cmdline

    kernel-install add-all
EOF

FROM base AS bootable
COPY --from=kernel /boot /boot
