#! /bin/sh -e

. /usr/share/debconf/confmodule

. /usr/share/grub-installer/functions.sh

_dbg_log() {
	# just having DEBCONF_DEBUG defined is enough to get log() to append the script's name
	DEBCONF_DEBUG=${DEBCONF_DEBUG:-0} log "$@"
}

db_progress START 0 3 grub-installer/progress/title
db_progress INFO grub-installer/progress/step_force_efi_removable

# Should we also install grub-efi to the removable media path?
# Ask the user
_dbg_log "Prompting user about removable media path"
db_input high grub-installer/force-efi-extra-removable
if ! db_go; then
	# back up to menu
	db_progress STOP
	exit 10
fi
db_get grub-installer/force-efi-extra-removable
if [ "$RET" != true ]; then
	db_progress STOP
	exit 0
fi

db_progress STEP 1
db_progress INFO grub-installer/progress/step_mount_filesystems

_dbg_log "Mounting filesystems"
# If we're installing grub-efi, it wants /sys mounted in the
# target. Maybe /proc too, and definitely the efivars fs. Should be
# harmless if we're not using it.
mountvirtfs proc /target/proc
mountvirtfs sysfs /target/sys
modprobe efivarfs >/dev/null 2>&1 || true
mountvirtfs efivarfs /target/sys/firmware/efi/efivars non-fatal
chroot /target mount /boot/efi && on_exit "umount /target/boot/efi" || true

db_progress STEP 1
db_progress INFO grub-installer/progress/step_install_loader
# Do the installation now
_dbg_log "Running grub-install"
if ! chroot /target grub-install --force-extra-removable; then
	db_input critical grub-installer/grub-install-failed || true
	db_go || true
	db_progress STOP
	exit 1
fi

db_progress STEP 1
db_progress INFO grub-installer/progress/step_update_debconf_efi_removable
# And add the debconf flag so the installed system will also do this in future
_dbg_log "Running debconf-set-selections in the chroot"
chroot /target 'debconf-set-selections' <<EOF
grub2/force_efi_extra_removable boolean true
EOF

db_progress STEP 1
db_progress STOP

# Don't need to clean up - the trap calls above will unmount filesystems for us
