## Authors:
##   Ajrat Makhmutov <rauty@altlinux.org>
##
## Copyright (C) 2025  Basealt LLC
##
## This file is part of alterator-kopidel.
##
## alterator-kopidel is free software: you can redistribute it and/or modify it under the terms
## of the GNU General Public License as published by the Free Software Foundation,
## either version 3 of the License, or (at your option) any later version.
##
## alterator-kopidel is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
## without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License along with alterator-kopidel.
## If not, see <https://www.gnu.org/licenses/>.

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

. alterator-sh-functions
. "${KOPIDEL_LIBDIR:-/usr/lib/alterator-kopidel}/steps"

alterator-mailbox-send-wrapper() {
	if [ -S /tmp/.private/root/alterator/browser-sock ]; then
		TMPDIR=/tmp/.private/root/ alterator-mailbox-send "$1"
	else
		alterator-mailbox-send "$1"
	fi
}

step_percentage_mailbox_sender() (
	alterator-mailbox-send-wrapper "step_progress: 0"
	while read -r line; do
		alterator-mailbox-send-wrapper "$line"
	done
	alterator-mailbox-send-wrapper "step_progress: 100"
)

run_step_ui_wrapper() (
	alterator-mailbox-send-wrapper "step: $1 main_progress: $2"
	run_step "$1" | step_percentage_mailbox_sender
	if [ "${PIPESTATUS[0]}" -ne 0 ]; then
		echo "Failed on the step $1"
		return 1
	fi
)
