#!/bin/bash
# 获取所有服务器上Docker环境运行的应用列表

set -e

echo "🐳 Docker应用列表 - 所有服务器"
echo "================================"
echo "生成时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

# 服务器列表
SERVERS=("macmini" "ubuntu1" "ubuntu2" "NAS")

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

# 统计变量
TOTAL_APPS=0
TOTAL_CONTAINERS=0

# 检查服务器连接函数
check_server_connection() {
    local server="$1"
    echo -n "检查服务器 $server 连接... "
    
    if ssh -q -o ConnectTimeout=5 -o BatchMode=yes "$server" "exit" 2>/dev/null; then
        echo -e "${GREEN}✓ 连接正常${NC}"
        return 0
    else
        echo -e "${RED}✗ 连接失败${NC}"
        return 1
    fi
}

# 获取Docker应用信息函数
get_docker_apps() {
    local server="$1"
    
    echo ""
    echo -e "${BLUE}====================${NC}"
    echo -e "${YELLOW}服务器: $server${NC}"
    echo -e "${BLUE}====================${NC}"
    
    # 检查Docker是否安装
    if ! ssh "$server" "command -v docker &> /dev/null"; then
        echo "❌ Docker未安装"
        return
    fi
    
    # 检查Docker服务状态
    DOCKER_STATUS=$(ssh "$server" "systemctl is-active docker 2>/dev/null || echo 'unknown'")
    if [ "$DOCKER_STATUS" != "active" ]; then
        echo "⚠️  Docker服务状态: $DOCKER_STATUS"
    fi
    
    # 获取运行中的容器
    echo ""
    echo "📦 运行中的容器:"
    echo "--------------"
    
    RUNNING_CONTAINERS=$(ssh "$server" "docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}' 2>/dev/null || echo '无运行中的容器'")
    echo "$RUNNING_CONTAINERS"
    
    # 统计运行中的容器数量
    RUNNING_COUNT=$(ssh "$server" "docker ps -q 2>/dev/null | wc -l || echo 0")
    echo "运行中: $RUNNING_COUNT 个容器"
    
    # 获取所有容器（包括停止的）
    echo ""
    echo "📋 所有容器:"
    echo "-----------"
    
    ALL_CONTAINERS=$(ssh "$server" "docker ps -a --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}' 2>/dev/null || echo '无法获取容器列表'")
    echo "$ALL_CONTAINERS"
    
    # 统计所有容器数量
    ALL_COUNT=$(ssh "$server" "docker ps -a -q 2>/dev/null | wc -l || echo 0")
    echo "总计: $ALL_COUNT 个容器"
    
    # 获取docker-compose应用
    echo ""
    echo "🎯 Docker Compose应用:"
    echo "-------------------"
    
    # 查找常见的docker-compose目录
    COMPOSE_DIRS=$(ssh "$server" "find /home /opt /usr/local -name 'docker-compose.yml' -o -name 'docker-compose.yaml' 2>/dev/null | head -20 || echo '未找到docker-compose文件'")
    
    if [ -n "$COMPOSE_DIRS" ] && [ "$COMPOSE_DIRS" != "未找到docker-compose文件" ]; then
        echo "找到的docker-compose目录:"
        echo "$COMPOSE_DIRS" | while read dir; do
            APP_NAME=$(basename $(dirname "$dir"))
            echo "  📁 $APP_NAME - $dir"
        done
        
        # 统计docker-compose应用数量
        COMPOSE_COUNT=$(echo "$COMPOSE_DIRS" | wc -l)
        echo "总计: $COMPOSE_COUNT 个docker-compose应用"
    else
        echo "未找到docker-compose应用"
    fi
    
    # 获取镜像列表
    echo ""
    echo "🖼️  Docker镜像:"
    echo "-------------"
    
    IMAGES=$(ssh "$server" "docker images --format 'table {{.Repository}}\t{{.Tag}}\t{{.Size}}' 2>/dev/null | head -10 || echo '无法获取镜像列表'")
    echo "$IMAGES"
    
    # 统计镜像数量
    IMAGE_COUNT=$(ssh "$server" "docker images -q 2>/dev/null | wc -l || echo 0")
    echo "总计: $IMAGE_COUNT 个镜像"
    
    # 更新统计
    TOTAL_CONTAINERS=$((TOTAL_CONTAINERS + ALL_COUNT))
    TOTAL_APPS=$((TOTAL_APPS + COMPOSE_COUNT))
    
    echo ""
    echo "📊 服务器 $server 统计:"
    echo "  • 运行中容器: $RUNNING_COUNT"
    echo "  • 所有容器: $ALL_COUNT"
    echo "  • Docker Compose应用: $COMPOSE_COUNT"
    echo "  • Docker镜像: $IMAGE_COUNT"
}

# 主程序
echo "🔍 开始检查服务器连接..."
echo ""

for server in "${SERVERS[@]}"; do
    if check_server_connection "$server"; then
        get_docker_apps "$server"
    else
        echo ""
        echo "⏭️  跳过服务器 $server"
        echo ""
    fi
done

# 生成总结报告
echo ""
echo -e "${GREEN}📈 总体统计报告${NC}"
echo "================================"
echo "检查的服务器数量: ${#SERVERS[@]}"
echo "总计容器数量: $TOTAL_CONTAINERS"
echo "总计Docker Compose应用: $TOTAL_APPS"
echo ""
echo "🔄 最近检查的应用状态:"

# 从配置文件获取应用列表
if [ -f "docker-apps.yaml" ]; then
    echo "从配置文件读取的应用列表:"
    grep -E "name:|server:" docker-apps.yaml | while read line; do
        echo "  $line"
    done
fi

echo ""
echo "🔧 常用命令:"
echo "  • 查看容器日志: docker logs <容器名>"
echo "  • 重启容器: docker restart <容器名>"
echo "  • 进入容器: docker exec -it <容器名> /bin/bash"
echo "  • 查看容器状态: docker stats"
echo ""
echo "📝 备注:"
echo "  • 绿色 ✓ 表示连接正常"
echo "  • 红色 ✗ 表示连接失败"
echo "  • 黄色 ⚠️  表示需要注意的状态"
echo ""
echo "✅ 报告生成完成"