#!/bin/sh

set -eux

chown -R 0:0 tmp/sysroot
chcon -R system_u:object_r:usr_t:s0 tmp/sysroot/composefs
chcon system_u:object_r:var_t:s0 tmp/sysroot/state/deploy/*/var
chcon system_u:object_r:etc_t:s0 tmp/sysroot/state/deploy/*/etc/*

definitions='tmp/repart.d'
export SYSTEMD_REPART_MKFS_OPTIONS_EXT4='-O verity'

mkdir -p "$definitions"

cat <<EOF > tmp/repart.d/01-esp.conf
[Partition]
Type=esp
Format=vfat
CopyFiles=/efi:/
SizeMinBytes=512M
SizeMaxBytes=512M
EOF

if [ "${FS_VERITY_MODE:-repart}" = 'repart' ]; then
    COPY_FILES_FLAG="/sysroot:/:fsverity=copy"
fi

cat <<EOF > tmp/repart.d/02-sysroot.conf
[Partition]
Type=root
Format=${FS_FORMAT:-ext4}
SizeMinBytes=10G
SizeMaxBytes=10G
CopyFiles=${COPY_FILES_FLAG:-/sysroot:/}
EOF

# Setting TMPDIR here has a couple of advantages:
#  - we already have our own temporary directory
#  - systemd-repart can copy the files faster when they are in the same partition
#  - we already know that this partition supports fs-verity (/var/tmp might not)
TMPDIR="${PWD}/tmp" systemd-repart \
    --empty=create \
    --size=auto \
    --dry-run=no \
    --no-pager \
    --offline=yes \
    --root=tmp \
    --definitions="${definitions}" \
    "$1"

if [ "${FS_VERITY_MODE:-repart}" = 'fix' ]; then
    "${0%/*}/fix-verity/fix-verity" "$1"
fi
