if [ -n "${__included_kopidel_install_progress-}" ]; then
	return 0
fi
readonly __included_kopidel_install_progress=1

show_install_phase() {
	{ echo "$1" > /dev/tty1; } 2>/dev/null || echo "$1"
}

watch_deployment_progress() {
	local line
	while [[ -f "$1" ]]; do
		while IFS= read -r line; do
			if [[ "$line" == deployment-finished ]]; then
				return 0
			elif [[ "$line" == deployment-complete ]]; then
				echo 'step_progress: 100'
				return 0
			elif [[ "$line" == 100 ]]; then
				echo 'step_progress: 99'
			elif [[ "$line" == [0-9] || "$line" == [1-9][0-9] ]]; then
				echo "step_progress: $line"
			fi
		done
		sleep 1
	done < "$1"
}

start_deployment_progress() {
	progress_file=/run/kopidel/install-fs.progress
	if [[ ! -w /dev/tty1 || -d /dev/tty1 ]]; then
		return 0
	fi
	if ! install -m 600 -T -- /dev/null "$progress_file" 2>/dev/null; then
		return 0
	fi

	(
		watch_deployment_progress "$progress_file" |
			TERM="${TERM:-linux}" LC_ALL=C.UTF-8 draw_progress_bar
	) 2>/dev/null >/dev/tty1 &
	progress_pid="$!"
}

finish_deployment_progress() {
	local completion=deployment-finished
	if [[ ! -v progress_pid ]]; then
		return 0
	fi
	if (( $1 == 0 )) && [[ -f "$destdir/_NEW_SYSTEM_" ]]; then
		completion=deployment-complete
	fi
	if echo -e "\n$completion" 2>/dev/null >> "$progress_file"; then
		wait "$progress_pid" 2>/dev/null || true
	fi
	rm -f -- "$progress_file" || true
}
