#!/bin/bash

## Copyright (C) 2025 Ajrat Makhmutov <rauty@altlinux.org>
##
## 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/>.

expected_percentage_handler() (
	expected_line_count="$1"
	initial_percentage="$2"
	end_percentage="$3"

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

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

		(( 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
)

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

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

		new_percentage=$(echo "$line" | grep -Eo ' [.0-9]+% ' | sed 's/^ //' | sed 's/\..*//' | sed 's/%.*//')
		if [ -n "$new_percentage" ]; then
			echo "step_progress: $((initial_percentage + percentage_increase * new_percentage / 100))"
		fi
	done
)
