#! /bin/sh -e

. /usr/share/debconf/confmodule

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

mountvirtfs () {
	fstype="$1"
	path="$2"
	if grep -q "[[:space:]]$fstype\$" /proc/filesystems && \
	   ! grep -q "^[^ ]\+ \+$path " /proc/mounts; then
		mkdir -p "$path" || \
			die grub-installer/mounterr "Error creating $path"
		mount -t "$fstype" "$fstype" "$path" || \
			die grub-installer/mounterr "Error mounting $path"
		EXTRA_PATHS="$EXTRA_PATHS $path"
		trap "umount $EXTRA_PATHS" HUP INT QUIT KILL PIPE TERM EXIT
	fi
}



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 || true
if [ -e /target/boot/efi ]; then
    chroot /target mount /boot/efi || true
    EXTRA_PATHS="$EXTRA_PATHS /target/boot/efi"
fi
if [ -n "$EXTRA_PATHS" ]; then
    trap "umount $EXTRA_PATHS" HUP INT QUIT KILL PIPE TERM EXIT
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
	if chroot /target grub-install -h 2>&1 | grep -q no-floppy; then
		grub_install_params="$grub_install_params --no-floppy"
	fi
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
