#!/bin/bash
################################################################################
# 59_log_export_check.sh — 配置日志导出检测
# 功能: 检测关键配置文件和日志目录是否存在、大小、最近修改时间
# 参考: LogExport.psm1
# 日期: 2026-07-22
# 说明: 只检测不导出，验证配置和日志可获取性
################################################################################

# 获取脚本所在目录并加载依赖
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

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

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

# ==================== 配置文件检测 ====================

check_config_files() {
    local platform_type
    platform_type=$(detect_platform_type)

    local total=0
    local exists=0
    local missing_list=""

    local -a config_paths

    if [ "$platform_type" = "new" ]; then
        config_paths=(
            "/data/services/web/pc/pc-vue2-ai/static/config.json"
            "/data/services/web/pc/pc-vue2-backstage/static/config.json"
            "/data/services/web/pc/pc-vue2-main/static/config.json"
            "/data/services/web/pc/pc-vue2-meetingV2/static/config.json"
            "/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/python-cmdb/setting.conf"
            "/data/middleware/nginx/config"
            "/data/middleware/redis/config"
            "/data/middleware/emqx/config"
            "/data/middleware/mysql/conf"
            "/data/middleware/nacos/conf"
        )
    else
        config_paths=(
            "/var/www/java/ubains-web-2.0/static/config.json"
            "/var/www/java/ubains-web-admin/static/config.json"
            "/var/www/java/api-java-meeting2.0/config"
            "/var/www/java/external-meeting-api/config"
            "/var/www/html/setting.conf"
            "/var/www/java/nginx-conf.d"
            "/var/www/redis/redis.conf"
            "/var/www/emqx/config"
        )
    fi

    for path in "${config_paths[@]}"; do
        total=$((total + 1))
        if [ -e "$path" ]; then
            exists=$((exists + 1))
        else
            if [ -n "$missing_list" ]; then
                missing_list="${missing_list},"
            fi
            missing_list="${missing_list}${path}"
        fi
    done

    output_result "LOGEXP_CONFIG_TOTAL" "$total"
    output_result "LOGEXP_CONFIG_EXISTS" "$exists"
    output_result "LOGEXP_CONFIG_MISSING" "$((total - exists))"

    if [ "$exists" -eq "$total" ]; then
        output_result "LOGEXP_CONFIG_LEVEL" "正常"
    elif [ "$exists" -gt 0 ]; then
        output_result "LOGEXP_CONFIG_LEVEL" "警告"
    else
        output_result "LOGEXP_CONFIG_LEVEL" "严重"
    fi
}

# ==================== 日志目录检测 ====================

check_log_dirs() {
    local platform_type
    platform_type=$(detect_platform_type)

    local total=0
    local exists=0
    local oversized=0
    local log_info_list=""

    local -a log_paths

    if [ "$platform_type" = "new" ]; then
        log_paths=(
            "/data/services/api/auth/auth-sso-auth/log.out"
            "/data/services/api/auth/auth-sso-gateway/log.out"
            "/data/services/api/auth/auth-sso-system/log.out"
            "/data/services/api/java-meeting/java-meeting2.0/logs"
            "/data/services/api/java-meeting/java-meeting-extapi/logs"
            "/data/services/api/java-meeting/java-message-scheduling/logs"
            "/data/services/api/java-meeting/java-mqtt/logs"
            "/data/services/api/java-meeting/java-quartz/logs"
            "/data/services/api/python-cmdb/log"
            "/data/middleware/nginx/log"
            "/data/middleware/emqx/log"
            "/data/middleware/mysql/logs"
            "/data/middleware/nacos/logs"
        )
    else
        log_paths=(
            "/var/www/java/api-java-meeting2.0/logs"
            "/var/www/java/external-meeting-api/logs"
            "/var/www/html/log"
            "/var/www/emqx/log"
            "/usr/local/docker/mysql/logs"
        )
    fi

    for path in "${log_paths[@]}"; do
        total=$((total + 1))
        if [ -e "$path" ]; then
            exists=$((exists + 1))

            # 获取大小
            local size_human
            size_human=$(du -sh "$path" 2>/dev/null | cut -f1 || echo "0")

            # 检查是否过大（>1GB）
            local size_bytes
            size_bytes=$(du -sb "$path" 2>/dev/null | cut -f1 || echo "0")
            if [ "$size_bytes" -gt 1073741824 ]; then
                oversized=$((oversized + 1))
            fi
        fi
    done

    output_result "LOGEXP_LOG_TOTAL" "$total"
    output_result "LOGEXP_LOG_EXISTS" "$exists"
    output_result "LOGEXP_LOG_MISSING" "$((total - exists))"
    output_result "LOGEXP_LOG_OVERSIZED" "$oversized"

    if [ "$exists" -eq "$total" ] && [ "$oversized" -eq 0 ]; then
        output_result "LOGEXP_LOG_LEVEL" "正常"
    elif [ "$exists" -gt 0 ]; then
        output_result "LOGEXP_LOG_LEVEL" "警告"
    else
        output_result "LOGEXP_LOG_LEVEL" "严重"
    fi
}

# ==================== 关键日志大小检测 ====================

check_log_sizes() {
    local platform_type
    platform_type=$(detect_platform_type)

    local -a check_files

    if [ "$platform_type" = "new" ]; then
        check_files=(
            "/data/services/api/java-meeting/java-meeting2.0/logs/ubains-ERROR.log"
            "/data/services/api/java-meeting/java-meeting-extapi/logs/ubains-ERROR.log"
            "/data/services/api/python-cmdb/log/error.log"
        )
    else
        check_files=(
            "/var/www/java/api-java-meeting2.0/logs/ubains-ERROR.log"
            "/var/www/java/external-meeting-api/logs/ubains-ERROR.log"
            "/var/www/html/log/error.log"
        )
    fi

    local total_size=0
    local file_count=0

    for file in "${check_files[@]}"; do
        if [ -f "$file" ]; then
            local fsize
            fsize=$(stat -c '%s' "$file" 2>/dev/null || echo "0")
            total_size=$((total_size + fsize))
            file_count=$((file_count + 1))
        fi
    done

    # 转换为 MB
    local total_mb=$((total_size / 1048576))

    output_result "LOGEXP_ERROR_LOG_COUNT" "$file_count"
    output_result "LOGEXP_ERROR_LOG_SIZE_MB" "$total_mb"

    if [ "$total_mb" -gt 500 ]; then
        output_result "LOGEXP_ERROR_LOG_LEVEL" "警告"
    else
        output_result "LOGEXP_ERROR_LOG_LEVEL" "正常"
    fi
}

# ==================== 日志轮转配置检测 ====================

check_logrotate() {
    local rotate_ok="no"
    local rotate_config=""

    # 检查 logrotate 配置
    if [ -d "/etc/logrotate.d" ]; then
        local app_configs
        app_configs=$(ls /etc/logrotate.d/ 2>/dev/null | grep -iE "ubains|meeting|nginx|redis|mysql|emqx|nacos" | head -5 || echo "")
        if [ -n "$app_configs" ]; then
            rotate_ok="yes"
            rotate_config=$(echo "$app_configs" | tr '\n' ',' | sed 's/,$//')
        fi
    fi

    output_result "LOGEXP_LOGROTATE_OK" "$rotate_ok"
    output_result "LOGEXP_LOGROTATE_CONFIG" "${rotate_config:-无}"

    if [ "$rotate_ok" = "yes" ]; then
        output_result "LOGEXP_LOGROTATE_LEVEL" "正常"
    else
        output_result "LOGEXP_LOGROTATE_LEVEL" "警告"
    fi
}

# ==================== 导出能力检测 ====================

check_export_capability() {
    local tar_ok="no"
    local gzip_ok="no"

    # 检查打包工具
    if command -v tar >/dev/null 2>&1; then
        tar_ok="yes"
    fi

    if command -v gzip >/dev/null 2>&1; then
        gzip_ok="yes"
    fi

    output_result "LOGEXP_TAR_AVAILABLE" "$tar_ok"
    output_result "LOGEXP_GZIP_AVAILABLE" "$gzip_ok"

    if [ "$tar_ok" = "yes" ] && [ "$gzip_ok" = "yes" ]; then
        output_result "LOGEXP_EXPORT_CAPABLE" "yes"
        output_result "LOGEXP_EXPORT_LEVEL" "正常"
    else
        output_result "LOGEXP_EXPORT_CAPABLE" "no"
        output_result "LOGEXP_EXPORT_LEVEL" "警告"
    fi
}

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

main() {
    log_info "开始配置日志导出检测..."

    set +e

    # 1. 配置文件检测
    check_config_files

    # 2. 日志目录检测
    check_log_dirs

    # 3. 关键日志大小检测
    check_log_sizes

    # 4. 日志轮转配置检测
    check_logrotate

    # 5. 导出能力检测
    check_export_capability

    # 6. 综合状态
    output_result "LOGEXP_STATUS" "已检测"
    output_result "LOGEXP_STATUS_LEVEL" "正常"

    log_info "配置日志导出检测完成"
}

main