#!/usr/bin/env bash
# Export databáze EMS z lokálního Docker Compose (služba db musí běžet).
#
# Použití (z kořene repa, kde je docker-compose.yml a .env):
#   ./scripts/export_ems_db.sh
#   ./scripts/export_ems_db.sh ~/zálohy/ems.dump
#
# Výstup: pg_dump -Fc (custom format) – vhodné pro pg_restore na server.
# Volitelně: COMPOSE_FILE, ENV_FILE (cesty k compose / .env).

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$REPO_ROOT"

COMPOSE_FILE="${COMPOSE_FILE:-docker-compose.yml}"
ENV_FILE="${ENV_FILE:-.env}"

if [[ ! -f "$COMPOSE_FILE" ]]; then
  echo "ERROR: compose file not found: $COMPOSE_FILE" >&2
  exit 1
fi

if [[ -f "$ENV_FILE" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$ENV_FILE"
  set +a
else
  echo "WARN: $ENV_FILE missing – DB_USER / DB_PASSWORD musí být v prostředí" >&2
fi

: "${DB_USER:?Set DB_USER in .env or environment}"
: "${DB_PASSWORD:?Set DB_PASSWORD in .env or environment}"

OUT="${1:-./ems_backup_$(date +%Y%m%d_%H%M%S).dump}"
OUT="$(cd "$(dirname "$OUT")" && pwd)/$(basename "$OUT")"

if ! docker compose -f "$COMPOSE_FILE" ps --status running -q db | grep -q .; then
  echo "ERROR: služba db neběží. Spusť: docker compose -f $COMPOSE_FILE up -d db" >&2
  exit 1
fi

echo "Exportuji ems -> $OUT"
docker compose -f "$COMPOSE_FILE" exec -T \
  -e "PGPASSWORD=${DB_PASSWORD}" \
  db \
  pg_dump -U "$DB_USER" -d ems -Fc --no-owner --no-acl -f /tmp/ems_export.dump

docker compose -f "$COMPOSE_FILE" cp "db:/tmp/ems_export.dump" "$OUT"
docker compose -f "$COMPOSE_FILE" exec -T db rm -f /tmp/ems_export.dump

echo "Hotovo: $OUT"
echo "Na server: scp \"$OUT\" user@server:/tmp/ems.dump"
