#!/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')"
