#!/usr/bin/env bash
set -euo pipefail

# ── Configuration ──────────────────────────────────────────────
DEPLOY_DIR="/mnt/user/appdata/nuzlocke-tracker"
BACKUP_DIR="${DEPLOY_DIR}/backups"
RETENTION_DAYS=7
DB_SERVICE="db"
DB_NAME="nuzlocke"
DB_USER="postgres"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/nuzlocke-${TIMESTAMP}.sql.gz"

# ── Create backup directory ───────────────────────────────────
mkdir -p "$BACKUP_DIR"

# ── Dump database ─────────────────────────────────────────────
cd "$DEPLOY_DIR"
docker compose exec -T "$DB_SERVICE" pg_dump -U "$DB_USER" "$DB_NAME" | gzip > "$BACKUP_FILE"

echo "Backup created: ${BACKUP_FILE}"

# ── Rotate old backups ────────────────────────────────────────
find "$BACKUP_DIR" -name "nuzlocke-*.sql.gz" -mtime +${RETENTION_DAYS} -delete

REMAINING=$(find "$BACKUP_DIR" -name "nuzlocke-*.sql.gz" | wc -l)
echo "Backups retained: ${REMAINING}"

# ── Restore procedure ────────────────────────────────────────
# To restore from a backup:
#   cd /mnt/user/appdata/nuzlocke-tracker
#   gunzip -c backups/nuzlocke-YYYYMMDD-HHMMSS.sql.gz | \
#     docker compose exec -T db psql -U postgres nuzlocke
