#!/usr/bin/env bash
# =============================================================================
# AWOOOI backup retention enforcer
#
# Operator policy: each backup repository keeps only the latest successful copy.
# This script is safe to run after backup jobs have succeeded; it never creates
# a snapshot and never touches production data, only restic repository metadata.
# =============================================================================

set -euo pipefail

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

EXPECTED_REPOS_DEFAULT="awoooi configs gitea harbor momo langfuse monitoring signoz open-webui clawbot sentry ai-artifacts public-routes"
REPOS="${BACKUP_RETENTION_REPOS:-${EXPECTED_REPOS_DEFAULT}}"

main() {
    local failed=0
    log_info "========== Latest-only retention enforcement start (keep-last=${KEEP_LAST}) =========="

    for name in ${REPOS}; do
        local repo="${BACKUP_BASE}/${name}"
        if [ ! -d "${repo}/data" ]; then
            log_warn "跳過未初始化 repo: ${repo}"
            continue
        fi

        log_info "Enforce latest-only retention: ${name}"
        if ! BACKUP_RETENTION_MODE=latest cleanup_old_backups "${repo}"; then
            failed=$((failed + 1))
        fi
    done

    if [ "${failed}" -eq 0 ]; then
        log_success "========== Latest-only retention enforcement complete =========="
    else
        log_error "========== Latest-only retention enforcement failed: ${failed} repo(s) =========="
    fi
    return "${failed}"
}

main "$@"
