#! /bin/sh -e

. /usr/share/debconf/confmodule

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

db_progress START 0 2 grub-installer/progress/title
db_progress INFO grub-installer/progress/step_bootdev

# 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
if [ -e /target/boot/efi ]; then
    chroot /target mount /boot/efi && on_exit "umount /target/boot/efi" || true
fi

db_input critical grub-installer/bootdev
if ! db_go; then
	# back up to menu
	db_progress STOP
	exit 10
fi

db_get grub-installer/bootdev
bootdev="$RET"
if echo "$bootdev" | grep -qv '('; then
	mappedbootdev="$(mapdevfs "$bootdev")" || true
	if [ "$mappedbootdev" ]; then
		bootdev="$mappedbootdev"
	fi
fi

db_progress STEP 1
db_subst grub-installer/progress/step_install_loader BOOTDEV "$bootdev"
db_progress INFO grub-installer/progress/step_install_loader

update_mtab

grub_install_params=
if ! is_floppy "$bootdev"; then
	grub_install_params="$grub_install_params --no-floppy"
fi

if chroot /target grub-install --version | grep -q 'GNU GRUB 0'; then
	grub_install_params="$grub_install_params --recheck"
fi

if ! log-output -t grub-installer chroot /target grub-install $grub_install_params "$bootdev"; then
	db_subst grub-installer/grub-install-failed BOOTDEV "$bootdev"
	db_input critical grub-installer/grub-install-failed || true
	db_go || true
	db_progress STOP
	exit 1
fi

db_progress STEP 1
db_progress STOP
