#!/bin/sh
. /usr/share/debconf/confmodule

log() {
	logger -t grub-installer "$@"
}

findfs () {
	mount | grep "on /target${1%/} " | cut -d' ' -f1
}

findfstype () {
	mount | grep "on /target${1%/} " | cut -d' ' -f5
}

is_sataraid () {
	if type dmraid >/dev/null 2>&1; then
		for frdisk in $(dmraid -s -c | grep -v "No RAID disks"); do
			if echo "$1" | grep -q "/$frdisk[0-9]\+"; then
				return 0
			fi
		done
	fi
	return 1
}

is_multipath () {
	if type multipath >/dev/null 2>&1; then
		for frdisk in $(multipath -l 2>/dev/null | grep '^mpath[0-9]\+ ' | cut -d ' ' -f 1); do
			if echo "$1" | grep -q "^/dev/mapper/${frdisk}-part[0-9]\+"; then
				return 0
			fi
		done
	fi
	return 1
}

ARCH="$(archdetect)"

case $ARCH in
    i386/mac|amd64/mac)
	# Note: depends on partman-efi to load the efivars module!
	if [ -d /sys/firmware/efi ]; then
		log "GRUB not yet usable on Intel-based Macs booted using EFI"
		exit 1
	fi
	;;
    powerpc/chrp_pegasos)
	;;
    powerpc/*)
	log "GRUB not yet usable on PowerPC systems other than Pegasos/Efika"
	exit 1
	;;
esac

bootfs=$(findfs /boot)
[ -n "$bootfs" ] || bootfs="$(findfs /)"

if [ -z "$bootfs" ]; then
	# Probably not yet mounted.
	exit 0
fi

# Check for the control file to work around lvdisplay refusal to work with
# certian lvm device names.
if lvdisplay "$bootfs" | grep -q 'LV Name' 2>/dev/null || [ -e "$(dirname $bootfs)/control" ]; then
	if ! is_sataraid $bootfs && ! is_multipath $bootfs; then
		log "/boot is a lvm volume ($bootfs), cannot install grub"
		exit 1
	fi
fi

bootfstype=$(findfstype /boot)
[ -n "$bootfstype" ] || bootfstype="$(findfstype /)"

db_get grub-installer/skip
if [ "$RET" = true ]; then
	exit 1
fi

exit 0
