#!/usr/bin/bash
set -euo pipefail

# During split-/usr initrd boot, the authenticated system /usr is commonly
# mounted below /sysusr.
if [[ -d /sysusr/usr/lib/repart.d ]]; then
    source_root=/sysusr
elif [[ -d /sysroot/usr/lib/repart.d ]]; then
    source_root=/sysroot
else
    echo 'image: authenticated /usr is unavailable to systemd-repart' >&2
    exit 1
fi

# Native reset detection authorizes erasure. Recreate USER in this same boot
# with the bootstrap key, exactly as on normal first boot.
reset_options=(--defer-partitions-factory-reset=no)
disk="$(/usr/lib/image-boot-disk)"
key_options=()
if [[ -e /run/image-user-provision.required ]]; then
    [[ -s /run/image-user-provision.key ]] || {
        echo 'image: provisioning requested without a bootstrap key; refusing repart' >&2
        exit 1
    }
    key_options=(--key-file=/run/image-user-provision.key)
else
    # Never let failure to discover an existing USER turn into keyless volume
    # creation. Re-check immediately before normal partition maintenance.
    /usr/lib/image-user-device >/dev/null || {
        echo 'image: ordinary boot requires an existing encrypted USER; refusing repart' >&2
        exit 1
    }
fi
echo "image: provisioning partitions on boot-loader disk ${disk}" >&2

exec systemd-repart --dry-run=no \
    --definitions="${source_root}/usr/lib/repart.d" \
    --copy-source="${source_root}" \
    "${key_options[@]}" \
    "${reset_options[@]}" "${disk}"
