#!/bin/bash
################################################################################
# 52_config_ip_check.sh — 配置IP检测
# 功能: 扫描配置文件中的未授权 IP 地址
# 参考: ConfigIPCheck.psm1, config_check.sh
# 日期: 2026-07-22
# 说明: 遍历平台配置目录，提取 IP 与允许列表对比，输出未授权 IP 明细
#       允许列表 = 服务器IP + 127.0.0.1 + 172.17.0.1
################################################################################

# 获取脚本所在目录并加载依赖
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LIB_DIR="${LIB_DIR:-/tmp/check_modules}"

# 加载配置文件和通用函数库
if [ -f "$LIB_DIR/lib/config.sh" ]; then
    source "$LIB_DIR/lib/config.sh"
else
    echo "ERROR: 配置文件不存在: $LIB_DIR/lib/config.sh"
    exit 1
fi

if [ -f "$LIB_DIR/lib/common.sh" ]; then
    source "$LIB_DIR/lib/common.sh"
else
    echo "ERROR: 通用函数库不存在: $LIB_DIR/lib/common.sh"
    exit 1
fi

# IP 正则
IP_REGEX='([0-9]{1,3}\.){3}[0-9]{1,3}'

# 允许列表（SERVER_IP 从 config.sh 注入，默认为空）
ALLOWED_IPS="${SERVER_IP} 127.0.0.1 172.17.0.1"

# ==================== 配置目录定义 ====================

# 新平台配置目录
NEW_PLATFORM_CONFIG_DIRS=(
    "/data/services/api/auth/auth-sso-auth/config"
    "/data/services/api/auth/auth-sso-gateway/config"
    "/data/services/api/auth/auth-sso-system/config"
    "/data/services/api/java-meeting/java-meeting2.0/config"
    "/data/services/api/java-meeting/java-meeting-extapi/config"
    "/data/services/api/java-meeting/java-message-scheduling/config"
    "/data/services/api/java-meeting/java-mqtt/config"
    "/data/services/api/java-meeting/java-quartz/config"
    "/data/services/api/python-cmdb"
    "/data/services/web/pc/pc-vue2-ai/static"
    "/data/services/web/mobile/mobile-vue2/static"
    "/data/middleware/nginx/config"
)

# 传统平台配置目录
OLD_PLATFORM_CONFIG_DIRS=(
    "/var/www/java/api-java-meeting2.0/config"
    "/var/www/java/external-meeting-api/config"
    "/var/www/java/ubains-web-2.0/static"
    "/var/www/java/ubains-web-admin/static"
    "/var/www/java/ubains-web-h5/static/h5"
    "/var/www/java/nginx-conf.d"
)

# ==================== 平台类型识别 ====================

detect_platform_type() {
    [ -d "/data/services" ] && echo "new" || echo "old"
}

# ==================== IP 扫描 ====================

scan_config_ips() {
    local platform_type="$1"
    local -a config_dirs

    if [ "$platform_type" = "new" ]; then
        config_dirs=("${NEW_PLATFORM_CONFIG_DIRS[@]}")
    else
        config_dirs=("${OLD_PLATFORM_CONFIG_DIRS[@]}")
    fi

    local total_files=0
    local unauthorized_count=0
    local unauthorized_lines=""

    for dir in "${config_dirs[@]}"; do
        if [ ! -d "$dir" ]; then
            continue
        fi

        while IFS= read -r file; do
            [ -z "$file" ] && continue
            [ ! -r "$file" ] && continue

            total_files=$((total_files + 1))

            local line_num=0
            while IFS= read -r line; do
                line_num=$((line_num + 1))

                # 提取行中的 IP
                local ips
                ips=$(echo "$line" | grep -oE "$IP_REGEX" 2>/dev/null)

                for ip in $ips; do
                    # 检查是否在允许列表
                    if ! echo " $ALLOWED_IPS " | grep -qF " $ip "; then
                        unauthorized_count=$((unauthorized_count + 1))
                        # 转义文件路径中的特殊字符
                        local escaped_file
                        escaped_file=$(echo "$file" | sed 's/"/\\"/g')
                        if [ -n "$unauthorized_lines" ]; then
                            unauthorized_lines="${unauthorized_lines},"
                        fi
                        unauthorized_lines="${unauthorized_lines}{\"file\":\"${escaped_file}\",\"line\":${line_num},\"ip\":\"${ip}\"}"
                    fi
                done
            done < "$file"
        done < <(find "$dir" -type f \( -name "*.yml" -o -name "*.properties" -o -name "config.js" -o -name "config.json" -o -name "*.conf" \) 2>/dev/null)
    done

    # 输出结果
    if [ "$unauthorized_count" -eq 0 ]; then
        output_result "CFG_IP_STATUS" "OK"
        output_result "CFG_IP_STATUS_LEVEL" "正常"
    else
        output_result "CFG_IP_STATUS" "WARN"
        output_result "CFG_IP_STATUS_LEVEL" "警告"
    fi

    output_result "CFG_IP_TOTAL_FILES" "$total_files"
    output_result "CFG_IP_UNAUTHORIZED_COUNT" "$unauthorized_count"

    # JSON 数组输出
    if [ -n "$unauthorized_lines" ]; then
        output_result "CFG_IP_UNAUTHORIZED_LINES" "[${unauthorized_lines}]"
    else
        output_result "CFG_IP_UNAUTHORIZED_LINES" "[]"
    fi
}

# ==================== 主检测流程 ====================

main() {
    log_info "开始配置IP检测..."

    set +e

    local platform_type
    platform_type=$(detect_platform_type)
    scan_config_ips "$platform_type"

    log_info "配置IP检测完成"
}

main
