#!/bin/bash
################################################################################
# 定时任务检测模块
# 功能: 检测crontab任务、systemd定时器等定时任务配置
# 作者: Claude Code
# 日期: 2026-05-09
################################################################################

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

# ==================== 检测函数 ====================

# 检测crontab任务
check_crontab() {
    local crontab_count=0
    local crontab_list=""

    if command -v crontab &> /dev/null; then
        # 获取当前用户的crontab
        local crontab_output
        crontab_output=$(crontab -l 2>/dev/null)

        if [ -n "$crontab_output" ]; then
            # 统计非注释行
            crontab_count=$(echo "$crontab_output" | grep -v "^#" | grep -v "^$" | wc -l)

            # 获取任务列表（前10个）
            crontab_list=$(echo "$crontab_output" | grep -v "^#" | grep -v "^$" | head -10)

            output_result "CRONTAB_COUNT" "$crontab_count"

            if [ -n "$crontab_list" ]; then
                output_result "CRONTAB_LIST" "已获取"
            fi
        else
            output_result "CRONTAB_COUNT" "0"
            output_result "CRONTAB_STATUS" "无任务"
        fi
    else
        output_result "CRONTAB_STATUS" "未安装"
    fi

    output_result "CRONTAB_LEVEL" "正常"
}

# 检测systemd定时器
check_systemd_timers() {
    local timer_count=0
    local active_timers=0

    if command -v systemctl &> /dev/null; then
        # 获取定时器列表
        local timer_list
        timer_list=$(systemctl list-timers --no-pager 2>/dev/null | tail -n +2 | head -10)

        if [ -n "$timer_list" ]; then
            timer_count=$(echo "$timer_list" | wc -l)
            active_timers=$(echo "$timer_list" | grep -c "ACTIVE" || echo "0")

            output_result "SYSTEMD_TIMERS" "$timer_count"
            output_result "SYSTEMD_TIMERS_ACTIVE" "$active_timers"
        else
            output_result "SYSTEMD_TIMERS" "0"
        fi
    else
        output_result "SYSTEMD_TIMERS" "systemctl不可用"
    fi

    output_result "SYSTEMD_TIMERS_LEVEL" "正常"
}

# 检测anacron任务
check_anacron() {
    local anacron_status="未安装"

    if [ -f /etc/anacrontab ]; then
        anacron_status="已配置"

        # 统计任务数量
        local anacron_count
        anacron_count=$(grep -v "^#" /etc/anacrontab 2>/dev/null | grep -v "^$" | wc -l)

        output_result "ANACRON_COUNT" "$anacron_count"
    else
        output_result "ANACRON_STATUS" "$anacron_status"
    fi
}

# 检测at任务
check_at_jobs() {
    local at_count=0

    if command -v at &> /dev/null; then
        # 获取at任务列表
        at_count=$(at -l 2>/dev/null | wc -l)

        output_result "AT_JOBS" "$at_count"
    else
        output_result "AT_JOBS" "未安装"
    fi

    output_result "AT_JOBS_LEVEL" "正常"
}

# 检测crond服务状态
check_crond_status() {
    local crond_status="未知"
    local crond_service=""

    if command -v systemctl &> /dev/null; then
        # 检查crond服务
        if systemctl is-active cron &> /dev/null; then
            crond_service="cron"
            crond_status="运行中"
        elif systemctl is-active crond &> /dev/null; then
            crond_service="crond"
            crond_status="运行中"
        else
            crond_status="未运行"
        fi
    fi

    output_result "CROND_SERVICE" "$crond_service"
    output_result "CROND_STATUS" "$crond_status"

    if [ "$crond_status" = "未运行" ]; then
        output_result "CROND_LEVEL" "警告"
    else
        output_result "CROND_LEVEL" "正常"
    fi
}

# 检测系统级crontab
check_system_crontab() {
    local system_cron_count=0
    local cron_dirs=("/etc/cron.d" "/etc/cron.hourly" "/etc/cron.daily" "/etc/cron.weekly" "/etc/cron.monthly")

    for dir in "${cron_dirs[@]}"; do
        if [ -d "$dir" ]; then
            local count
            count=$(find "$dir" -type f 2>/dev/null | wc -l)
            system_cron_count=$((system_cron_count + count))
        fi
    done

    output_result "SYSTEM_CRON_COUNT" "$system_cron_count"

    # 检查/etc/crontab
    if [ -f /etc/crontab ]; then
        local crontab_entries
        crontab_entries=$(grep -v "^#" /etc/crontab 2>/dev/null | grep -v "^$" | wc -l)
        output_result "ETC_CRONTAB_ENTRIES" "$crontab_entries"
    fi
}

# 检测定时任务日志
check_cron_logs() {
    local cron_errors=0

    if command -v journalctl &> /dev/null; then
        # 检查cron相关日志中的错误
        cron_errors=$(journalctl --since '24 hours ago' -u cron -u crond 2>/dev/null | grep -ci "error" || echo "0")
    fi

    output_result "CRON_ERRORS_24H" "$cron_errors"

    if [ "$cron_errors" -gt 10 ]; then
        output_result "CRON_LOGS_LEVEL" "警告"
    else
        output_result "CRON_LOGS_LEVEL" "正常"
    fi
}

# ==================== 主检测流程 ====================
main() {
    log_info "开始定时任务检测..."

    # 执行各项检测
    check_crontab
    check_systemd_timers
    check_anacron
    check_at_jobs
    check_crond_status
    check_system_crontab
    check_cron_logs

    log_info "定时任务检测完成"
}

# 执行主函数
main
