#!/bin/bash

# 检查服务连接性脚本

PORT=12240
SERVER_IP="119.45.30.82"

echo "=== 检查服务连接性 ==="
echo ""

# 1. 检查服务是否在运行
echo "1. 检查服务进程..."
PID=$(ps aux | grep cattletends | grep -v grep | awk '{print $2}')
if [ -n "$PID" ]; then
    echo "   ✓ 服务正在运行，PID: $PID"
else
    echo "   ✗ 服务未运行"
    exit 1
fi

echo ""

# 2. 检查端口是否监听
echo "2. 检查端口 $PORT 监听状态..."
LISTENING=$(netstat -tlnp 2>/dev/null | grep ":$PORT " || ss -tlnp 2>/dev/null | grep ":$PORT ")
if [ -n "$LISTENING" ]; then
    echo "   ✓ 端口 $PORT 正在监听"
    echo "   详细信息:"
    echo "$LISTENING" | sed 's/^/   /'
    
    # 检查监听地址
    if echo "$LISTENING" | grep -q "0.0.0.0:$PORT\|:::$PORT"; then
        echo "   ✓ 服务监听在所有网络接口上（0.0.0.0），可以从外部访问"
    elif echo "$LISTENING" | grep -q "127.0.0.1:$PORT\|localhost:$PORT"; then
        echo "   ⚠ 服务只监听在 localhost，无法从外部访问"
        echo "   需要修改配置监听 0.0.0.0"
    fi
else
    echo "   ✗ 端口 $PORT 未监听"
    exit 1
fi

echo ""

# 3. 本地测试
echo "3. 本地连接测试..."
if curl -s -o /dev/null -w "%{http_code}" http://localhost:$PORT/api/cattle-data | grep -q "200\|404"; then
    echo "   ✓ 本地连接成功"
else
    echo "   ✗ 本地连接失败"
fi

echo ""

# 4. 检查防火墙
echo "4. 检查防火墙状态..."
if command -v firewall-cmd &> /dev/null; then
    FIREWALL_STATUS=$(firewall-cmd --state 2>/dev/null)
    if [ "$FIREWALL_STATUS" = "running" ]; then
        echo "   ⚠ Firewalld 正在运行"
        PORT_OPEN=$(firewall-cmd --query-port=$PORT/tcp 2>/dev/null)
        if [ "$PORT_OPEN" = "yes" ]; then
            echo "   ✓ 端口 $PORT 已在防火墙中开放"
        else
            echo "   ✗ 端口 $PORT 未在防火墙中开放"
            echo ""
            echo "   执行以下命令开放端口:"
            echo "   firewall-cmd --add-port=$PORT/tcp --permanent"
            echo "   firewall-cmd --reload"
        fi
    else
        echo "   ℹ Firewalld 未运行或未安装"
    fi
fi

echo ""

# 5. 检查 iptables
if command -v iptables &> /dev/null; then
    IPTABLES_RULE=$(iptables -L INPUT -n | grep "$PORT" || iptables -L INPUT -n | grep "ACCEPT.*tcp")
    if [ -n "$IPTABLES_RULE" ]; then
        echo "   ℹ 检测到 iptables 规则"
    fi
fi

echo ""

# 6. 网络接口检查
echo "5. 网络接口信息..."
IP_ADDR=$(hostname -I | awk '{print $1}' 2>/dev/null || ip addr show | grep "inet " | grep -v "127.0.0.1" | head -1 | awk '{print $2}' | cut -d'/' -f1)
if [ -n "$IP_ADDR" ]; then
    echo "   服务器IP地址: $IP_ADDR"
    if [ "$IP_ADDR" = "$SERVER_IP" ]; then
        echo "   ✓ IP地址匹配"
    else
        echo "   ⚠ IP地址不匹配，请确认服务器IP是否正确"
    fi
fi

echo ""
echo "=== 检查完成 ==="
echo ""
echo "如果本地测试成功但外部无法访问，请检查："
echo "1. 云服务器安全组是否开放 $PORT 端口"
echo "2. 服务器防火墙是否开放 $PORT 端口"
echo "3. 服务是否监听在 0.0.0.0 而不是 127.0.0.1"

