#!/usr/bin/env bash
#
# dbdr-backup.sh -- a scheduled backup of one database with dbdr.
#
# The example script for Volume II, Chapter 6 (Running Unattended). Copy
# it, then change the settings below. It:
#   - takes a schema dump and a native data dump into a new,
#     timestamped directory, readable only by the user running it;
#   - writes a SHA-256 manifest of everything it produced;
#   - refuses to run while another copy of itself is running;
#   - removes backups older than KEEP_DAYS, but only after this run has
#     succeeded;
#   - exits non-zero on any failure, so the scheduler (cron, systemd, a
#     Kubernetes CronJob) can alert on it.
#
# The password is never on the command line: it is read from the file
# named by DBDR_PASSWORD_FILE (for example, a mounted secret) and handed
# to dbdr through DBDR_PASSWORD.

set -euo pipefail
umask 077                         # dumps contain real data: owner-only files

# --- settings -------------------------------------------------------
ENGINE="${ENGINE:-clickhouse}"    # clickhouse | postgres
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-}"            # empty: dbdr's default for ENGINE
DB_USER="${DB_USER:-dumper}"      # a read-only user; see Chapter 2
DB_NAME="${DB_NAME:?set DB_NAME}"
HTTP_PORT="${HTTP_PORT:-}"        # ClickHouse native data; empty: 8443 with TLS
TLS_MODE="${TLS_MODE:-verify-full}" # verify-full | require | disable
TLS_CA="${TLS_CA:-}"              # PEM file of the CA that signed the server cert
BACKUP_ROOT="${BACKUP_ROOT:?set BACKUP_ROOT}"
KEEP_DAYS="${KEEP_DAYS:-14}"
DBDR="${DBDR:-dbdr}"
: "${DBDR_PASSWORD_FILE:?set DBDR_PASSWORD_FILE}"
# ---------------------------------------------------------------------

log() { printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >&2; }

mkdir -p "$BACKUP_ROOT"
lock="$BACKUP_ROOT/.lock"
if ! mkdir "$lock" 2>/dev/null; then
	log "another backup is running (lock $lock exists); exiting"
	exit 75 # EX_TEMPFAIL: the scheduler can retry later
fi
trap 'rmdir "$lock"' EXIT

DBDR_PASSWORD="$(cat "$DBDR_PASSWORD_FILE")"
export DBDR_PASSWORD

stamp="$(date -u +%Y%m%dT%H%M%SZ)"
out="$BACKUP_ROOT/$DB_NAME-$stamp"
work="$out.partial"
mkdir "$work"

conn=(-e="$ENGINE" -hn="$DB_HOST" -un="$DB_USER" -db="$DB_NAME" --tls="$TLS_MODE")
[[ -n "$DB_PORT" ]] && conn+=(-pn="$DB_PORT")
[[ -n "$TLS_CA" ]] && conn+=(--tls-ca="$TLS_CA")
native=(--only=data -fmt=native --compress=zip)
[[ "$ENGINE" == clickhouse && -n "$HTTP_PORT" ]] && native+=(--http-port="$HTTP_PORT")

log "dumping $ENGINE database $DB_NAME from $DB_HOST into $out"
"$DBDR" "${conn[@]}" --only=schema -o="$work/schema.sql" 2>>"$work/dbdr.log"
"$DBDR" "${conn[@]}" "${native[@]}" -o="$work/data.zip" 2>>"$work/dbdr.log"

(cd "$work" && shasum -a 256 schema.sql data.zip >SHA256SUMS)

# Only a complete backup gets its final name. A directory still ending in
# .partial was interrupted, and is never mistaken for a good one.
mv "$work" "$out"
log "ok: $(du -sh "$out" | cut -f1) in $out"

# Retention, last: a failed run above never deletes older good backups.
find "$BACKUP_ROOT" -maxdepth 1 -type d -name "$DB_NAME-*" ! -name '*.partial' \
	-mtime +"$KEEP_DAYS" -print -exec rm -rf {} + | sed 's/^/pruned: /' >&2
