#!/usr/bin/env bash
# backup/export -- one archive that can be pulled off the server
#
# Customers rarely want a directory tree; they want one file they can scp and
# keep somewhere else.
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_export)"

if [ ! -d "$NV_BACKUP_ROOT" ]; then ui_info "$(t backup_none)"; exit 0; fi

mapfile -t sets < <(find "$NV_BACKUP_ROOT" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' 2>/dev/null | sort -r | head -n 5)
[ ${#sets[@]} -gt 0 ] || { ui_info "$(t backup_none)"; exit 0; }

ui_section "$(t backup_export_will)"
total=0
for s in "${sets[@]}"; do
    size=$(du -sm "$NV_BACKUP_ROOT/$s" 2>/dev/null | cut -f1)
    total=$((total + ${size:-0}))
    printf '  %-44s %s MB\n' "$s" "${size:-0}"
done
ui_kv "$(t backup_total)" "$(t backup_export_mb "$total")"
ui_blank

out="/root/nhanhvps-backups-$(date -u '+%Y%m%dT%H%M%SZ').tar.gz"
ui_step "$(t backup_export_running "$out")"
if tar czf "$out" -C "$NV_BACKUP_ROOT" "${sets[@]}" 2>/dev/null; then
    chmod 0600 "$out"
    nv_trace backup-export "$out sets=${#sets[@]}"
    ui_ok "$(t backup_export_done "$out")"
    ui_kv "$(t col_size)" "$(du -h "$out" | cut -f1)"
    ui_info "$(t backup_export_hint)"
else
    nv_fail 4503 "$(t backup_export_failed)"
    rm -f "$out"
    exit 1
fi
exit 0
