#!/usr/bin/env bash
# shellcheck disable=2317
PING_ITER=64
PROGRESS_BAR_CHAR=(█ ▒)

command() {
    local -r host=${1?"first parameter must be an host"}
    local -r iteration=${2?"second parameter must be an iteration number"}
    local -r cmd=(ping -c "${iteration}" "${host}")

    "${cmd[@]}"
}
trap change_column_size WINCH

draw_progressbar() {
    local -r progress=${1?"progress is mandatory"}
    local -r total=${2?"total elements is mandatory"}
    local -r info_segment=${3:""}
    local progress_segment
    local todo_segment

    local -r bar_size=$((COLUMNS - ${#info_segment}))
    local -r progress_ratio=$((progress * 100 / total))
    local -r progress_segment_size=$((bar_size * progress_ratio / 100))
    local -r todo_segment_size=$((bar_size - progress_segment_size))

    printf -v progress_segment "%${progress_segment_size}s" ""
    printf -v todo_segment "%${todo_segment_size}s" ""

    printf >&2 "%s%s%s\r" \
        "${info_segment}" \
        "${progress_segment// /${PROGRESS_BAR_CHAR[0]}}" \
        "${todo_segment// /${PROGRESS_BAR_CHAR[1]}}"

}

parse_output() {
    trap change_column_size WINCH
    while read -r line; do
        if [[ "$line" =~ icmp_seq=([[:digit:]]{1,}).*time=(.*) ]]; then

            draw_progressbar \
                "${BASH_REMATCH[1]}" \
                "$PING_ITER" \
                "Ping in progress (time: ${BASH_REMATCH[2]}) "
        elif [[ "$line" =~ ^PING(.*\(.*\)).* ]]; then
            printf "Launch ping command to %s with %d iterations\n" \
                "${BASH_REMATCH[1]}" \
                "$PING_ITER"
        elif [[ "$line" =~ .*packets\ transmitted.* ]]; then
            printf >&2 "\033[0K\r"
            printf "%s\n" "$line"
        fi
    done
}

change_column_size() {
    printf >&2 "%${COLUMNS}s" ""
    printf >&2 "\033[0K\r"
    COLUMNS=$(tput cols)
}

main() {
    COLUMNS=$(tput cols)
    command "aquilenet.fr" "$PING_ITER" > >(parse_output)
}

main
exit 0
