#!/usr/bin/env bash
# backup/check -- prove the archives can actually be opened
#
# A backup that was never verified is a hope, not a backup. This reads the
# gzip stream to the end and looks for evidence that it is a 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"

ui_header "$(t backup_m_check)" "$NV_BACKUP_ROOT"

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

ok=0; bad=0; empty=0
for d in $(ls -1d "$NV_BACKUP_ROOT"/*/ 2>/dev/null | sort -r | head -n 10); do
    ui_section "$(basename "${d%/}")"
    found=0
    for f in "$d"/*.sql.gz; do
        [ -f "$f" ] || continue
        found=1
        if [ ! -s "$f" ]; then
            empty=$((empty + 1)); ui_err "$(basename "$f") $(t backup_check_empty)"; continue
        fi
        if ! gzip -t "$f" 2>/dev/null; then
            bad=$((bad + 1)); ui_err "$(basename "$f") $(t backup_check_corrupt)"; continue
        fi
        marker=$(gunzip -c "$f" 2>/dev/null | head -c 200000 | grep -cE 'CREATE TABLE|INSERT INTO')
        if [ "$marker" -gt 0 ]; then
            ok=$((ok + 1))
            ui_ok "$(printf '%-34s %s' "$(basename "$f")" "$(du -h "$f" | cut -f1)")"
        else
            bad=$((bad + 1)); ui_err "$(basename "$f") $(t backup_check_notdump)"
        fi
    done
    [ "$found" = "0" ] && ui_info "$(t backup_check_noarchive)"
done

ui_blank
ui_kv "$(t backup_check_ok)"   "$ok"
ui_kv "$(t backup_check_bad)"  "$bad"
ui_kv "$(t backup_check_empty)" "$empty"
if [ "$bad" -gt 0 ] || [ "$empty" -gt 0 ]; then
    nv_log warn 4405 "backup verification found $bad bad and $empty empty archive(s)"
    exit 1
fi
exit 0
