#!/bin/sh

. /usr/share/debconf/confmodule
. /lib/partman/definitions.sh
. /lib/partman/auto-shared.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
}

# Skip if no disks detected and don't run on S/390
if [ -z "$(get_auto_disks)" ] || \
   [ "$(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 any autopartition method has been set
method=""
if db_get partman-auto/method && [ "$RET" ]; then
	method="$RET"
fi

# See if any autopartition disks have been set
disks=""
if db_get partman-auto/disk && [ "$RET" ]; then
	disks="$RET"
fi

# If both are set, let's try to do a completely automatic partitioning
if [ "$method" ] && [ "$disks" ]; then
	# The code for the methods could be merged, but in the future non-regular
	# methods may support multiple disks
	case "$method" in
		regular)
			for disk in $disks; do
				id=$(dev_to_partman "$disk") || true
				if [ -n "$id" ]; then
					autopartition "$id"
					exit 0
				fi
			done
			exit 1
			;;
		lvm)
			search-path autopartition-lvm || exit 1
			for disk in $disks; do
				id=$(dev_to_partman "$disk") || true
				if [ -n "$id" ]; then
					autopartition-lvm "$id"
					exit 0
				fi
			done
			exit 1
			;;
		crypto)
			search-path autopartition-crypto || exit 1
			for disk in $disks; do
				id=$(dev_to_partman "$disk") || true
				if [ -n "$id" ]; then
					autopartition-crypto "$id"
					exit 0
				fi
			done
			exit 1
			;;
		raid)
			# Partition all the disks given ready for
			# partman-auto-raid
			for disk in $disks; do
				id=$(dev_to_partman "$disk") || true
				if [ -n "$id" ]; then
					autopartition "$id"
				fi
			done
			exit 0
			;;
		*)
			logger -t partman-auto "Unsupported method '$method'"
			exit 1
			;;
	esac
fi

echo "partman-auto/init_automatically_partition" > /lib/partman/automatically_partition/question
code=99 # signals a retry
while [ $code = 99 ]; do
	ask_user /lib/partman/automatically_partition 
	code=$?
done
echo "partman-auto/automatically_partition" > /lib/partman/automatically_partition/question
exit $code
