#!/bin/bash

## Copyright (C) 2023 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

# shellcheck source=./check_runtime.bsh
source /usr/libexec/helper-scripts/check_runtime.bsh

if should_run_unit_tests "${BASH_SOURCE[0]}"; then
  progress_bar_should_run_unit_tests='true'
else
  progress_bar_should_run_unit_tests='false'
fi

if [ "${progress_bar_should_run_unit_tests}" = 'true' ]; then
  # shellcheck disable=SC2317
  set -o pipefail
  set -o errtrace
fi

draw_progress_bar() {
  if ! test -t 1; then
    true "Output is not being sent to the terminal because terminal is not connected to stdout."
    return 0
  fi
  : "${TERM:=""}"
  if [ "$TERM" = "" ]; then
    true "TERM is empty. Not drawing progress bar."
    return 0
  fi

  local percent_done bar_width filled_chars empty_chars bar spaces

  percent_done="${1:-0}"  # Default to 0 if no argument is given
  bar_width=50            # Width of the progress bar

  # Validate input
  if ! [[ "$percent_done" =~ ^[0-9]+$ ]] || [ "$percent_done" -gt 100 ] || [ "$percent_done" -lt 0 ]; then
      printf '%s\n' "Error: Invalid percentage value '$percent_done'. Must be a number between 0 and 100." >&2
      exit 1
  fi

  # Calculate how many characters will be filled in the bar
  filled_chars=$((percent_done * bar_width / 100))
  empty_chars=$((bar_width - filled_chars))

  # Build the bar string
  bar=$(printf '%0.s#' $(seq 1 $filled_chars))
  spaces=$(printf '%0.s ' $(seq 1 $empty_chars))

  # Print the progress bar
  printf "\r[%-50s] %3s%%" "$bar$spaces" "$percent_done"
}

main() {
  # Example usage
  for i in {0..100}; do
    draw_progress_bar "$i"
    sleep 0.1  # Simulating work
  done
}

if [ "${progress_bar_should_run_unit_tests}" = 'true' ]; then
  main
else
  true "INFO: Not running because it was sourced by another script or SKIP_UNIT_TESTS is true."
fi
