#!/bin/bash
################################################################################
# 55_cron_expected.sh — 定时任务预期检测
# 功能: 检查预期 crontab 条目是否存在
# 参考: check_server_health.sh (test_scheduled_tasks)
# 日期: 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"
}

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

main() {
    log_info "开始定时任务预期检测..."

    set +e

    local platform_type
    platform_type=$(detect_platform_type)

    # 预期 crontab 条目（匹配命令部分，不含时间）
    local -a expected_entries
    expected_entries=(
        "bash /usr/local/docker/UbainsmysqlBakUp.sh"
    )

    # 新平台额外期望 ujava2 守护脚本
    if [ "$platform_type" = "new" ]; then
        expected_entries+=("/data/services/scripts/ujava2-startup.sh")
    fi

    # 获取当前 crontab
    local current_crontab
    current_crontab=$(crontab -l 2>/dev/null || echo "")

    local total_expected=${#expected_entries[@]}
    local miss_count=0
    local miss_list=""

    for entry in "${expected_entries[@]}"; do
        if ! echo "$current_crontab" | grep -qF "$entry"; then
            miss_count=$((miss_count + 1))
            local escaped_entry
            escaped_entry=$(echo "$entry" | sed 's/"/\\"/g')
            [ -n "$miss_list" ] && miss_list="${miss_list},"
            miss_list="${miss_list}\"${escaped_entry}\""
        fi
    done

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

    output_result "CRON_EXPECTED_TOTAL" "$total_expected"
    output_result "CRON_EXPECTED_MISS_COUNT" "$miss_count"

    if [ -n "$miss_list" ]; then
        output_result "CRON_EXPECTED_MISS_LIST" "[${miss_list}]"
    else
        output_result "CRON_EXPECTED_MISS_LIST" "[]"
    fi

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

main