#!/usr/bin/env bash
# Dumps the food-market Postgres DB to a timestamped gzipped file.
# Usage:
#   deploy/backup.sh                      — local dev DB (postgres@14 via Unix socket)
#   deploy/backup.sh --remote HOST:PORT   — over network
#   deploy/backup.sh --docker             — DB running in the compose container
set -euo pipefail

MODE="${1:-local}"
STAMP="$(date -u +%Y%m%d-%H%M%S)"
BACKUP_DIR="${BACKUP_DIR:-$HOME/food-market-backups}"
mkdir -p "$BACKUP_DIR"
OUT="$BACKUP_DIR/food_market-$STAMP.sql.gz"

case "$MODE" in
  local|"")
    pg_dump -U "${PGUSER:-nns}" -d "${PGDATABASE:-food_market}" \
      --no-owner --no-privileges --clean --if-exists \
      | gzip > "$OUT"
    ;;
  --docker)
    docker compose -f "$(dirname "$0")/docker-compose.yml" exec -T postgres \
      pg_dump -U food_market -d food_market --no-owner --no-privileges --clean --if-exists \
      | gzip > "$OUT"
    ;;
  --remote)
    HOST="$2"
    pg_dump -h "${HOST%:*}" -p "${HOST#*:}" -U "${PGUSER:-food_market}" -d food_market \
      --no-owner --no-privileges --clean --if-exists \
      | gzip > "$OUT"
    ;;
  *)
    echo "usage: $0 [local|--docker|--remote HOST:PORT]" >&2
    exit 1
    ;;
esac

echo "Wrote $OUT ($(du -h "$OUT" | cut -f1))"

# Retain last 30 days
find "$BACKUP_DIR" -name 'food_market-*.sql.gz' -mtime +30 -delete 2>/dev/null || true
