#!/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=""
				mounted=""
				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"
				elif echo "$1" | grep -q "LABEL="; then
					debug "mounting boot partition by label for linux system on $partition: $1"
					label=$(echo "$1" | cut -d = -f 2)
					if /target/bin/mount -L "$label" -o ro $tmpmnt/boot -t "$3"; then
						mounted=1
						bootpart=$(mount | grep $tmpmnt/boot | cut -d " " -f 1)
					else
						error "failed to mount by label"
					fi
				elif echo "$1" | grep -q "UUID="; then
					debug "mounting boot partition by UUID for linux system on $partition: $1"
					uuid=$(echo "$1" | cut -d = -f 2)
					if /target/bin/mount -U "$uuid" -o ro $tmpmnt/boot -t "$3"; then
						mounted=1
						bootpart=$(mount | grep $tmpmnt/boot | cut -d " " -f 1)
					else
						error "failed to mount by UUID"
					fi
				else
					bootpart=""
				fi

				if [ ! "$mounted" ]; then
					if [ -z "$bootpart" ]; then
						debug "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
		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
