#!/bin/bash

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

if [ "${BASH_SOURCE}" != "${0}" ]; then
  ## Script was sourced.
  ## This is useful for other programs / scripts to be able to `source` the
  ## functions of this script for code reuse. dist-installer-gui will do this.
  progress_bar_was_sourced="true"
else
  ## Script was executed.
  progress_bar_was_sourced="false"
  # 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_was_sourced" = "true" ]; then
  true "INFO: Not running because it was sourced by another script."
else
  main
fi
