#!/bin/bash
################################################################################
# 23_mysql_depth.sh — MySQL深度检测
# 功能: 检测MySQL缓冲池、慢查询、连接、主从、大表、QPS等深度指标
# 参考: MiddlewareCheck.psm1 / check_mysql_deep.sh 移植
################################################################################

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: config.sh not found"; exit 1; fi
if [ -f "$LIB_DIR/lib/common.sh" ]; then source "$LIB_DIR/lib/common.sh"; else echo "ERROR: common.sh not found"; exit 1; fi

MYSQL_PWD="${MYSQL_PASSWORD:-}"
CONTAINER="${CONTAINERS[mysql]:-mysql}"
MYSQL_CMD="docker exec -e MYSQL_PWD=\"$MYSQL_PWD\" $CONTAINER mysql -uroot -N"

# 运行时间
UPTIME=$(eval $MYSQL_CMD -e "SHOW STATUS LIKE 'Uptime';" 2>/dev/null | awk '{print $2}')
if [ -n "$UPTIME" ] && [ "$UPTIME" -gt 0 ]; then
    UPTIME_DAYS=$((UPTIME / 86400))
    output_result "MYSQL_DEPTH_UPTIME_DAYS" "$UPTIME_DAYS"
fi

# QPS
QUESTIONS=$(eval $MYSQL_CMD -e "SHOW GLOBAL STATUS LIKE 'Questions';" 2>/dev/null | awk '{print $2}')
if [ -n "$QUESTIONS" ] && [ -n "$UPTIME" ] && [ "$UPTIME" -gt 0 ]; then
    QPS=$(awk "BEGIN {printf \"%.2f\", $QUESTIONS/$UPTIME}")
    output_result "MYSQL_DEPTH_QPS" "$QPS"
fi

# TPS
COM_COMMIT=$(eval $MYSQL_CMD -e "SHOW GLOBAL STATUS LIKE 'Com_commit';" 2>/dev/null | awk '{print $2}')
COM_ROLLBACK=$(eval $MYSQL_CMD -e "SHOW GLOBAL STATUS LIKE 'Com_rollback';" 2>/dev/null | awk '{print $2}')
if [ -n "$COM_COMMIT" ] && [ -n "$COM_ROLLBACK" ] && [ -n "$UPTIME" ] && [ "$UPTIME" -gt 0 ]; then
    TOTAL_TRANS=$((COM_COMMIT + COM_ROLLBACK))
    TPS=$(awk "BEGIN {printf \"%.2f\", $TOTAL_TRANS/$UPTIME}")
    output_result "MYSQL_DEPTH_TPS" "$TPS"
fi

# 连接数
THREADS_CONNECTED=$(eval $MYSQL_CMD -e "SHOW STATUS LIKE 'Threads_connected';" 2>/dev/null | awk '{print $2}')
MAX_CONNECTIONS=$(eval $MYSQL_CMD -e "SHOW VARIABLES LIKE 'max_connections';" 2>/dev/null | awk '{print $2}')
if [ -n "$THREADS_CONNECTED" ] && [ -n "$MAX_CONNECTIONS" ] && [ "$MAX_CONNECTIONS" -gt 0 ]; then
    CONN_PERCENT=$(awk "BEGIN {printf \"%.1f\", $THREADS_CONNECTED*100/$MAX_CONNECTIONS}")
    output_result "MYSQL_DEPTH_CONNECTION_USAGE" "$CONN_PERCENT"
    output_result "MYSQL_DEPTH_CONNECTIONS" "$THREADS_CONNECTED/$MAX_CONNECTIONS"
fi

# 慢查询
SLOW_QUERIES=$(eval $MYSQL_CMD -e "SHOW GLOBAL STATUS LIKE 'Slow_queries';" 2>/dev/null | awk '{print $2}')
output_result "MYSQL_DEPTH_SLOW_QUERY_COUNT" "${SLOW_QUERIES:-0}"

# 慢查询是否开启
SLOW_QUERY_LOG=$(eval $MYSQL_CMD -e "SHOW VARIABLES LIKE 'slow_query_log';" 2>/dev/null | awk '{print $2}')
output_result "MYSQL_DEPTH_SLOW_QUERY_ENABLED" "${SLOW_QUERY_LOG:-OFF}"

# 死锁
DEADLOCK_OUTPUT=$(eval $MYSQL_CMD -e "SHOW GLOBAL STATUS LIKE 'Innodb_deadlocks';" 2>/dev/null | awk '{print $2}')
output_result "MYSQL_DEPTH_DEADLOCKS" "${DEADLOCK_OUTPUT:-0}"

# Buffer Pool 命中率
BP_READS=$(eval $MYSQL_CMD -e "SELECT variable_value FROM performance_schema.global_status WHERE variable_name = 'Innodb_buffer_pool_reads';" 2>/dev/null)
BP_REQUESTS=$(eval $MYSQL_CMD -e "SELECT variable_value FROM performance_schema.global_status WHERE variable_name = 'Innodb_buffer_pool_read_requests';" 2>/dev/null)
if [ -n "$BP_REQUESTS" ] && [ "$BP_REQUESTS" -gt 0 ] 2>/dev/null; then
    HIT_RATE=$(awk "BEGIN {printf \"%.2f\", (1 - ${BP_READS:-0}/$BP_REQUESTS)*100}")
    output_result "MYSQL_DEPTH_BUFFER_POOL_HIT_RATE" "$HIT_RATE"
fi

# 表缓存命中率
OPEN_TABLES=$(eval $MYSQL_CMD -e "SHOW GLOBAL STATUS LIKE 'Open_tables';" 2>/dev/null | awk '{print $2}')
OPENED_TABLES=$(eval $MYSQL_CMD -e "SHOW GLOBAL STATUS LIKE 'Opened_tables';" 2>/dev/null | awk '{print $2}')
if [ -n "$OPEN_TABLES" ] && [ -n "$OPENED_TABLES" ] && [ "$OPENED_TABLES" -ge 0 ] 2>/dev/null; then
    if [ "$OPENED_TABLES" -eq 0 ]; then
        output_result "MYSQL_DEPTH_CACHE_HIT_RATE" "100.00"
    elif [ "$OPEN_TABLES" -gt 0 ]; then
        TOTAL_OPENS=$((OPEN_TABLES + OPENED_TABLES))
        CACHE_HIT_RATE=$(awk "BEGIN {printf \"%.2f\", ($OPEN_TABLES*100)/$TOTAL_OPENS}")
        output_result "MYSQL_DEPTH_CACHE_HIT_RATE" "$CACHE_HIT_RATE"
    fi
fi

# 活跃查询数
ACTIVE_QUERIES=$(eval $MYSQL_CMD -e "SHOW PROCESSLIST;" 2>/dev/null | grep -v "Sleep" | grep -v "binlog" | wc -l)
output_result "MYSQL_DEPTH_ACTIVE_QUERIES" "$ACTIVE_QUERIES"

# Binlog状态
BINLOG_STATUS=$(eval $MYSQL_CMD -e "SHOW VARIABLES LIKE 'log_bin';" 2>/dev/null | awk '{print $2}')
if [ "$BINLOG_STATUS" = "ON" ]; then
    BINLOG_COUNT=$(eval $MYSQL_CMD -e "SHOW BINARY LOGS;" 2>/dev/null | wc -l)
    output_result "MYSQL_DEPTH_BINLOG_STATUS" "ON/${BINLOG_COUNT}"
    BINLOG_EXPIRE=$(eval $MYSQL_CMD -e "SHOW VARIABLES LIKE 'expire_logs_days';" 2>/dev/null | awk '{print $2}')
    output_result "MYSQL_DEPTH_BINLOG_EXPIRE_DAYS" "${BINLOG_EXPIRE:-0}"
else
    output_result "MYSQL_DEPTH_BINLOG_STATUS" "OFF"
fi

# 表碎片
FRAGMENTED_TABLES=$(eval $MYSQL_CMD -e "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','performance_schema','mysql','sys') AND DATA_FREE > 10485760;" 2>/dev/null)
output_result "MYSQL_DEPTH_FRAGMENTED_TABLES" "${FRAGMENTED_TABLES:-0}"

# 连接错误
CONN_ERRORS=$(eval $MYSQL_CMD -e "SHOW STATUS LIKE 'Aborted_connects';" 2>/dev/null | awk '{print $2}')
output_result "MYSQL_DEPTH_CONN_ERRORS" "${CONN_ERRORS:-0}"

# InnoDB缓冲池大小
INNODB_BP_SIZE=$(eval $MYSQL_CMD -e "SHOW VARIABLES LIKE 'innodb_buffer_pool_size';" 2>/dev/null | awk '{print $2}')
if [ -n "$INNODB_BP_SIZE" ] && [ "$INNODB_BP_SIZE" -gt 0 ] 2>/dev/null; then
    BP_SIZE_MB=$((INNODB_BP_SIZE / 1024 / 1024))
    output_result "MYSQL_DEPTH_INNODB_BP_SIZE" "${BP_SIZE_MB}MB"
fi

# 活跃事务
TRX_ACTIVE=$(eval $MYSQL_CMD -e "SHOW STATUS LIKE 'Innodb_trx_active';" 2>/dev/null | awk '{print $2}')
output_result "MYSQL_DEPTH_TRX_ACTIVE" "${TRX_ACTIVE:-0}"

# 锁等待
LOCK_WAITS=$(eval $MYSQL_CMD -e "SHOW STATUS LIKE 'Innodb_row_lock_current_waits';" 2>/dev/null | awk '{print $2}')
output_result "MYSQL_DEPTH_LOCK_WAITS" "${LOCK_WAITS:-0}"

# 数据库总大小
DB_SIZE=$(eval $MYSQL_CMD -e "SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','performance_schema','mysql','sys');" 2>/dev/null)
if [ -n "$DB_SIZE" ]; then
    output_result "MYSQL_DEPTH_DATABASE_SIZE" "${DB_SIZE}MB"
fi

# 表总数
TABLE_COUNT=$(eval $MYSQL_CMD -e "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','performance_schema','mysql','sys') AND TABLE_TYPE='BASE TABLE';" 2>/dev/null)
output_result "MYSQL_DEPTH_TABLE_COUNT" "${TABLE_COUNT:-0}"

# 复制状态
SLAVE_IO=$(eval $MYSQL_CMD -e "SHOW SLAVE STATUS\G" 2>/dev/null | grep "Slave_IO_Running:" | awk '{print $2}')
if [ "$SLAVE_IO" = "Yes" ]; then
    output_result "MYSQL_DEPTH_REPLICATION_STATUS" "SLAVE"
    SLAVE_SQL=$(eval $MYSQL_CMD -e "SHOW SLAVE STATUS\G" 2>/dev/null | grep "Slave_SQL_Running:" | awk '{print $2}')
    BEHIND_MASTER=$(eval $MYSQL_CMD -e "SHOW SLAVE STATUS\G" 2>/dev/null | grep "Seconds_Behind_Master:" | awk '{print $2}')
    output_result "MYSQL_DEPTH_SLAVE_IO_RUNNING" "${SLAVE_IO:-No}"
    output_result "MYSQL_DEPTH_SLAVE_SQL_RUNNING" "${SLAVE_SQL:-No}"
    output_result "MYSQL_DEPTH_SLAVE_DELAY" "${BEHIND_MASTER:-0}"
else
    output_result "MYSQL_DEPTH_REPLICATION_STATUS" "MASTER"
fi

# 进程列表摘要
PROCESSLIST_OUTPUT=$(eval $MYSQL_CMD -e "SHOW PROCESSLIST;" 2>/dev/null)
if [ -n "$PROCESSLIST_OUTPUT" ]; then
    SLEEP_COUNT=$(echo "$PROCESSLIST_OUTPUT" | grep -c "Sleep" || echo "0")
    QUERY_ACTIVE=$(echo "$PROCESSLIST_OUTPUT" | grep -v "Sleep" | wc -l)
    output_result "MYSQL_DEPTH_ACTIVE_PROCESSLIST" "Sleep:${SLEEP_COUNT},Active:${QUERY_ACTIVE}"
fi

# 大表检测
TOP_TABLES=$(eval $MYSQL_CMD -e "SELECT table_name, ROUND((data_length + index_length) / 1024 / 1024, 2) AS total_mb FROM information_schema.TABLES WHERE TABLE_SCHEMA NOT IN ('information_schema','performance_schema','mysql','sys') ORDER BY (data_length + index_length) DESC LIMIT 5;" 2>/dev/null)
if [ -n "$TOP_TABLES" ]; then
    output_result "MYSQL_DEPTH_TOP_TABLES" "$(echo "$TOP_TABLES" | tr '\n' '|' | sed 's/|$//')"
fi

# 临时表使用率
TEMP_DISK=$(eval $MYSQL_CMD -e "SHOW STATUS LIKE 'Created_tmp_disk_tables';" 2>/dev/null | awk '{print $2}')
TEMP_TOTAL=$(eval $MYSQL_CMD -e "SHOW STATUS LIKE 'Created_tmp_tables';" 2>/dev/null | awk '{print $2}')
if [ -n "$TEMP_DISK" ] && [ -n "$TEMP_TOTAL" ] && [ "$TEMP_TOTAL" -gt 0 ] 2>/dev/null; then
    TEMP_RATE=$(awk "BEGIN {printf \"%.2f\", ($TEMP_DISK*100)/$TEMP_TOTAL}")
    output_result "MYSQL_DEPTH_TEMP_TABLE_RATE" "$TEMP_RATE"
fi

# 缺少索引的表
MISSING_INDEX=$(eval $MYSQL_CMD -e "SELECT COUNT(*) FROM information_schema.TABLES t WHERE t.table_schema NOT IN ('information_schema','performance_schema','mysql','sys') AND NOT EXISTS (SELECT 1 FROM information_schema.STATISTICS s WHERE s.table_schema = t.table_schema AND s.table_name = t.table_name) AND t.table_rows > 1000;" 2>/dev/null)
output_result "MYSQL_DEPTH_TABLES_WITHOUT_INDEX" "${MISSING_INDEX:-0}"