#!/usr/bin/env bash
# menu.sh: menu w ramce w czystym Bashu. Strzałki przesuwają pasek, Enter otwiera okno z pamięcią NAS-a,
# jego woluminami albo czasem pracy i obciążeniem, dowolny klawisz zamyka okno, q kończy program.
# Uruchom: bash menu.sh   (PROC i DF mogą wskazać pliki próbne zamiast /proc i 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=("Pamięć" "Woluminy" "Czas i obciążenie" "Wyjście")
sel=0

at() { printf '\e[%d;%dH' "$1" "$2"; } # WIERSZ KOLUMNA: przesuwa kursor

pad() { printf '%s%*s' "$1" $(($2 - ${#1})) ''; } # TEKST SZEROKOŚĆ: dopełnia spacjami, liczy znaki, nie bajty

box() { # WIERSZ KOLUMNA WYSOKOŚĆ SZEROKOŚĆ TYTUŁ: podwójna bursztynowa ramka, pusta w środku
  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() { # PROCENT SZEROKOŚĆ: zielony do 69 %, bursztynowy do 89 %, czerwony od 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: rozmiar w GiB z jednym miejscem po przecinku
  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 "Pamięć"
  at 8 35 && printf 'Razem      %s' "$(gib "$total")"
  at 9 35 && printf 'W użyciu   %s' "$(gib "$used")"
  at 10 35 && printf 'Dostępne   %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 "Woluminy"
  while read -r fs size used _a pct mnt; do
    [[ $mnt == /share/* && $mnt != /share/*/* ]] || continue
    at "$line" 35 && printf '%s%s%s %s z %s' "$B" "$(pad "${mnt#/share/}" 15)" "$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 'Brak woluminów danych w /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 "Czas pracy i obciążenie"
  at 8 35 && printf 'Pracuje    %s%d d %d h %d min%s' "$B" $((up / 86400)) $((up % 86400 / 3600)) $((up % 3600 / 60)) "$N"
  at 9 35 && printf 'Obciążenie %s / %s / %s' "${l1/./,}" "${l5/./,}" "${l15/./,}"
  at 10 35 && printf '%s           średnie z 1, 5 i 15 minut%s' "$D" "$N"
  at 11 35 && printf 'Rdzenie    %d' "$cores"
  at 12 35 && printf 'Procesory  %d logicznych' "$cpus"
}

draw() { # cały ekran: tytuł, menu, klawisze
  printf '\e[2J'
  local model
  model=$(getsysinfo model 2>/dev/null) || model=$(uname -n)
  at 1 1 && printf '%s %s%21s%s' "$BAR" "$(pad "Menu NAS-a" 58)" "$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 ▶ %s%s' "$BAR" "$(pad "${items[i]}" 17)" "$N"; else printf '   %s' "$(pad "${items[i]}" 17)"; fi
  done
  at 24 1 && printf '%s ↑↓ wybór   Enter otwiera   q wyjście%s' "$D" "$N"
}

restore() { printf '\e[0m\e[?25h\e[?1049l'; }
trap restore EXIT
trap 'exit 0' INT TERM
printf '\e[?1049h\e[?25l' # osobny ekran, bez kursora

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 Dowolny klawisz zamyka okno%s' "$D" "$N"
      IFS= read -rsn1 _
      ;;
  esac
  draw
done
