Files
swym/script/database-backup.sh
rob thijssen 216729eb25 feat: database backup and restore scripts
database-backup.sh dumps the full remote swym DB to a local custom-format
pg_dump file. database-restore.sh restores a local backup to the remote DB,
stopping all swym services beforehand and restarting them afterwards (via
trap so services come back up even on failure). Both scripts derive the DB
connection URL from config/dev/api.json following the same pattern as
seed-dev.sh.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-09 10:45:51 +02:00

42 lines
1.6 KiB
Bash
Executable File

#!/usr/bin/env bash
# Create a full backup of the remote swym database to a local file.
#
# Usage: ./script/database-backup.sh <target_path>
#
# target_path Local file path to write the backup to (pg_dump custom format).
# Example: /tmp/swym-backup-$(date +%Y%m%d-%H%M%S).dump
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
if [[ $# -lt 1 ]]; then
echo "Usage: $0 <target_path>" >&2
exit 1
fi
target_path="$1"
# Build connection string from dev api config (same logic as seed-dev.sh).
api_cfg="$REPO_ROOT/config/dev/api.json"
config_db_url=$(jq -r '.database.url' "$api_cfg")
db_user="$(echo "${config_db_url}" | cut -d '/' -f 3 | cut -d '@' -f 1)"
db_host="$(echo "${config_db_url}" | cut -d '@' -f 2 | cut -d ':' -f 1)"
db_port="$(echo "${config_db_url}" | cut -d ':' -f 3 | cut -d '/' -f 1)"
db_name="$(echo "${config_db_url}" | cut -d '/' -f 4 | cut -d '?' -f 1)"
db_ssl_mode=verify-full
db_ssl_root_cert=/etc/pki/ca-trust/source/anchors/ca.internal-rsa.pem
db_ssl_cert=/etc/pki/tls/misc/$(hostnamectl hostname)-rsa.pem
db_ssl_key=/etc/pki/tls/private/$(hostnamectl hostname)-rsa.pem
db_url="postgres://${db_user}@${db_host}:${db_port}/${db_name}?sslmode=${db_ssl_mode}&sslrootcert=${db_ssl_root_cert}&sslcert=${db_ssl_cert}&sslkey=${db_ssl_key}"
echo "==> Backing up ${db_user}@${db_host}:${db_port}/${db_name}${target_path}"
pg_dump \
--format=custom \
--no-password \
"$db_url" \
--file="$target_path"
size=$(du -sh "$target_path" | cut -f1)
echo "==> Backup complete: ${target_path} (${size}) at $(date -u '+%Y-%m-%dT%H:%M:%SZ')"