#!/usr/bin/env bash
# progress.sh: copies a folder with a progress bar, the bytes copied, the speed and the time left. A spinner turns
# while it counts the files. q or Ctrl+C stops the copy and removes the half-copied file.
# Run it: bash progress.sh [-l KIB_PER_SECOND] SOURCE DESTINATION   (-l limits the speed, so the NAS stays quick)
# It needs Bash 4 or newer, such as TurboShell's bash. With NOW set, the clock counts the planned time of each block.
set -uo pipefail
shopt -s globstar nullglob

A=$'\e[38;5;214m' G=$'\e[32m' R=$'\e[31m' D=$'\e[2m' B=$'\e[1m' N=$'\e[0m'
limit=0
[[ ${1:-} == -l ]] && limit=$2 && shift 2
(($# == 2)) || { echo "Usage: bash progress.sh [-l KIB_PER_SECOND] SOURCE DESTINATION" >&2 && exit 2; }
src=${1%/} dst=${2%/}
files=() sizes=() total=0 done_bytes=0 copied=0 current='' fake_us=0 start_us=0

kib() { # BYTES: the size in KiB or MiB with one decimal
  if (($1 < 1048576)); then printf '%d.%d KiB' $(($1 / 1024)) $(($1 % 1024 * 10 / 1024)); else
    printf '%d.%d MiB' $(($1 / 1048576)) $(($1 % 1048576 * 10 / 1048576))
  fi
}

clock_us() { # the time in microseconds; with NOW set, the planned time of the blocks copied so far
  if [[ -n ${NOW:-} ]]; then echo "$fake_us"; else echo "${EPOCHREALTIME//[!0-9]/}"; fi
}

stop() { # STATUS: the end after q or Ctrl+C; the file being copied goes, because it is not whole
  [[ -n $current ]] && rm -f "$current" && printf '\n  %sRemoved the half-copied file %s.%s' "$R" "$current" "$N"
  printf '\n  %sStopped.%s %d of %d files copied, %s.\e[?25h\n' "$B" "$N" "$copied" "${#files[@]}" "$(kib "$done_bytes")"
  exit "$1"
}
trap 'stop 130' INT
trap 'printf "\e[?25h"' EXIT

draw() { # NAME: the bar, the numbers and the file, three lines that are redrawn in place
  local pct=$((total ? done_bytes * 100 / total : 100)) w=50 full fill rest us speed=0 left='--:--'
  us=$(($(clock_us) - start_us))
  ((us > 0)) && speed=$((done_bytes * 1000000 / us))
  ((speed > 0)) && left=$(printf '%d:%02d' $(((total - done_bytes) / speed / 60)) $(((total - done_bytes) / speed % 60)))
  full=$((pct * w / 100))
  printf -v fill '%*s' "$full" ''
  printf -v rest '%*s' $((w - full)) ''
  printf '\e[3F\e[2K  %s%s%s%s%s %3d %%\n' "$G" "${fill// /█}" "$D" "${rest// /░}" "$N" "$pct"
  printf '\e[2K  %s of %s   %s%s/s%s   %s left\n' "$(kib "$done_bytes")" "$(kib "$total")" "$A" "$(kib "$speed")" "$N" "$left"
  printf '\e[2K  %s%s%s\n' "$D" "$1" "$N"
}

printf '\e[?25l\n  %sCopy%s %s → %s\n\n' "$B$A" "$N" "$src" "$dst"
spin=(⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏)
for f in "$src"/**; do # count the files first, so the bar knows the whole
  [[ -f $f ]] || continue
  files+=("$f")
  sizes+=("$(stat -c %s "$f")")
  total=$((total + sizes[-1]))
  printf '\r  %s%s%s Counting files: %d' "$A" "${spin[${#files[@]} % 10]}" "$N" "${#files[@]}"
done
printf '\r\e[2K  %d files, %s\n\n\n\n' "${#files[@]}" "$(kib "$total")"

chunk=1024 # KiB per block; with a limit, one block per second at most
((limit > 0 && limit < chunk)) && chunk=$limit
start_us=$(clock_us)
for i in "${!files[@]}"; do
  f=${files[i]} out=$dst/${files[i]#"$src"/}
  mkdir -p "${out%/*}"
  : >"$out"
  current=$out
  for ((k = 0; k * chunk * 1024 < sizes[i]; k++)); do
    if ((limit > 0)); then # wait the time this block may take, and listen for q meanwhile
      ms=$((chunk * 1000 / limit))
      IFS= read -rsn1 -t "$((ms / 1000)).$(printf '%03d' $((ms % 1000)))" key && [[ $key == q ]] && stop 0
      fake_us=$((fake_us + ms * 1000))
    elif read -t 0; then
      IFS= read -rsn1 key && [[ $key == q ]] && stop 0
    fi
    dd if="$f" of="$out" bs="${chunk}K" skip="$k" seek="$k" count=1 conv=notrunc 2>/dev/null
    n=$((sizes[i] - k * chunk * 1024)) # the last block of a file may be shorter
    done_bytes=$((done_bytes + (n < chunk * 1024 ? n : chunk * 1024)))
    draw "${f#"$src"/}"
  done
  current='' copied=$((copied + 1))
done
printf '  %sDone.%s %d files, %s.\n' "$G" "$N" "$copied" "$(kib "$total")"
