#!/bin/bash

# 用法提示
usage() {
    echo "用法: $0 [-n 网卡名] [-p 端口列表]"
    echo "示例: "
    echo "  $0 -n eth0 -p \"80 443\"      # 检查指定网卡和端口"
    echo "  $0 -n eth1                   # 检查指定网卡的所有默认端口"
    echo "  $0 -p \"8080 8443\"           # 使用默认网卡检查指定端口"
}

# 网卡
get_nics() {
    if [ -f /tmp/multidialstatus.json ];then
        nics=$(cat /tmp/multidialstatus.json | jq -r .multidial[].practicnic | sort)
    fi
    # 
    if [ -z "${nics}" ];then
        if [ -f /app_config/resource_config.json ];then
           nics=$(cat /app_config/resource_config.json | jq .nic_list)
        fi
    fi
    #
    if [ -z "${nics}" ]; then
      nics=$(route -n | grep "^0.0.0.0" | awk '{print $8}')
    fi

    echo "${nics}"
}

# 主进程
main() {
    # 默认配置
    default_nic=$(get_nics)
    default_ports=(8888 8889 9928 9922 9923 1487)

    while getopts ":n:p:" opt;
    do
        case $opt in
            n)
              nic=${OPTARG}
              ;;
            p)
              custom_ports=${OPTARG}
              ;;
            \?)
              echo "无效选项: -${OPTARG}" >&2; usage; exit 1
              ;;
            :)
              echo "选项 -$OPTARG 需要参数." >&2; usage; exit 1
              ;;

        esac
    done

    # 设置最终参数
    nics="${nic:-$default_nic}"
    ports=("${custom_ports[@]:-${default_ports[@]}}")

    # 插件检查
    if [ ! -x /xyapp/system/miner.plugin-sysprobe.ipk/bin/revclient ]; then
        echo "错误： /xyapp/system/miner.plugin-sysprobe.ipk/bin 目录找不到可执行的 revclient 程序"
        exit 1
    fi

    # 执行检测
    for nic in ${nics}; do


        echo "正在检测网卡: $nic"
        echo "检查端口: ${ports[*]}"
        echo "--------------------------------"


        for port in "${ports[@]}"; do
            output=$(/xyapp/system/miner.plugin-sysprobe.ipk/bin/revclient -n "$nic" -I "$port" -A "$port"   2>/dev/null)

            # 提取字段
            mapped_addr=$(echo "$output" | sed -n 's/.*"mappedAddr":"\([^"]*\)".*/\1/p')

            # 输出：223.114.192.70:40837)
            p2p_reverse=$(echo "$output" | sed -n 's/.*"p2pReverse":\([^,}]*\).*/\1/p' )

            # 处理结果
            if [[ "$p2p_reverse" == "1" ]]; then
                status="OK"
            else
                status="FAIL"
            fi

            # 统一输出格式
            printf "%-8s => %-20s [%s]\n" "$port" "${mapped_addr:-N/A}" "$status"

            sleep 1s
        done
    done
}

# 入口
main "$@"
