#!/usr/bin/env bash
# 用途：檢查 K3s 叢集節點狀態

set -euo pipefail

# 顏色定義
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo "=========================================="
echo "        K3s 叢集節點狀態"
echo "=========================================="
echo ""

# 取得節點資訊
NODES=$(kubectl get nodes -o wide --no-headers)

# 統計
NODE_TOTAL=$(echo "$NODES" | wc -l)
NODE_READY=$(echo "$NODES" | grep -c " Ready " || true)
NODE_NOT_READY=$((NODE_TOTAL - NODE_READY))

echo "📊 叢集概況"
echo "------------------------------------------"
echo "總節點數: $NODE_TOTAL"
echo -e "  ${GREEN}✓ Ready:    $NODE_READY${NC}"
if [ $NODE_NOT_READY -gt 0 ]; then
  echo -e "  ${RED}✗ NotReady: $NODE_NOT_READY${NC}"
fi
echo ""

# 顯示每個節點的詳細資訊
echo "🖥️  節點詳細資訊"
echo "------------------------------------------"

echo "$NODES" | while IFS= read -r line; do
  # 解析每個欄位
  NAME=$(echo "$line" | awk '{print $1}')
  STATUS=$(echo "$line" | awk '{print $2}')
  ROLES=$(echo "$line" | awk '{print $3}')
  INTERNAL_IP=$(echo "$line" | awk '{print $6}')
  OS_IMAGE=$(echo "$line" | awk '{print $8}')
  KERNEL=$(echo "$line" | awk '{print $9}')

  # 顏色判斷
  if [[ "$STATUS" == "Ready"* ]]; then
    STATUS_COLOR="$GREEN"
    ICON="✓"
  else
    STATUS_COLOR="$RED"
    ICON="✗"
  fi

  # 角色簡化
  if [[ "$ROLES" == *"control-plane"* ]]; then
    ROLE="${BLUE}[master]${NC}"
  elif [[ "$ROLES" == "<none>" ]]; then
    ROLE="[worker]"
  else
    ROLE="$ROLES"
  fi

  # 輸出
  echo -e "${STATUS_COLOR}$ICON $NAME${NC} $ROLE"
  echo "   狀態: $STATUS"
  echo "   IP:   $INTERNAL_IP"
  echo "   OS:   $OS_IMAGE $KERNEL"
  echo ""
done

# Pod 分佈
echo "📦 Pod 分佈"
echo "------------------------------------------"
kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.spec.nodeName}{"\n"}{end}' 2>/dev/null | grep -E "(vm120|vm121|vm122)" | while IFS=$'\t' read -r ns pod node; do
  echo "  $pod ($ns) → $node"
done | head -15

POD_TOTAL=$(kubectl get pods -A --no-headers 2>/dev/null | wc -l)
if [ $POD_TOTAL -gt 15 ]; then
  echo "  ..."
fi
echo "  總 Pod 數: $POD_TOTAL"
echo ""

echo "=========================================="
