#!/bin/sh

. /lib/partman/lib/base.sh
. /lib/partman/lib/commit.sh

dev=$2
id=$3

cd $dev

db_set partman-partitioning/confirm_copy false
db_input critical partman-partitioning/confirm_copy || true
db_go || exit 0
db_get partman-partitioning/confirm_copy

[ "$RET" = true ] || exit 0

ask_for_source () {
	local noninteractive
	noninteractive=true
	while true; do
		source_dev=''
		source_id=''
		while [ ! "$source_id" ]; do
			choices=$(partition_tree_choices)
			debconf_select critical partman-partitioning/source_partition "$choices" asdfasdfasdf
			case $? in
			    1)
				$noninteractive
				;;
			    255)
				return 1
				;;
			esac
			noninteractive='return 1'
			source_dev=${RET%//*}
			source_id=${RET#*//}
		done
		source_dev=${source_dev##*/}
		if perform_copying; then break; fi
	done
	return 0
}

perform_copying () {
	commit_changes partman-partitioning/copy_commit_failed || exit 0

	name_progress_bar partman-partitioning/progress_copying
	open_dialog COPY_PARTITION $id $source_dev $source_id
	close_dialog

	for s in /lib/partman/init.d/*; do
		if [ -x $s ]; then
			$s || exit 0
		fi
	done
}

ask_for_source
