#!/bin/bash
# =============================================================================
# WOOO AIOps - Harbor 備份腳本
# 版本: 1.1.0
# 建立日期: 2026-03-12
# 2026-05-19 ogt + Codex: 納入 repo/Ansible；離機上傳改由 sync-offsite-backups.sh 統一管控。
# =============================================================================

set -euo pipefail

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

SERVICE="harbor"
HARBOR_DB_CONTAINER="harbor-db"
LOCAL_REPO="${BACKUP_BASE}/harbor"
DUMP_DIR="/tmp/harbor-backup-$$"

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

main() {
    local start_time
    local timestamp
    local db_dump
    local size
    local tags
    local snapshot_id
    local duration

    start_time=$(date +%s)
    timestamp=$(date "+%Y%m%d_%H%M%S")
    db_dump="${DUMP_DIR}/harbor_db_${timestamp}.sql"
    trap cleanup EXIT

    log_info "========== 開始 Harbor 備份 =========="
    mkdir -p "${DUMP_DIR}"

    log_info "執行 Harbor PostgreSQL dump..."
    docker exec "${HARBOR_DB_CONTAINER}" pg_dump -U postgres registry > "${db_dump}" 2>&1

    if [ -s "${db_dump}" ]; then
        size=$(du -h "${db_dump}" | cut -f1)
        log_success "Harbor DB dump 完成 (${size})"
    else
        log_error "Harbor DB dump 失敗"
        notify_clawbot "failed" "${SERVICE}" "Harbor 資料庫 dump 失敗"
        exit 1
    fi

    log_info "備份 Harbor 配置..."
    cp /opt/harbor/harbor.yml "${DUMP_DIR}/" 2>/dev/null || log_warn "harbor.yml 不存在"

    if [ ! -d "${LOCAL_REPO}/data" ]; then
        log_info "初始化本地 Restic 倉庫..."
        restic -r "${LOCAL_REPO}" init --password-file "${RESTIC_PASSWORD_FILE}"
    fi

    tags=$(build_tags "${SERVICE}")
    restic -r "${LOCAL_REPO}" backup "${DUMP_DIR}" \
        --password-file "${RESTIC_PASSWORD_FILE}" \
        ${tags}

    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 || true)
    log_success "Restic 備份完成: ${snapshot_id:-unknown}"

    log_info "執行 GFS 清理..."
    cleanup_old_backups "${LOCAL_REPO}"

    log_info "Offsite copy is handled by sync-offsite-backups.sh; no direct rclone sync here."

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

main "$@"
