#!/bin/bash
# =============================================================================
# WOOO AIOps - Gitea 備份腳本
# 版本: 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="gitea"
GITEA_CONTAINER="gitea"
LOCAL_REPO="${BACKUP_BASE}/gitea"
DUMP_DIR="/tmp/gitea-backup-$$"

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

main() {
    local start_time
    local tags
    local snapshot_id
    local duration

    start_time=$(date +%s)
    trap cleanup EXIT

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

    log_info "執行 Gitea dump..."
    if docker exec -u git "${GITEA_CONTAINER}" gitea dump -c /data/gitea/conf/app.ini -f /tmp/gitea-dump.zip 2>&1; then
        docker cp "${GITEA_CONTAINER}:/tmp/gitea-dump.zip" "${DUMP_DIR}/gitea-dump.zip"
        docker exec -u git "${GITEA_CONTAINER}" rm -f /tmp/gitea-dump.zip
        log_success "Gitea dump 完成"
    else
        log_error "Gitea dump 失敗"
        notify_clawbot "failed" "${SERVICE}" "Gitea dump 失敗"
        exit 1
    fi

    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 "========== Gitea 備份完成 (${duration}s) =========="
    notify_clawbot "success" "${SERVICE}" "Gitea 備份完成" "${duration}"
}

main "$@"
