#!/bin/sh

set -eux

os="${1:-fedora}"
cd "${0%/*}"

../common/check-config

case "${os}" in
    fedora)
        containerfile='Containerfile'
        ;;
    arch)
        containerfile='Containerfile.arch'
        ;;
    *)
        echo "*** unknown variant ${os}"
        false
        ;;
esac

# https://github.com/containers/buildah/issues/5656
PODMAN_BUILD="podman build --no-cache"

cargo build --release

cp ../../target/release/cfsctl .
cp ../../target/release/composefs-setup-root extra/usr/lib/dracut/modules.d/37composefs/
CFSCTL='./cfsctl --repo tmp/sysroot/composefs'

rm -rf tmp
rm -rf tmp/efi tmp/sysroot/composefs/images
${CFSCTL} init --algorithm=fsverity-sha256-12 --erofs-version 1

${PODMAN_BUILD} \
    --iidfile=tmp/base.iid \
    --target=base \
    -f "${containerfile}" \
    .

BASE_ID="$(cat tmp/base.iid)"
${CFSCTL} oci pull containers-storage:"${BASE_ID}"

# Compute the composefs kernel argument from the repo-side view of the base image.
# Using oci compute-id --bootable gives the same digest that prepare-boot will use
# when processing the final image (both go through transform_for_boot with the repo),
# so the karg baked into the UKI will match what prepare-boot validates.
BASE_BOOTABLE_ID="$(${CFSCTL} oci compute-id --bootable "@${BASE_ID}")"
BASE_KARG="composefs.digest=v1-sha256-12:${BASE_BOOTABLE_ID}"

${PODMAN_BUILD} \
    --iidfile=tmp/final.iid \
    --build-context=base="container-image://${BASE_ID}" \
    --build-arg=COMPOSEFS_KARG="${BASE_KARG}" \
    -f "${containerfile}" \
    .

FINAL_ID="$(cat tmp/final.iid)"
${CFSCTL} oci pull containers-storage:"${FINAL_ID}"
${CFSCTL} oci prepare-boot "@${FINAL_ID}" --bootdir tmp/efi

../common/install-systemd-boot
../common/make-image "${os}-uki-efi.qcow2"
