#!/bin/bash
# Wombat-Email: the nightly backup (installed by installer/90-backup.sh as /usr/local/sbin/wombat-email-backup,
# run by wombat-email-backup.timer). Encrypted with restic into the repository in the settings.
#   1. the database (pg_dump, roles too) and Redis (what Rspamd learned) dumped to files
#   2. one snapshot: settings and secrets, mail, DKIM keys, certificates, the dumps
#   3. old snapshots removed: 14 daily, 8 weekly, 12 monthly kept; the space is freed on Sundays
#   4. on Sundays, 10 % of the stored data read back and checked (--verify-all: all of it)
# The result goes to /var/lib/wombat-email/backup-status.json (the daily report and the panel read it).
#   wombat-email-backup restic snapshots      any restic command, with the repository set
set -uo pipefail
. /etc/wombat-email/settings
export RESTIC_REPOSITORY=$BACKUP_REPO RESTIC_PASSWORD_FILE=/etc/wombat-email/secrets/backup-password
export RCLONE_CONFIG=/root/.config/rclone/rclone.conf RCLONE_FAST_LIST=true   # far fewer requests to cloud storage
[ -f /etc/wombat-email/secrets/backup.env ] && { set -a; . /etc/wombat-email/secrets/backup.env; set +a; }
if [ "${1:-}" = restic ]; then shift; exec restic "$@"; fi

DUMP=/var/backups/wombat-email/dumps
STATUS=/var/lib/wombat-email/backup-status.json
PATHS=(/etc /root /var/mail/vmail /var/lib/rspamd/dkim "$DUMP")
[ -d /var/lib/radicale/collections ] && PATHS+=(/var/lib/radicale/collections)   # contacts and calendars (86-dav)
EXCLUDES=(--exclude /root/.cache)
VERIFY_ALL=0; [ "${1:-}" = --verify-all ] && VERIFY_ALL=1
RUNNING=/var/lib/wombat-email/backup-running   # for the panel: a first backup to cloud storage can take hours
export STARTED=$(date +%s)
TMP=$(mktemp -d); trap 'rm -rf "$TMP" "$RUNNING"' EXIT
log() { echo "$*"; logger -t wombat-email-backup "$*"; }
install -d -m 700 "$DUMP"
install -d -m 755 /var/lib/wombat-email
touch "$RUNNING"; chmod 644 "$RUNNING"

status() {   # STATE MESSAGE: the result, kept with the last verification
    STATE=$1 MESSAGE=$2 python3 -I - "$STATUS" <<'PY'
import json, os, sys, time
path = sys.argv[1]
try: old = json.load(open(path))
except Exception: old = {}
s = {"state": os.environ["STATE"], "message": os.environ["MESSAGE"], "finished": int(time.time())}
try:
    sm = json.loads(os.environ.get("SUMMARY") or "{}")
    if sm: s.update(snapshot=sm.get("snapshot_id", ""), files=sm.get("total_files_processed", 0),
                    bytes=sm.get("total_bytes_processed", 0), added=sm.get("data_added_packed", 0))
except ValueError: pass
s["snapshots"] = int(os.environ.get("SNAPSHOTS") or 0)
check = os.environ.get("CHECK_RESULT", "")
s["check"] = {"at": int(time.time()), "result": check} if check else old.get("check")
s["repository"] = os.environ.get("RESTIC_REPOSITORY", "")
s["seconds"] = s["finished"] - int(os.environ["STARTED"])
# How long backups take, for the panel: finished ones only, a failed run says nothing about that.
s["recent"] = ((old.get("recent") or []) + ([s["seconds"]] if s["state"] == "ok" else []))[-14:]
json.dump(s, open(path + ".new", "w"), indent=1); os.replace(path + ".new", path)
PY
}
count_snapshots() { restic snapshots --json 2>/dev/null | python3 -I -c 'import json,sys; print(len(json.load(sys.stdin) or []))' 2>/dev/null || echo 0; }
export SUMMARY="" SNAPSHOTS=0 CHECK_RESULT=""

# 1. dumps (written aside, then put in place, so a failed dump never replaces a good one)
if ! runuser -u postgres -- pg_dump -Fc wombat_email > "$DUMP/wombat_email.dump.new"; then
    status error "Database dump failed"; log "ERROR: database dump failed"; exit 1
fi
if ! runuser -u postgres -- pg_dumpall --globals-only > "$DUMP/pg-roles.sql.new"; then
    status error "Database dump failed (roles)"; log "ERROR: database dump failed (roles)"; exit 1
fi
if ! runuser -u postgres -- pg_dump -Fc roundcube > "$DUMP/roundcube.dump.new"; then
    status error "Database dump failed (webmail)"; log "ERROR: webmail database dump failed"; exit 1
fi
mv "$DUMP/roundcube.dump.new" "$DUMP/roundcube.dump"; mv "$DUMP/wombat_email.dump.new" "$DUMP/wombat_email.dump"; mv "$DUMP/pg-roles.sql.new" "$DUMP/pg-roles.sql"
redis-cli --rdb "$DUMP/redis.rdb" >/dev/null 2>&1 || log "warning: the Redis dump failed (backing up the rest)"
chmod 600 "$DUMP"/*

# 2. the snapshot (exit 3: some files couldn't be read; the snapshot is still made). An interrupted backup
# leaves a lock; restic unlock clears only stale ones (30 minutes old), and a live one is waited for.
restic unlock >/dev/null 2>&1
OUT=$(restic backup --retry-lock 10m --json --tag nightly --exclude-caches "${EXCLUDES[@]}" "${PATHS[@]}" 2>"$TMP/err")
CODE=$?
SUMMARY=$(grep '"message_type":"summary"' <<<"$OUT" | tail -1)
if [ $CODE -ne 0 ] && [ $CODE -ne 3 ]; then
    status error "restic backup failed (exit $CODE): $(tail -1 "$TMP/err")"
    log "ERROR: restic backup failed (exit $CODE)"; cat "$TMP/err"; exit 1
fi
[ $CODE -eq 3 ] && { log "warning: $(grep -c . "$TMP/err") files couldn't be read"; head -20 "$TMP/err"; }

# 3. old snapshots
# (the space is only freed on Sundays: pruning is the slow part on cloud storage)
PRUNE=(); [ "$(date +%u)" = 7 ] && PRUNE=(--prune)
if ! restic forget --retry-lock 10m --tag nightly --keep-daily 14 --keep-weekly 8 --keep-monthly 12 "${PRUNE[@]}" >"$TMP/forget" 2>&1; then
    SNAPSHOTS=$(count_snapshots)
    status warning "Snapshot saved, but removing old snapshots failed: $(tail -1 "$TMP/forget")"
    log "warning: forget/prune failed"; cat "$TMP/forget"; exit 1
fi

# 4. verification
if [ $VERIFY_ALL = 1 ] || [ "$(date +%u)" = 7 ]; then
    SUBSET=$([ $VERIFY_ALL = 1 ] && echo --read-data || echo --read-data-subset=10%)
    if restic check "$SUBSET" >"$TMP/check" 2>&1; then CHECK_RESULT=ok; else CHECK_RESULT="failed: $(tail -1 "$TMP/check")"; fi
    log "check ($SUBSET): $CHECK_RESULT"
fi
SNAPSHOTS=$(count_snapshots)
if [ -n "$CHECK_RESULT" ] && [ "$CHECK_RESULT" != ok ]; then
    status error "Snapshot saved, but the verification failed"; exit 1
fi
status ok "Snapshot saved"
log "ok: snapshot $(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1])).get("snapshot","")[:8])' "$STATUS"), $SNAPSHOTS kept"
