#!/usr/bin/env bash
# menu.sh: a framed menu in pure Bash. The arrow keys move the bar, Enter opens a box with the NAS's memory,
# its volumes or its uptime and load, any key closes the box, q quits.
# Run it: bash menu.sh   (PROC and DF may point it at sample files instead of /proc and df -k)
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'
items=("Memory" "Volumes" "Uptime and load" "Quit")
sel=0

at() { printf '\e[%d;%dH' "$1" "$2"; } # LINE COLUMN: move the cursor

box() { # LINE COLUMN HEIGHT WIDTH TITLE: a double 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 >= 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 GiB' $((t / 10)) $((t % 10))
}

show_memory() {
  local key value total=0 avail=0 used
  while read -r key value _; do
    case $key in
      MemTotal:) total=$value ;;
      MemAvailable:) avail=$value ;;
    esac
  done <"$PROC/meminfo"
  used=$((total - avail))
  box 6 32 7 46 "Memory"
  at 8 35 && printf 'Total      %s' "$(gib "$total")"
  at 9 35 && printf 'In use     %s' "$(gib "$used")"
  at 10 35 && printf 'Available  %s%s%s' "$G" "$(gib "$avail")" "$N"
  at 11 35 && bar $((used * 100 / total)) 30 && printf ' %d %%' $((used * 100 / total))
}

show_volumes() {
  local fs size used _a pct mnt line=8
  box 6 32 8 46 "Volumes"
  while read -r fs size used _a pct mnt; do
    [[ $mnt == /share/* && $mnt != /share/*/* ]] || continue
    at "$line" 35 && printf '%s%-15s%s %s of %s' "$B" "${mnt#/share/}" "$N" "$(gib "$used")" "$(gib "$size")"
    at $((line + 1)) 35 && bar "${pct%\%}" 30 && printf ' %s' "$pct"
    line=$((line + 2))
  done < <(if [[ -n ${DF:-} ]]; then cat "$DF"; else df -k; fi)
  ((line == 8)) && at 8 35 && printf 'No data volumes under /share.'
}

show_uptime() {
  local up l1 l5 l15 cpus cores
  read -r up _ <"$PROC/uptime"
  read -r l1 l5 l15 _ <"$PROC/loadavg"
  cpus=$(grep -c '^processor' "$PROC/cpuinfo")
  cores=$(awk -F': ' '/^physical id/ {p = $2} /^core id/ {print p "-" $2}' "$PROC/cpuinfo" | sort -u | wc -l)
  up=${up%.*}
  box 6 32 9 46 "Uptime and load"
  at 8 35 && printf 'Up for     %s%d d %d h %d min%s' "$B" $((up / 86400)) $((up % 86400 / 3600)) $((up % 3600 / 60)) "$N"
  at 9 35 && printf 'Load       %s / %s / %s' "$l1" "$l5" "$l15"
  at 10 35 && printf '%s           1, 5 and 15 minutes%s' "$D" "$N"
  at 11 35 && printf 'Cores      %d' "$cores"
  at 12 35 && printf 'Processors %d logical' "$cpus"
}

draw() { # the whole screen: title, menu, keys
  printf '\e[2J'
  local model
  model=$(getsysinfo model 2>/dev/null) || model=$(uname -n)
  at 1 1 && printf '%s %-58s%21s%s' "$BAR" "NAS menu" "$model" "$N"
  box 4 4 $((${#items[@]} + 4)) 24 "Menu"
  local i
  for i in "${!items[@]}"; do
    at $((6 + i)) 6
    if ((i == sel)); then printf '%s ▶ %-17s%s' "$BAR" "${items[i]}" "$N"; else printf '   %-17s' "${items[i]}"; fi
  done
  at 24 1 && printf '%s ↑↓ move   Enter open   q quit%s' "$D" "$N"
}

restore() { printf '\e[0m\e[?25h\e[?1049l'; }
trap restore EXIT
trap 'exit 0' INT TERM
printf '\e[?1049h\e[?25l' # a screen of its own, no cursor

draw
while true; do
  IFS= read -rsn1 key
  if [[ $key == $'\e' ]]; then
    IFS= read -rsn2 -t 0.05 rest
    key=$key$rest
  fi
  case $key in
    $'\e[A' | $'\eOA') sel=$(((sel + ${#items[@]} - 1) % ${#items[@]})) ;;
    $'\e[B' | $'\eOB') sel=$(((sel + 1) % ${#items[@]})) ;;
    q | Q) exit 0 ;;
    '')
      case $sel in
        0) show_memory ;;
        1) show_volumes ;;
        2) show_uptime ;;
        3) exit 0 ;;
      esac
      at 24 1 && printf '\e[2K%s Any key closes the box%s' "$D" "$N"
      IFS= read -rsn1 _
      ;;
  esac
  draw
done
