#!/bin/sh

. /usr/share/debconf/confmodule

db_register partman-zfs/confirm partman-zfs/confirm_nooverwrite

# Load modules and scan volume groups if it was not done before
if [ ! -f /var/lib/partman/zfs ] && [ "$(udpkg --print-os)" = kfreebsd -o "$(udpkg --print-os)" = linux ] ; then
	# load required kernel modules
	db_progress INFO partman/progress/init/loading_zfs
	if [ "$(udpkg --print-os)" = kfreebsd ]; then
	    kldload zfs >/dev/null 2>&1
	else
	    modprobe zfs >/dev/null 2>&1
	fi

	# Make sure that zfs is available - not a critical error.
        # Wait up to 10 seconds as ZoL module may need time to settle down.
        local zfs_load_timeout
        zfs_load_timeout=0
        while ! [ -e /dev/zfs ] && ! [ "$zfs_load_timeout" -eq "10" ]; do
            sleep 1
            let zfs_load_timeout++
        done

	# Just to make sure...
	if ! test -d /boot/zfs ; then
	    mkdir -p /boot/zfs
	fi

	# scan for zfs pools - don't mount any filesystems, they are unmounted
	# by partman anyway...
	log-output -t partman zpool import -a -f -o altroot=/target -N

	# Some ZFS versions don't create cachefile when "-o altroot" is used.
	# Request it explicitly.
	for vg in $(zpool list -H -o name) ; do
		log-output -t partman-zfs zpool set cachefile=/boot/zfs/zpool.cache "$vg" || return 1
	done

	touch /var/lib/partman/zfs
fi
