#!/bin/sh

set -eu

cat <<'EOF' >>/sysroot/etc/fstab
/run/mnt/data /writable none bind,x-initrd.mount 0 0
EOF

# in recovery mode on hybrid systems, snap-bootstrap generates passwd, shadow,
# group, and gshadow files in /run/snapd/hybrid-users. these files contain users
# imported from the host system mixed with the default users from the base snap
# that is used for recovery mode.
mode="$(/usr/libexec/core/get-mode mode)" || mode="$(/usr/libexec/core/get-arg snapd_recovery_mode)" || mode="unknown"
if [ -f /run/snapd/hybrid-users/passwd ] && [ "${mode}" = "recover" ]; then
    cat <<'EOF' >>/sysroot/etc/fstab
/run/snapd/hybrid-users/passwd /etc/passwd none bind 0 0
/run/snapd/hybrid-users/shadow /etc/shadow none bind 0 0
/run/snapd/hybrid-users/group /etc/group none bind 0 0
/run/snapd/hybrid-users/gshadow /etc/gshadow none bind 0 0
EOF
fi

# If there is a drivers tree, snap-bootstrap will not have mounted the kernel
# snap on /run/mnt/kernel and it will have taken care of mounting the drivers
# tree in /lib/{firmware,modules}.
if ! mountpoint /run/mnt/kernel; then
    exit 0
fi

# Otherwise, mount /lib/{firmware,modules} directly from directories in the
# kernel snap. This will happen on install/recover modes.

cat <<'EOF' >>/sysroot/etc/fstab
/run/mnt/kernel/firmware /usr/lib/firmware none bind,x-initrd.mount 0 0
/run/mnt/kernel/modules /usr/lib/modules none bind,x-initrd.mount 0 0
EOF

for subdir in firmware modules; do
    drop_d=/etc/systemd/system/sysroot-usr-lib-"$subdir".mount.d
    mkdir -p "$drop_d"
    cat <<EOF >"$drop_d"/what.conf
[Mount]
# systemd-fstab-generator tries to be smart and uses
# /sysroot/run/mnt/kernel/$subdir, so we need to set the path
What=/run/mnt/kernel/$subdir
EOF
done
