#!/usr/bin/env bash
# show-container-versions.sh
# Displays version info from OCI image labels for each WEDA Node container.

set -euo pipefail

CONTAINERS=(dmagent system-agent watchtower)

# ── helpers ───────────────────────────────────────────────────────────────────

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BOLD='\033[1m'
RESET='\033[0m'

die() { echo -e "${RED}Error: $*${RESET}" >&2; exit 1; }

command -v docker >/dev/null 2>&1 || die "'docker' is required but not installed."

label() {
    local image="$1" key="$2"
    docker image inspect "$image" --format "{{index .Config.Labels \"$key\"}}" 2>/dev/null || echo ""
}

# ── header ────────────────────────────────────────────────────────────────────

echo -e "\n${BOLD}WEDA Node — Installed Container Version Info${RESET}\n"

# ── per-container ─────────────────────────────────────────────────────────────

found_any=false

for name in "${CONTAINERS[@]}"; do
    if ! docker inspect "$name" >/dev/null 2>&1; then
        echo -e "${YELLOW}${name}${RESET}: container not found"
        echo ""
        continue
    fi

    found_any=true
    image=$(docker inspect --format '{{.Config.Image}}' "$name")

    title=$(label "$image" "org.opencontainers.image.title")
    version=$(label "$image" "org.opencontainers.image.version")
    created=$(label "$image" "org.opencontainers.image.created")
    ref=$(label "$image" "org.opencontainers.image.ref.name")

    echo -e "${GREEN}${BOLD}${name}${RESET}"
    printf '  %-12s %s\n' "Title:"    "${title:-n/a}"
    printf '  %-12s %s\n' "Version:"  "${version:-n/a}"
    printf '  %-12s %s\n' "Created:"  "${created:-n/a}"
    printf '  %-12s %s\n' "Ref:"      "${ref:-n/a}"
    echo ""
done

if [[ "$found_any" == false ]]; then
    echo -e "${YELLOW}No WEDA Node containers found. Is WEDA Node installed and running?${RESET}"
    exit 1
fi
