#!/bin/sh
# Sub-tests that require a mounted partition.
. /usr/share/os-prober/common.sh
set -e
partition=$1

parsefstab () {
	while read line; do
		case "$line" in
			"#"*)
				:	
			;;
			*)
				set -- $line
				echo $1 $2 $3
			;;
		esac
	done
}

tmpmnt=/var/lib/os-prober/mount
if [ ! -d $tmpmnt ]; then
	mkdir $tmpmnt
fi

for type in $(grep -v nodev /proc/filesystems); do
	if mount -o ro -t $type $partition $tmpmnt 2>/dev/null; then
		bootpart=""
		if [ -e "$tmpmnt/etc/fstab" ]; then
			# Try to mount any /boot partition.
			bootmnt=$(parsefstab < $tmpmnt/etc/fstab | grep " /boot ") || true
			if [ -n "$bootmnt" ]; then
				set -- $bootmnt
				boottomnt=""
				if [ -e "$1" ]; then
					bootpart="$1"
					boottomnt="$1"
				elif [ -e "$tmpmnt/$1" ]; then
					bootpart="$1"
					boottomnt="$tmpmnt/$1"
				elif [ -e "/target/$1" ]; then
					bootpart="$1"
					boottomnt="/target/$1"
				else
					bootpart=""
				fi

				if [ -z "$bootpart" ]; then
					debg "found boot partition $1 for linux system on $partition, but cannot map to existing device"
				else
					debug "found boot partition $bootpart for linux system on $partition"
					if ! mount -o ro "$boottomnt" $tmpmnt/boot -t "$3"; then
						error "failed to mount $boottomnt on $tmpmnt/boot"
					fi
				fi
			fi
		fi
		if [ -z "$bootpart" ]; then
			bootpart="$partition"
		fi
		
		for test in /usr/lib/linux-boot-probes/mounted/*; do
			if [ -f $test ] && [ -x $test ]; then
				debug "running $test $partition $bootpart $tmpmnt $type"
				if $test $partition $bootpart $tmpmnt $type; then
					debug "$test succeeded"
					umount $tmpmnt/boot 2>/dev/null || true 	
					umount $tmpmnt
					rmdir $tmpmnt || true
					exit 0
				fi
			fi
		done
		
		umount $tmpmnt/boot 2>/dev/null || true 	
		umount $tmpmnt

		break
	fi
done

rmdir $tmpmnt || true

# No tests found anything.
exit 1
