#!/usr/bin/env bash
# stats.sh: a live dashboard of the NAS. Every 2 seconds it redraws the CPU, its load and temperature, the memory,
# the data volumes and the network rate of each eth port, until you press q.
# Run it: bash stats.sh   (PROC, DF and NOW may point it at sample files and a fixed clock)
set -uo pipefail

PROC=${PROC:-/proc}
A=$'\e[38;5;214m' G=$'\e[32m' R=$'\e[31m' D=$'\e[2m' B=$'\e[1m' N=$'\e[0m' BAR=$'\e[1;30;48;5;214m'
prev_rx=() prev_tx=() prev_us=0

at() { printf '\e[%d;%dH' "$1" "$2"; }

box() { # LINE COLUMN HEIGHT WIDTH TITLE: a frame in amber, empty inside
  local l=$1 c=$2 h=$3 w=$4 i inner
  printf -v inner '%*s' $((w - 2)) ''
  at "$l" "$c" && printf '%s┌%s┐' "$A" "${inner// /─}"
  for ((i = 1; i < h - 1; i++)); do at $((l + i)) "$c" && printf '│%s│' "$inner"; done
  at $((l + h - 1)) "$c" && printf '└%s┘' "${inner// /─}"
  at "$l" $((c + 2)) && printf '%s %s %s' "$B$A" "$5" "$N"
}

bar() { # PERCENT WIDTH: green up to 69 %, amber up to 89 %, red from 90 %
  local p=$1 w=$2 full colour=$G fill rest
  ((p > 100)) && p=100
  ((p >= 70)) && colour=$A
  ((p >= 90)) && colour=$R
  full=$((p * w / 100))
  printf -v fill '%*s' "$full" ''
  printf -v rest '%*s' $((w - full)) ''
  printf '%s%s%s%s%s' "$colour" "${fill// /█}" "$D" "${rest// /░}" "$N"
}

gib() { # KIB: the size in GiB with one decimal
  local t=$((($1 * 10 + 524288) / 1048576))
  printf '%d.%d' $((t / 10)) $((t % 10))
}

rate() { # BYTES_PER_SECOND: the rate in B/s, KiB/s or MiB/s
  if (($1 < 1024)); then
    printf '%d B/s' "$1"
  elif (($1 < 1048576)); then
    printf '%d.%d KiB/s' $(($1 / 1024)) $(($1 % 1024 * 10 / 1024))
  else
    printf '%d.%d MiB/s' $(($1 / 1048576)) $(($1 % 1048576 * 10 / 1048576))
  fi
}

temp() { # WHAT: a getsysinfo temperature ("53 C/127 F") in °C, green, amber from 60, red from 75
  local t colour=$G
  t=$(getsysinfo "$1" 2>/dev/null) || return 1
  t=${t%% C*}
  ((t >= 60)) && colour=$A
  ((t >= 75)) && colour=$R
  printf '%s%s °C%s' "$colour" "$t" "$N"
}

draw_cpu() {
  local name cpus cores l1 l5 l15 load t
  name=$(grep -m1 '^model name' "$PROC/cpuinfo" | sed 's/.*: //; s/(R)//g; s/(TM)//g; s/ CPU//')
  cpus=$(grep -c '^processor' "$PROC/cpuinfo")
  cores=$(awk -F': ' '/^physical id/ {p = $2} /^core id/ {print p "-" $2}' "$PROC/cpuinfo" | sort -u | wc -l)
  read -r l1 l5 l15 _ <"$PROC/loadavg"
  load=$((10#${l1/./} / cpus)) # the load of 1 minute per logical processor, in percent
  box 3 1 8 40 "CPU"
  at 4 3 && printf '%s%.36s%s' "$B" "$name" "$N"
  at 5 3 && printf '%d cores, %d logical processors' "$cores" "$cpus"
  at 6 3 && printf 'Load      %s  %s  %s' "$l1" "$l5" "$l15"
  at 7 3 && bar "$load" 24 && printf ' %3d %%' "$load"
  if t=$(temp cputmp); then at 8 3 && printf 'CPU       %s' "$t"; fi
  if t=$(temp systmp); then at 9 3 && printf 'System    %s' "$t"; fi
}

draw_memory() {
  local key value total=0 avail=0 cache=0 used
  while read -r key value _; do
    case $key in
      MemTotal:) total=$value ;;
      MemAvailable:) avail=$value ;;
      Buffers: | Cached:) cache=$((cache + value)) ;;
    esac
  done <"$PROC/meminfo"
  used=$((total - avail))
  box 3 41 8 40 "Memory"
  at 4 43 && printf 'Total      %6s GiB' "$(gib "$total")"
  at 5 43 && printf 'In use     %6s GiB' "$(gib "$used")"
  at 6 43 && printf 'Available  %s%6s GiB%s' "$G" "$(gib "$avail")" "$N"
  at 7 43 && printf 'Cache      %6s GiB' "$(gib "$cache")"
  at 8 43 && bar $((used * 100 / total)) 24 && printf ' %3d %%' $((used * 100 / total))
}

draw_volumes() { # one row per data volume; sets next, the first line below the box
  local size used pct mnt rows=() row line=12
  while read -r _ size used _ pct mnt; do
    [[ $mnt == /share/* && $mnt != /share/*/* ]] || continue
    rows+=("$(printf '%-16s' "${mnt#/share/}")$(bar "${pct%\%}" 30) $(printf '%7s / %7s GiB %4s' "$(gib "$used")" "$(gib "$size")" "$pct")")
  done < <(if [[ -n ${DF:-} ]]; then cat "$DF"; else df -k; fi)
  ((${#rows[@]})) || rows=("No data volumes under /share.")
  box 11 1 $((${#rows[@]} + 2)) 80 "Volumes"
  for row in "${rows[@]}"; do
    at "$line" 3 && printf '%s' "$row"
    line=$((line + 1))
  done
  next=$((line + 1))
}

draw_network() { # LINE: one row per eth port, the rate since the last frame
  local l=$1 i=0 name rx tx now_us ms rows=() row
  now_us=${EPOCHREALTIME:-}
  now_us=${now_us//[!0-9]/}
  if [[ -n $now_us ]] && ((prev_us > 0)); then ms=$(((now_us - prev_us) / 1000)); else ms=2000; fi
  ((ms > 0)) || ms=1
  while read -r name rx _ _ _ _ _ _ _ tx _; do
    [[ $name == eth* ]] && ((l + ${#rows[@]} < 21)) || continue # the rows that fit above the last line
    [[ -n ${prev_rx[i]:-} ]] || { prev_rx[i]=$rx && prev_tx[i]=$tx; }
    rows+=("$(printf '%-6s ↓ %-12s ↑ %-12s %stotal ↓ %6s GiB  ↑ %6s GiB%s' "${name%:}" \
      "$(rate $(((rx - prev_rx[i]) * 1000 / ms)))" "$(rate $(((tx - prev_tx[i]) * 1000 / ms)))" \
      "$D" "$(gib $((rx / 1024)))" "$(gib $((tx / 1024)))" "$N")")
    prev_rx[i]=$rx prev_tx[i]=$tx i=$((i + 1))
  done < <(sed 's/:/ /' "$PROC/net/dev")
  prev_us=${now_us:-0}
  box "$l" 1 $((${#rows[@]} + 2)) 80 "Network"
  for row in "${rows[@]}"; do
    l=$((l + 1))
    at "$l" 3 && printf '%s' "$row"
  done
}

frame() {
  local model clock next
  model=$(getsysinfo model 2>/dev/null) || model=$(uname -n)
  clock=${NOW:-$(date '+%Y-%m-%d %H:%M:%S')}
  at 1 1 && printf '%s %-20s%-39s%20s%s' "$BAR" "NAS stats" "$model" "$clock" "$N"
  draw_cpu
  draw_memory
  draw_volumes
  draw_network "$next"
  at 24 1 && printf '%s Refreshes every 2 seconds   q quits%s' "$D" "$N"
}

restore() { printf '\e[0m\e[?25h\e[?1049l'; }
trap restore EXIT
trap 'exit 0' INT TERM
printf '\e[?1049h\e[?25l\e[2J'
while true; do
  frame
  IFS= read -rsn1 -t 2 key && [[ $key == q || $key == Q ]] && exit 0
done
