## 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_percentage_handlers-}" ]; then
	return 0
fi
readonly __included_kopidel_percentage_handlers=1

expected_percentage_handler() (
	expected_line_count="$1"
	initial_percentage="$2"
	end_percentage="$3"
	log_file="${4-}"

	(( percentage_increase = end_percentage - initial_percentage ))
	line_num=1
	current_percentage="$initial_percentage"

	while read -r line; do
		if [ -n "$log_file" ]; then
			echo "$line" >> "$log_file"
		else
			echo "$line"
		fi

		(( new_percentage = initial_percentage + percentage_increase * line_num / expected_line_count ))
		if [ "$new_percentage" != "$current_percentage" ]; then
			echo "step_progress: $new_percentage"
			current_percentage="$new_percentage"
		fi
		(( line_num += 1 ))
	done
)

default_percentage_handler() (
	initial_percentage="$1"
	end_percentage="$2"
	(( percentage_increase = end_percentage - initial_percentage ))

	while read -r line; do
		echo "$line"

		if [[ "$line" =~ ^[0-9]+$ ]]; then
			echo "step_progress: $((initial_percentage + percentage_increase * line / 100))"
		fi
	done
)

dd_percentage_handler() (
	initial_percentage="$1"
	end_percentage="$2"
	(( percentage_increase = end_percentage - initial_percentage ))

	dd_pid="$3"
	output_file="$4"
	total_bytes="$5"

	while true; do
		if ! kill -0 "$dd_pid" 2>/dev/null; then
			echo "step_progress: $end_percentage"
			break
		fi

		if [ -f "$output_file" ]; then
			current_bytes=$(stat -c %s "$output_file")
			(( percent = initial_percentage + percentage_increase * current_bytes / total_bytes ))
			if [ "$percent" -gt "$end_percentage" ]; then
				percent="$end_percentage"
			fi
			echo "step_progress: $percent"
		else
			echo "step_progress: $initial_percentage"
		fi

		sleep 0.5
	done
)
