#!/bin/bash
# Customer Service 健康检查脚本

SERVICE_NAME="customer-service"
SERVICE_PORT=8086
MAX_RETRIES=30
RETRY_INTERVAL=2

echo "开始检查 $SERVICE_NAME 服务健康状态..."

# 检查服务端口是否开放
check_port() {
    nc -z localhost $SERVICE_PORT
    return $?
}

# 获取健康检查端点
check_health() {
    response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:$SERVICE_PORT/customer/actuator/health)
    if [ "$response" = "200" ]; then
        return 0
    else
        return 1
    fi
}

# 等待服务启动
retry_count=0
while [ $retry_count -lt $MAX_RETRIES ]; do
    if check_port; then
        echo "服务端口 $SERVICE_PORT 已开放"
        
        # 等待服务完全启动
        sleep 5
        
        if check_health; then
            echo "$SERVICE_NAME 服务健康检查通过"
            exit 0
        else
            echo "服务健康检查失败，HTTP状态码异常"
        fi
    else
        echo "等待服务启动... ($((retry_count + 1))/$MAX_RETRIES)"
    fi
    
    retry_count=$((retry_count + 1))
    sleep $RETRY_INTERVAL
done

echo "$SERVICE_NAME 服务启动超时或健康检查失败"
exit 1
