#! /usr/bin/env bash
#
# avtime
#
# Release: 1.0 of 2026/03/27
# 2026, Joseph Maillardet
#
# This program 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
# any later version.
#
# This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.

set -euo pipefail

LANG=C
R=0; U=0; S=0; P=0;
TIMEFORMAT='%R %U %S %P'

if [[ "$1" =~ ^[0-9]+$ ]]
	then count="$1"; shift
	else count=100
fi

msg() { printf -- "%s\n" "$*"; }
add() { msg "$1 + $2" | bc; }
moy() { msg "scale=$2; $1 / $count" | bc; }

out() {
	printf "\e[u\e[J%s Real:%.3fs User:%.3fs System:%.3fs CPU:%.2f%%\n" "$1" "$2" "$3" "$4" "$5"
}

printf "\n\e[1A\e[s" # go 1 line down then up + save position

while read -r A B C D E; do
	R=$(add "$R" "$B")
	U=$(add "$U" "$C")
	S=$(add "$S" "$D")
	P=$(add "$P" "$E")
	out "$A" "$B" "$C" "$D" "$E"
done < <(
	for token in $(seq "$count"); do
		printf "%i/%i " "$token" "$count"
		time "$@" &>/dev/null
	done 2>&1
)

R=$(moy "$R" 3)
U=$(moy "$U" 3)
S=$(moy "$S" 3)
P=$(moy "$P" 2)

out "Moyenne:" "$R" "$U" "$S" "$P"

exit 0
