#!/bin/sh

. /usr/share/debconf/confmodule
. /lib/partman/definitions.sh

dev_to_partman () {
	local dev_name="$1"
	
	local mapped_dev_name="$(mapdevfs $dev_name)"
	if [ -n "$mapped_dev_name" ]; then
		dev_name="$mapped_dev_name"
	fi

	for dev in $DEVICES/*; do
		# mapdevfs both to allow for different ways to refer to the
		# same device using devfs, and to allow user input in
		# non-devfs form
		if [ "$(mapdevfs $(cat $dev/device))" = "$dev_name" ]; then
			echo $dev
		fi
	done
}

# Do not run on S/390
if [ "$(udpkg --print-architecture)" = s390 ]; then
	exit 0
fi

# Only run the first time
if [ -f /var/lib/partman/initial_auto ]; then
	exit 0
fi
[ -d /var/lib/partman ] || mkdir /var/lib/partman
touch /var/lib/partman/initial_auto

# See if a disk to autopartition (either classic or LVM) has been set
if db_get partman-auto/disk && [ -n "$RET" ]; then
	disk="$RET"
	id=$(dev_to_partman "$disk") || true
	if [ -n "$id" ]; then
		autopartition "$id"
		exit 0
	fi
elif search-path autopartition-lvm && \
     db_get partman-auto-lvm/disk && [ -n "$RET" ]; then
	disk="$RET"
	id=$(dev_to_partman "$disk") || true
	if [ -n "$id" ]; then
		autopartition-lvm "$id"
		exit 0
	fi
fi

echo "partman-auto/init_automatically_partition" > /lib/partman/automatically_partition/question
partman_newlayout
