#!/bin/sh

. /lib/partman/lib/base.sh

set -e

cleanup_ro_partitions=
mountpoint="$(mktemp -d)"
cleanup () {
	if [ -e $mountpoint ]; then
		umount -l $mountpoint 2>/dev/null || true
		rmdir $mountpoint || true
	fi
	for p in $cleanup_ro_partitions; do
		blockdev --setrw $p || true
	done
}
trap cleanup EXIT HUP INT QUIT TERM

# In case we're booting from EFI mode and there's no existing ESP present,
# do not offer reusing existing partitions as we won't be able to boot into
# them.
efi_count_path="/var/lib/partman/efi_esp_count"
if [ -e /var/lib/partman/efi ] && [ -f $efi_count_path ]; then
	esp_count=$(cat $efi_count_path)
	if [ "$esp_count" = 0 ]; then
		exit 0
	fi
fi

reuse=
disks=
if db_get partman-auto/disk; then
	disks="$RET"
fi
for dev in $DEVICES/*; do
	[ -d $dev ] || continue
	if [ "$disks" ]; then
		partman_disk="$(cat "$dev/device")"
		found=0
		for preseed_disk in $disks; do
			preseed_id=$(mapdevfs $preseed_disk)
			case " $preseed_id " in
			    *" $partman_disk "*)
				found=1
				;;
			    *)
				continue
				;;
			esac
		done
		if [ "$found" = "0" ]; then
			continue
		fi
	fi
	cd $dev
	open_dialog PARTITIONS
	while { read_line num id size type fs path name; [ "$id" ]; }; do
		[ ! "$(echo "$fs" | egrep -s 'free|fat|ntfs|hfs|swap')" ] || continue
		[ -e "$path" ] || continue
		part=$dev//$id
		if [ -n "$fs" ]; then
		    mounted=
		    if type grub-mount >/dev/null 2>&1 && \
			grub-mount "$path" "$mountpoint" 2>/dev/null 3>&- 6>&- 7<&-; then
			mounted=1
		    else
			blockdev --setro "$path" || continue
			cleanup_ro_partitions="$cleanup_ro_partitions $path"
			if mount -o ro "$path" "$mountpoint" 3>&- 6>&- 7<&-; then
			    mounted=1
			fi
		    fi
		    if [ "$mounted" ]; then
			release="$(grep -s DISTRIB_ID $mountpoint/etc/lsb-release)" || true
			umount -l "$mountpoint" || true
			if [ "${release##DISTRIB_ID=}" = "Trisquel" ]; then
				db_subst partman-auto/text/reuse PARTITION "$(humandev "$path")"
				db_metaget partman-auto/text/reuse description
				reuse="$reuse$NL$part$TAB$RET"
			fi
		    fi
		fi
	done
	for p in $cleanup_ro_partitions; do
		blockdev --setrw $p || true
	done
	close_dialog
done

if [ "$reuse" ]; then
	printf %s "$reuse"
fi
