#!/bin/bash
# =============================================================================
# WOOO AIOps - AWOOOI 高頻備份（每 6 小時）
# 2026-04-05 Claude Code: awoooi_prod 為核心生產 DB，每日一次不夠
# 部署位置: /backup/scripts/backup-awoooi-frequent.sh (on 192.168.0.110)
# cron: 0 */6 * * * /backup/scripts/backup-awoooi-frequent.sh >> /backup/logs/cron.log 2>&1
# 說明: 每 6 小時備份 awoooi_prod，最多損失 6 小時資料
#       完整備份（含 Gitea/Harbor）仍由 backup-all.sh 每日 02:00 執行
# =============================================================================

set -euo pipefail

source "$(dirname "$0")/common.sh"

SERVICE="awoooi-frequent"
AWOOOI_HOST="192.168.0.188"
AWOOOI_DB_USER="awoooi"
AWOOOI_DB_PASS="awoooi_prod_2026"
AWOOOI_DB_HOST="localhost"
AWOOOI_DB_PORT="5432"
LOCAL_REPO="${BACKUP_BASE}/awoooi"
DUMP_DIR="/tmp/awoooi-freq-backup-$$"

# 高頻備份保留策略
KEEP_HOURLY=28   # 保留 7 天的 6 小時快照（7*4=28）
KEEP_DAILY=30
KEEP_WEEKLY=12
KEEP_MONTHLY=24

main() {
    local start_time=$(date +%s)

    log_info "========== AWOOOI 高頻備份 ($(date '+%H:%M')) =========="
    mkdir -p "${DUMP_DIR}"

    local timestamp=$(date "+%Y%m%d_%H%M%S")

    # 只備份 awoooi_prod（高頻核心）
    if ssh ollama@${AWOOOI_HOST} "PGPASSWORD='${AWOOOI_DB_PASS}' pg_dump \
        -U ${AWOOOI_DB_USER} -h ${AWOOOI_DB_HOST} -p ${AWOOOI_DB_PORT} \
        awoooi_prod" > "${DUMP_DIR}/awoooi_prod_${timestamp}.sql" 2>&1; then
        local size=$(du -h "${DUMP_DIR}/awoooi_prod_${timestamp}.sql" | cut -f1)
        log_success "awoooi_prod dump 完成 (${size})"
    else
        log_error "awoooi_prod dump 失敗"
        notify_clawbot "failed" "${SERVICE}" "AWOOOI 高頻備份失敗"
        rm -rf "${DUMP_DIR}"
        exit 1
    fi

    # Restic 備份（同一倉庫，頻率不同）
    restic -r "${LOCAL_REPO}" backup "${DUMP_DIR}" \
        --password-file "${RESTIC_PASSWORD_FILE}" \
        --tag "service:awoooi" --tag "freq:6h" \
        --tag "timestamp:${timestamp}" 2>&1

    local snapshot_id=$(restic -r "${LOCAL_REPO}" snapshots --latest 1 --json \
        --password-file "${RESTIC_PASSWORD_FILE}" 2>/dev/null | \
        grep -oP '"short_id":"\K[^"]+' | head -1)
    log_success "快照: ${snapshot_id}"

    # GFS 清理（加入 hourly 保留）
    restic -r "${LOCAL_REPO}" forget --prune \
        --password-file "${RESTIC_PASSWORD_FILE}" \
        --keep-hourly ${KEEP_HOURLY} \
        --keep-daily ${KEEP_DAILY} \
        --keep-weekly ${KEEP_WEEKLY} \
        --keep-monthly ${KEEP_MONTHLY} 2>&1

    rm -rf "${DUMP_DIR}"

    local end_time=$(date +%s)
    log_success "========== AWOOOI 高頻備份完成 ($((end_time-start_time))s) =========="
}

main "$@"
