#!/bin/sh

# This script sets method "zfs" for all partitions that have the zfs
# flag set.  It also discovers the logical volumes and creates in them
# a loop partition table and partition.

. /lib/partman/lib/base.sh
. /lib/partman/lib/zfs-base.sh

if [ -x /sbin/zpool ]; then
	vgroups=$(/sbin/zpool list -H 2>/dev/null | \
		sed -e 's/\t.*//' | sort)
else
	vgroups=''
fi

for dev in /var/lib/partman/devices/*; do
	[ -d "$dev" ] || continue
	cd $dev
	partitions=
	open_dialog PARTITIONS
	while { read_line num id size type fs path name; [ "$id" ]; }; do
		if [ "$fs" != free ]; then
			partitions="$partitions $id,$path"
		fi
	done
	close_dialog

	# Check if device/partitions are used for ZFS (PV)
	for part in $partitions; do
		set -- $(IFS=, && echo $part)
		id=$1
		path=$2
		zfs=

		# If the device is in fact being used for zfs, mark it as such.
		# This is a hack and it only works for full block devices, not
		# partitions. It makes raid devices used for zfs show up as such.
		if zpool status 2>/dev/null | grep -q "\s$(basename $(cat $dev/device))\s" ; then
			zfs=1
		else
			open_dialog GET_FILE_SYSTEM $id
			read_line fs
			close_dialog
			if [ "$fs" = zfs ]; then
				zfs=1
			fi
		fi
		if [ "$zfs" ]; then
			mkdir -p $id
			echo zfs >$id/method

			if ! [ -e $id/locked ]; then
				vg=$(pv_get_vg $path)
				for vgs in $vgroups; do
					if [ "$vg" = "$vgs" ]; then
						vg_lock_pvs $vg $path
					fi
				done
			fi
		fi
	done

	# Check if device is a logical volume
	if [ -f device ]; then
		# Obtain the VG from the device name
		device=$(cat device)
		case "$device" in
		    /dev/zvol/*)
			vglv=${device#/dev/zvol/}
			vg=$(echo "$vglv" | cut -d"/" -f1)
			;;
		esac
		is_lv=
		for vgs in $vgroups; do
			[ ! "$vgs" = "$vg" ] || is_lv=1
		done

		# If this is a new logical volume
		if [ "$is_lv" ] && [ -z "$partitions" ]; then
			# create a label
			open_dialog NEW_LABEL loop
			close_dialog
			# find the free space
			open_dialog PARTITIONS
			free_space=''
			while { read_line num id size type fs path name; [ "$id" ]; }; do
				if [ "$fs" = free ]; then
					free_space=$id
					free_size=$size
				fi
			done
			close_dialog
			# create partition in the free space
			if [ "$free_space" ]; then
				create_new_partition primary $free_space full $free_size "zfs"
			fi
			open_dialog DISK_UNCHANGED
			close_dialog
		fi
	fi
done
