#!/usr/bin/env bash
# Clusev themed MOTD — printed at host login (Debian/Ubuntu run-parts MOTD).
# Installed by install.sh, which substitutes __CLUSEV_URL__, __CLUSEV_VERSION__ and
# __CLUSEV_COMPOSE__ (absolute path to the production compose file). Signal-orange brand,
# live stack status, no emoji (status = colour + dot). Idempotent: install.sh only ever
# overwrites this single 00-clusev file, never other MOTD parts. Never fails a login
# (every dynamic lookup degrades to "unbekannt").
O=$'\033[38;5;208m'   # signal-orange (brand)
G=$'\033[38;5;42m'    # online green
E=$'\033[38;5;203m'   # offline red
D=$'\033[2m'          # dim
B=$'\033[1m'          # bold
R=$'\033[0m'          # reset

URL="__CLUSEV_URL__"
VERSION="__CLUSEV_VERSION__"
COMPOSE="__CLUSEV_COMPOSE__"

# Live stack status — "X/Y Dienste aktiv" (green when all up, red otherwise). Best-effort:
# any failure (no docker, daemon down, file moved) falls back to a dim "Status unbekannt".
stack_status() {
  command -v docker >/dev/null 2>&1 || { printf '%s● Status unbekannt%s' "$D" "$R"; return; }
  [ -f "$COMPOSE" ] || { printf '%s● Status unbekannt%s' "$D" "$R"; return; }
  local total running
  total=$(docker compose -f "$COMPOSE" config --services 2>/dev/null | grep -c .)
  running=$(docker compose -f "$COMPOSE" ps --status running -q 2>/dev/null | grep -c .)
  if [ "${total:-0}" -gt 0 ] && [ "${running:-0}" = "$total" ]; then
    printf '%s● %s/%s Dienste aktiv%s' "$G" "$running" "$total" "$R"
  elif [ "${total:-0}" -gt 0 ]; then
    printf '%s● %s/%s aktiv — Stack pruefen%s' "$E" "$running" "$total" "$R"
  else
    printf '%s● Status unbekannt%s' "$D" "$R"
  fi
}

printf '%s\n' ""
printf '  %s%s█▀▀ █   █ █ █▀▀ █▀▀ █ █%s\n'   "$B" "$O" "$R"
printf '  %s%s█   █   █ █ ▀▀█ █▀▀ █ █%s\n'   "$B" "$O" "$R"
printf '  %s%s▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀ ▀▀▀  ▀ %s   %sFleet Control · v%s%s\n' "$B" "$O" "$R" "$D" "$VERSION" "$R"
printf '  %s──────────────────────────────────────────────────────────%s\n' "$D" "$R"
printf '   %sDashboard%s   %s%s%s\n'   "$D" "$R" "$O" "$URL" "$R"
printf '   %sStack%s       %s\n'        "$D" "$R" "$(stack_status)"
printf '   %sLogin%s       %sStandard-Passwort: clusev — beim ersten Login aendern · Reset: clusev reset-admin%s\n' "$D" "$R" "$D" "$R"
printf '   %sVerwalten%s   %sclusev ps | logs | restart%s\n' "$D" "$R" "$D" "$R"
printf '   %sUpdate%s      %ssudo clusev update%s\n' "$D" "$R" "$D" "$R"
printf '  %s──────────────────────────────────────────────────────────%s\n' "$D" "$R"
printf '%s\n' ""
