randomayzer/tools/db-backup.sh

18 lines
1,010 B
Bash
Executable file

#!/usr/bin/env bash
set -euo pipefail
umask 077
# Environment file is read by Docker Compose, never sourced as executable shell code.
: "${RANDOMAYZER_ENV_FILE:?Set absolute 0600 env file path}"
[[ $(stat -c '%a' "$RANDOMAYZER_ENV_FILE") == 600 ]] || { echo 'Environment file must have mode 0600' >&2; exit 1; }
[[ $# == 1 && -d $1 ]] || { echo 'Usage: tools/db-backup.sh /absolute/backup-directory' >&2; exit 1; }
root=$(cd "$(dirname "$0")/.." && pwd)
backup_dir=$(realpath "$1")
file="$backup_dir/randomayzer-$(date -u +%Y%m%dT%H%M%S)-$$.dump"
args=(--env-file "$RANDOMAYZER_ENV_FILE" -f "$root/compose.production.yml")
export RANDOMAYZER_ENV_FILE
trap 'rm -f "$file.partial"' EXIT
docker compose "${args[@]}" exec -T postgres pg_dump -U randomayzer -d randomayzer -Fc > "$file.partial"
# Validate archive readability; full restore drill is a separate mandatory daily step.
docker compose "${args[@]}" exec -T postgres pg_restore --list < "$file.partial" > /dev/null
mv "$file.partial" "$file"
echo "$file"