#!/bin/sh -e

. /lib/partman/definitions.sh

# Verify that /boot is on an ext2 partition on a disk using BSD
# disklabels, so that the system will actually be bootable.

(modprobe srm_env || true) 2> /dev/null
if [ ! -f /proc/srm_environment/named_variables/booted_dev ]
then
	# No need for us to check anything more -- aboot won't work here
	# anyway.  This is a problem for whatever installs milo.
	exit 0
fi

get_aboot_root_boot() {
	(for i in /lib/partman/fstab.d/*; do
		[ -x "$i" ] || continue
		$i
	done) | 
	while read fs mp type options dump pass
	do
		if [ "$mp" = / ]; then
			echo "root_type=$type; root_fs=$fs;"
		elif [ "$mp" = /boot ]; then
			echo "boot_type=$type; boot_fs=$fs;"
		fi
	done
}

eval "$(get_aboot_root_boot)"

if [ -z "$boot_fs" ]
then
	boot_fs=$root_fs
	boot_type=$root_type
fi

disk=
for dev in $DEVICES/*
do
	[ -d "$dev" ] || continue
	cd $dev
	partitions=
	open_dialog PARTITIONS
	while { read_line num id size type fs path name; [ "$id" ]; }; do
		if [ -d $id -a "$path" = "$boot_fs" ]; then
			ourdev=$dev
			disk="$(cat ${dev}/device)"
		fi
	done
	close_dialog

	[ -z "$disk" ] || break
done

# If we can't figure out the parent dev, let it slide for now.
if [ -n "$disk" ]
then
	cd $ourdev
	open_dialog PARTITIONS
	while { read_line num id size type fs path name; [ "$id" ]; }; do
		start=${id%-*}
		if [ "$(($start/1024))" -le 1 -a -d "$id" ]; then
			if [ "$(cat $id/method)" = "aboot" ]; then
				partnum="$num"
			else
				non_aboot_partition=yes
			fi
		fi
	done
	close_dialog

	if [ -n "$non_aboot_partition" ]; then
		db_input critical aboot-installer/no-space-for-aboot
		db_go
		db_get aboot-installer/no-space-for-aboot
		if [ "$RET" = "false" ]; then
			exit 1
		fi
	fi

	label=$(parted "$disk" print | sed -n 's/Disk label type: //p')
	if [ "$label" != "bsd" ]; then
		. /usr/share/debconf/confmodule

		db_input critical aboot-installer/non-bsd-partitions
		db_go
		db_get aboot-installer/non-bsd-partitions
		if [ "$RET" = "false" ]; then
			exit 1
		fi
	fi

fi

if [ "$boot_type" != "ext2" ]
then
	. /usr/share/debconf/confmodule

	db_subst aboot-installer/non-ext2-boot PARTTYPE $boot_type 
	db_input critical aboot-installer/non-ext2-boot
	db_go
	db_get aboot-installer/non-ext2-boot
	if [ "$RET" = "false" ]; then
		exit 1
	fi
fi

# Save the number of our aboot dummy partition, so we have it
# later when parted_server is no longer available
if [ -n "$partnum" ]; then
	mkdir -p /var/lib/aboot-installer
	echo $partnum > /var/lib/aboot-installer/aboot-partnum
else
	rm -f /var/lib/aboot-installer/aboot-partnum
fi
