#!/bin/bash

# 考陪练系统数据库备份状态检查脚本
# 作者: AI Assistant
# 日期: 2025-09-23

BACKUP_DIR="/root/aiedu/kaopeilian-backend/backups"
LOG_FILE="${BACKUP_DIR}/check_status.log"

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "${LOG_FILE}"
}

# 检查最近的备份文件
check_recent_backup() {
    local recent_backup=$(find "${BACKUP_DIR}" -name "kaopeilian_backup_*.sql.gz" -type f -mtime -1 | sort | tail -1)
    
    if [ -n "${recent_backup}" ]; then
        local backup_time=$(stat -c %Y "${recent_backup}")
        local current_time=$(date +%s)
        local time_diff=$((current_time - backup_time))
        local hours_diff=$((time_diff / 3600))
        
        log "最近备份: $(basename ${recent_backup})"
        log "备份时间: $(stat -c %y "${recent_backup}")"
        log "距离现在: ${hours_diff} 小时前"
        
        if [ ${hours_diff} -gt 2 ]; then
            log "WARNING: 备份文件超过2小时未更新"
            return 1
        else
            log "备份状态: 正常"
            return 0
        fi
    else
        log "ERROR: 未找到最近的备份文件"
        return 1
    fi
}

# 检查备份文件大小
check_backup_size() {
    local recent_backup=$(find "${BACKUP_DIR}" -name "kaopeilian_backup_*.sql.gz" -type f -mtime -1 | sort | tail -1)
    
    if [ -n "${recent_backup}" ]; then
        local backup_size=$(stat -c %s "${recent_backup}")
        local backup_size_mb=$((backup_size / 1024 / 1024))
        
        log "备份文件大小: ${backup_size_mb}MB"
        
        if [ ${backup_size_mb} -lt 1 ]; then
            log "WARNING: 备份文件过小，可能不完整"
            return 1
        else
            log "备份文件大小: 正常"
            return 0
        fi
    fi
}

# 检查定时任务状态
check_cron_status() {
    if crontab -l | grep -q "backup_database.sh"; then
        log "定时任务: 已配置"
        return 0
    else
        log "ERROR: 定时任务未配置"
        return 1
    fi
}

# 检查systemd定时器状态
check_systemd_timer() {
    if systemctl is-active kaopeilian-backup.timer >/dev/null 2>&1; then
        log "Systemd定时器: 运行中"
        
        # 获取下次执行时间
        local next_run=$(systemctl list-timers kaopeilian-backup.timer --no-pager | grep kaopeilian-backup.timer | awk '{print $1, $2}')
        log "下次执行时间: ${next_run}"
        
        return 0
    else
        log "ERROR: Systemd定时器未运行"
        return 1
    fi
}

# 检查Docker容器状态
check_docker_container() {
    if docker ps | grep -q "kaopeilian_mysql"; then
        log "MySQL容器: 运行中"
        return 0
    else
        log "ERROR: MySQL容器未运行"
        return 1
    fi
}

# 主检查函数
main() {
    log "========== 备份状态检查开始 =========="
    
    local exit_code=0
    
    # 执行各项检查
    check_recent_backup || exit_code=1
    check_backup_size || exit_code=1
    check_cron_status || exit_code=1
    check_systemd_timer || exit_code=1
    check_docker_container || exit_code=1
    
    if [ ${exit_code} -eq 0 ]; then
        log "========== 备份状态检查完成: 全部正常 =========="
    else
        log "========== 备份状态检查完成: 发现问题 =========="
    fi
    
    return ${exit_code}
}

# 执行主函数
main "$@"
