#!/usr/bin/env bash
# backup/now -- dump every registered site's database plus our own config
#
# Files are written to /var/backups/nhanhvps/<stamp>.<tag>/ with the database
# password kept out of the archive, and the result is verified (non-zero size).
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 mod_backup_now)"

stamp=$(date -u '+%Y%m%dT%H%M%SZ')
dest="$NV_BACKUP_ROOT/$stamp.manual"
install -d -m 0700 "$dest"

fail=0; ok=0
for domain in $(nv_site_list); do
    db=$(nv_site_get "$domain" db_name "")
    [ -z "$db" ] && continue
    if ! db_available; then
        ui_err "$(t db_unreachable)"; fail=$((fail + 1)); continue
    fi
    ui_step "$(t backup_dumping "$domain")"
    pass=$(nv_secret db_root_password)
    if [ -n "$pass" ]; then
        mysqldump --protocol=socket -u root -p"$pass" --single-transaction \
            --default-character-set=utf8mb4 "$db" 2>/dev/null | gzip -9 >"$dest/$domain.sql.gz"
    else
        mysqldump --protocol=socket -u root --single-transaction \
            --default-character-set=utf8mb4 "$db" 2>/dev/null | gzip -9 >"$dest/$domain.sql.gz"
    fi
    if [ -s "$dest/$domain.sql.gz" ]; then
        ui_ok "$(printf '%-30s %s' "$domain" "$(du -h "$dest/$domain.sql.gz" | cut -f1)")"
        ok=$((ok + 1))
    else
        ui_err "$domain"; rm -f "$dest/$domain.sql.gz"; fail=$((fail + 1))
    fi
done

# configuration only: never the secret file
for f in /etc/nhanhvps/nhanhvps.conf /etc/nginx/conf.d/00-nhanhvps.conf \
         /etc/php/8.3/fpm/pool.d/nhanhvps.conf /etc/mysql/mariadb.conf.d/99-nhanhvps.cnf; do
    [ -f "$f" ] && cp -a "$f" "$dest/$(printf '%s' "$f" | tr '/' '_')"
done
printf '%s\t%s\t%s\n' "$stamp" "backup-now" "$dest" >>"$NV_BACKUP_ROOT/MANIFEST"
nv_trace backup "$dest ok=$ok fail=$fail"

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