#!/bin/sh

set -eux

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

../common/check-config

case "${os}" in
    fedora)
        containerfile='Containerfile'
        cargo build --release
        ;;
    arch)
        containerfile='Containerfile.arch'
        cargo build --release
        ;;
    rhel9)
        containerfile='Containerfile.rhel9'
        cargo build --release --features=rhel9
        ;;
    ubuntu)
        containerfile='Containerfile.ubuntu'
        cargo build --release
        ;;
    rawhide)
        containerfile='Containerfile.rawhide'
        cargo build --release
        ;;
    fedora-compat)
        # try a variant using the old mount APIs with a new kernel
        containerfile='Containerfile'
        cargo build --release --features=pre-6.15
        ;;
    *)
        echo "*** unknown variant ${os}"
        false
        ;;
esac

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

podman build \
    --iidfile=tmp/base.iid \
    -f "${containerfile}" \
    .

BASE_ID="$(cat tmp/base.iid)"

${CFSCTL} oci pull "containers-storage:${BASE_ID}"

if [ "${FS_VERITY_MODE:-repart}" = "none" ]; then
    CFSCTL="$CFSCTL --insecure"
fi

${CFSCTL} oci prepare-boot "@${BASE_ID}" --bootdir tmp/efi --entry-id=example --cmdline rw

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