#!/bin/bash
# ============================================================
#  脚本功能：收集指定命名空间下副本数 > 0 的 Deployment 信息
#  包含：Deployment 名称、镜像名称、GIT 相关环境变量
# ============================================================

set -euo pipefail

# ── 配置区 ──────────────────────────────────────────────────
NAMESPACE="sd-wf-ga-fly-260327"
OUTPUT_FILE="deployment_info_$(date +%Y%m%d_%H%M%S).txt"
# ────────────────────────────────────────────────────────────

echo "=========================================="
echo " 命名空间 : $NAMESPACE"
echo " 输出文件 : $OUTPUT_FILE"
echo "=========================================="

# 创建（清空）输出文件
> "$OUTPUT_FILE"

# 获取所有 Deployment 名称（换行分隔）
DEPLOYMENTS=$(kubectl get deployments -n "$NAMESPACE" \
  -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null)

if [[ -z "$DEPLOYMENTS" ]]; then
  echo "[ERROR] 命名空间 '$NAMESPACE' 下未发现任何 Deployment，请检查命名空间是否正确。"
  exit 1
fi

PROCESSED=0
SKIPPED=0

while IFS= read -r DEPLOY; do
  [[ -z "$DEPLOY" ]] && continue

  # ── 1. 获取期望副本数 ──────────────────────────────────────
  REPLICAS=$(kubectl get deployment "$DEPLOY" -n "$NAMESPACE" \
    -o jsonpath='{.spec.replicas}' 2>/dev/null)
  REPLICAS="${REPLICAS:-0}"

  if [[ "$REPLICAS" == 0 ]]; then
    echo "[SKIP]  $DEPLOY  (副本数=${REPLICAS}，≤ 1，跳过)"
    (( SKIPPED++ )) || true
    continue
  fi

  echo "[INFO]  处理 Deployment: $DEPLOY  (副本数=${REPLICAS})"

  # ── 2. 获取第一个容器的镜像名称 ───────────────────────────
  IMAGE=$(kubectl get deployment "$DEPLOY" -n "$NAMESPACE" \
    -o jsonpath='{.spec.template.spec.containers[0].image}' 2>/dev/null)
  IMAGE="${IMAGE:-<未获取到镜像>}"

  # ── 3. 在第一个副本 Pod 中执行 env | grep GIT ─────────────
  GIT_ENV=$(kubectl exec -n "$NAMESPACE" "deploy/$DEPLOY" \
    -- sh -c "env | grep GIT" 2>/dev/null || echo "")

  # ── 4. 写入输出文件 ───────────────────────────────────────
  {
    echo "deployment名称：${DEPLOY}"
    echo "镜像名称：${IMAGE}"
    echo "环境变量："
    if [[ -n "$GIT_ENV" ]]; then
      while IFS= read -r env_line; do
        echo "    ${env_line}"
      done <<< "$GIT_ENV"
    else
      echo "    (未发现 GIT 相关环境变量)"
    fi
    echo ""
    echo "------------------------------------------"
    echo ""
  } >> "$OUTPUT_FILE"

  (( PROCESSED++ )) || true

done <<< "$DEPLOYMENTS"

# ── 汇总输出 ──────────────────────────────────────────────
echo ""
echo "=========================================="
echo " 完成！已处理: ${PROCESSED} 个，已跳过: ${SKIPPED} 个"
echo " 结果文件: $OUTPUT_FILE"
echo "=========================================="