#!/bin/bash
set -euo pipefail

# -------- Configuration --------
DOCKER_COMPOSE_FILE="/opt/appdata/.docker-compose/docker-compose.yml"
CONTAINER_BACKUP_DIR="/data/postgres/backup"
PG_DUMP_PARAMS="-U user_pg -h localhost"
DATABASE_BACKUP_TOOL="pg_dump"

# Load shared functions
source /opt/scripts_remote/shared_functions.sh

# -------- Function --------
backup_database() {
  local database_name="$1"
  local container_path="$CONTAINER_BACKUP_DIR/${database_name}.backup"

  echo "📦 Dumping database: $database_name..."
  if docker compose -f "$DOCKER_COMPOSE_FILE" exec -T pg \
     "$DATABASE_BACKUP_TOOL" $PG_DUMP_PARAMS -d "$database_name" -F c -f "$container_path"; then
    echo "✅ Dump of '$database_name' completed."
  else
    echo "❌ Failed to dump '$database_name'."
    exit 1
  fi
}

# -------- Main Execution --------
backup_database "sonarr-main"
backup_database "sonarr-log"