#!/bin/sh
umount /sysroot/run/fstab
cp /sysroot/run/image.fstab /run/

# TODO:UC20: move this logic into snap-bootstrap to be incorporated with 
# initramfs-mounts

if grep -q snapd_recovery_mode=run /proc/cmdline; then
    run_mode=1
elif grep -q snapd_recovery_mode=install /proc/cmdline; then
    if grep -q mode=run /run/mnt/ubuntu-data/system-data/var/lib/snapd/modeenv; then
        run_mode=1
    fi
fi


# Always bind-mount all the host filesystems
mkdir -p /run/mnt/host
echo '/run/mnt/host /host none rbind 0 0' >> /run/image.fstab
if [ -n "${run_mode-}" ]; then
    # TODO:UC20: support other bootloaders too
    if [ -f /run/mnt/ubuntu-boot/EFI/ubuntu/grub.cfg ]; then
        echo '/run/mnt/ubuntu-boot/EFI/ubuntu /boot/grub none bind 0 0' >> /run/image.fstab
        # ensure ESP efi dir is available for fwupdate (LP: 1892392)
        echo '/run/mnt/ubuntu-seed/ /boot/efi none bind 0 0' >> /run/image.fstab        
    elif [ -f /run/mnt/ubuntu-boot/uboot/ubuntu/boot.sel ]; then
        echo '/run/mnt/ubuntu-boot/uboot/ubuntu /boot/uboot none bind 0 0' >> /run/image.fstab
    fi
fi
mount -o bind /run/image.fstab /sysroot/etc/fstab
umount -lf /sysroot/run
cp /run/systemd/transient/*.mount /etc/systemd/system
