#!/bin/bash

# 部署健康检查脚本

echo "================================================"
echo "KT财务系统部署健康检查"
echo "================================================"
echo ""

TARGET_HOST="172.16.74.149"
TARGET_PORT="8080"
MAX_RETRIES=10
RETRY_INTERVAL=5

echo "🔍 检查目标: http://${TARGET_HOST}:${TARGET_PORT}"
echo ""

# 1. 网络连通性检查
echo "1️⃣ 检查网络连通性..."
if ping -c 3 $TARGET_HOST > /dev/null 2>&1; then
    echo "   ✅ 主机 $TARGET_HOST 可达"
else
    echo "   ❌ 主机 $TARGET_HOST 不可达"
    exit 1
fi

# 2. 端口检查
echo ""
echo "2️⃣ 检查端口连接 (${MAX_RETRIES}次重试)..."
for i in $(seq 1 $MAX_RETRIES); do
    echo "   尝试 $i/$MAX_RETRIES..."

    if nc -zv -w 3 $TARGET_HOST $TARGET_PORT 2>&1 | grep -q "succeeded\|Connected"; then
        echo "   ✅ 端口 $TARGET_PORT 已开放"
        PORT_OPEN=true
        break
    fi

    if [ $i -lt $MAX_RETRIES ]; then
        echo "   ⏳ 等待 ${RETRY_INTERVAL}秒后重试..."
        sleep $RETRY_INTERVAL
    fi
done

if [ "$PORT_OPEN" != "true" ]; then
    echo "   ❌ 端口 $TARGET_PORT 无法连接"
    echo ""
    echo "⚠️ 可能的原因:"
    echo "   - Docker容器未启动"
    echo "   - 端口映射配置错误"
    echo "   - 防火墙阻止连接"
    echo "   - 服务启动失败"
    exit 1
fi

# 3. HTTP服务检查
echo ""
echo "3️⃣ 检查HTTP服务..."
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 http://${TARGET_HOST}:${TARGET_PORT}/ 2>/dev/null)

if [ -z "$HTTP_CODE" ]; then
    echo "   ❌ 无法获取HTTP响应"
    exit 1
fi

echo "   HTTP状态码: $HTTP_CODE"

if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "301" ] || [ "$HTTP_CODE" = "302" ]; then
    echo "   ✅ HTTP服务正常"
else
    echo "   ⚠️ HTTP状态码异常: $HTTP_CODE"
fi

# 4. 响应时间检查
echo ""
echo "4️⃣ 检查响应时间..."
RESPONSE_TIME=$(curl -s -o /dev/null -w "%{time_total}" --connect-timeout 5 http://${TARGET_HOST}:${TARGET_PORT}/ 2>/dev/null)

if [ -n "$RESPONSE_TIME" ]; then
    echo "   响应时间: ${RESPONSE_TIME}秒"

    if [ $(echo "$RESPONSE_TIME < 3" | bc) -eq 1 ]; then
        echo "   ✅ 响应时间正常"
    else
        echo "   ⚠️ 响应时间较慢"
    fi
fi

echo ""
echo "================================================"
echo "✅ 部署健康检查完成"
echo "================================================"
echo ""
echo "🌐 访问地址: http://${TARGET_HOST}:${TARGET_PORT}"
