#!/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

mode="$(/usr/libexec/core/get-mode mode)" || mode="$(/usr/libexec/core/get-arg snapd_recovery_mode)" || mode="unknown"

# 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 [ "${mode}" = "run" ]; 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
    elif [ -f /run/mnt/ubuntu-seed/piboot/ubuntu/piboot.conf ]; then
        echo '/run/mnt/ubuntu-seed/piboot/ubuntu /boot/piboot none bind 0 0' >> /run/image.fstab
    fi
fi
mount -o bind /run/image.fstab /sysroot/etc/fstab
umount -lf /sysroot/run
