#!/usr/bin/env bash
# database/status -- version, capacity and top databases by size
set -o pipefail
SELF=$(readlink -f "${BASH_SOURCE[0]}")
NV_BASE=$(cd "$(dirname "$SELF")/../../.." && pwd)
export NV_BASE
# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

nv_require_root || exit 1
ui_header "$(t mod_db_status)"

if ! db_available; then
    ui_err "$(t db_unreachable)"
    exit 1
fi

ui_kv "$(t db_version)" "$(mariadb -V 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -n 1)"
ui_kv "$(t db_count)"   "$(db_root_exec 'SHOW DATABASES' 2>/dev/null | grep -vcE '^(information_schema|performance_schema|mysql|sys)$')"

ui_section "$(t db_top_size)"
printf '  %-32s %s\n' "$(t col_database)" "$(t col_size)"
db_root_exec "SELECT table_schema, ROUND(SUM(data_length+index_length)/1024/1024,1)
              FROM information_schema.tables
              GROUP BY table_schema ORDER BY 2 DESC LIMIT 10" 2>/dev/null \
    | while IFS=$'\t' read -r name mb; do
          [ -z "$name" ] && continue
          printf '  %-32s %s MB\n' "$name" "$mb"
      done
ui_blank
exit 0
