#!/bin/bash
# =============================================================================
# WOOO AIOps - Open-WebUI 備份腳本 (SSH → 192.168.0.188)
# 版本: 1.0.0
# 建立日期: 2026-04-05
# 2026-04-05 Claude Code: 新增 Open-WebUI LLM 對話紀錄備份 — 首席架構師備份審計
# =============================================================================

set -euo pipefail

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

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

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

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

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

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

    # Step 2: 初始化 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 3: 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 4: GFS 清理
    cleanup_old_backups "${LOCAL_REPO}"

    cleanup

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

main "$@"
