#!/bin/bash
# =============================================================================
# WOOO AIOps - ClawBot Redis 備份腳本 (SSH → 192.168.0.188)
# 版本: 1.0.0
# 建立日期: 2026-04-05
# 2026-04-05 Claude Code: 新增 ClawBot Redis 狀態/快取備份 — 首席架構師備份審計
# =============================================================================

set -euo pipefail

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

SERVICE="clawbot"
LOCAL_REPO="${BACKUP_BASE}/clawbot"
DUMP_DIR="/tmp/clawbot-backup-$$"
REMOTE_HOST="ollama@192.168.0.188"

cleanup() {
    rm -rf "${DUMP_DIR}"
}

main() {
    local start_time=$(date +%s)
    log_info "========== 開始 ClawBot Redis 備份 (188→110) =========="
    mkdir -p "${DUMP_DIR}"

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

    # Step 1: 觸發 Redis BGSAVE 確保數據落盤
    log_info "觸發 Redis BGSAVE..."
    ssh "${REMOTE_HOST}" "docker exec clawbot-redis redis-cli BGSAVE" 2>/dev/null || log_warn "BGSAVE 失敗或 clawbot-redis 未運行，繼續備份"
    sleep 2  # 等待 BGSAVE 完成

    # Step 2: SSH 到 188 將 Redis volume 打包傳回
    log_info "從 192.168.0.188 拉取 clawbot-redis volume..."
    if ssh "${REMOTE_HOST}" "docker run --rm -v clawbot-v5_clawbot-redis-data:/data alpine tar czf - /data 2>/dev/null" > "${DUMP_DIR}/clawbot-redis_${timestamp}.tar.gz"; then
        local size=$(du -h "${DUMP_DIR}/clawbot-redis_${timestamp}.tar.gz" | cut -f1)
        log_success "ClawBot Redis volume 拉取完成 (${size})"
    else
        log_error "ClawBot Redis volume 拉取失敗"
        notify_clawbot "failed" "${SERVICE}" "ClawBot Redis 備份失敗 (SSH 188)"
        cleanup
        exit 1
    fi

    # Step 3: 初始化 Restic 倉庫
    if [ ! -d "${LOCAL_REPO}/data" ]; then
        log_info "初始化 Restic 倉庫: ${LOCAL_REPO}"
        restic -r "${LOCAL_REPO}" init --password-file "${RESTIC_PASSWORD_FILE}" 2>&1 || {
            log_error "Restic 倉庫初始化失敗"
            cleanup
            exit 1
        }
    fi

    # Step 4: Restic 備份
    log_info "建立 Restic 備份..."
    local tags=$(build_tags "${SERVICE}")
    restic -r "${LOCAL_REPO}" backup "${DUMP_DIR}"         --password-file "${RESTIC_PASSWORD_FILE}"         ${tags} 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 "Restic 備份完成: ${snapshot_id}"

    # Step 5: GFS 清理
    cleanup_old_backups "${LOCAL_REPO}"

    cleanup

    local end_time=$(date +%s)
    local duration=$((end_time - start_time))
    log_success "========== ClawBot Redis 備份完成 (${duration}s) =========="
    notify_clawbot "success" "${SERVICE}" "ClawBot Redis 備份完成" "${duration}"
}

main "$@"
