#!/usr/bin/env bash
# backup/sites-all -- snapshot every managed site in one pass
#
# This is what the cron entry should call when per-site snapshots are wanted
# rather than a single aggregated database dump.
set -o pipefail
SELF=$(readlink -f "${BASH_SOURCE[0]}")
NV_BASE=$(cd "$(dirname "$SELF")/../../.." && pwd)
export NV_BASE
# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

nv_require_root || exit 1
ui_header "$(t backup_m_sitesall)"

if [ "$(nv_site_count)" -eq 0 ]; then ui_info "$(t site_none)"; exit 0; fi

ok=0; fail=0
printf '  %-34s %-10s %s\n' "$(t col_domain)" "$(t col_size)" "$(t col_status)"
for domain in $(nv_site_list); do
    nv_lock_acquire "site:$domain" 5 || { ui_warn "$(t lock_busy "$domain")"; fail=$((fail + 1)); continue; }
    dir=$(site_snapshot "$domain" "auto-$domain")
    rc=$?
    nv_lock_release "site:$domain"
    if [ "$rc" -eq 0 ] && [ -n "$dir" ]; then
        ok=$((ok + 1))
        printf '  %-34s %-10s %s\n' "$domain" "$(du -sh "$dir" | cut -f1)" "$(t backup_ok)"
    else
        fail=$((fail + 1))
        printf '  %-34s %-10s %s\n' "$domain" '-' "$(t backup_failed)"
    fi
done

nv_backup_prune "$(nv_conf backup_keep_days 14)"
ui_blank
ui_kv "$(t backup_ok)"     "$ok"
ui_kv "$(t backup_failed)" "$fail"
ui_kv "$(t backup_location)" "$NV_BACKUP_ROOT"
ui_blank
[ "$fail" -gt 0 ] && exit 1
exit 0
