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

cd "$(dirname "$0")/.."

BACKUP_DIR="${BACKUP_DIR:-./backups}"
STORAGE_HOST_PATH="${STORAGE_HOST_PATH:-./storage}"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
TARGET_DIR="${BACKUP_DIR}/${TIMESTAMP}"

mkdir -p "${TARGET_DIR}"

echo "==> Creating backup in ${TARGET_DIR}"

if [[ -n "${POSTGRES_CONTAINER:-}" ]]; then
  echo "==> Creating PostgreSQL dump from container ${POSTGRES_CONTAINER}"
  docker exec "${POSTGRES_CONTAINER}" pg_dump -U "${POSTGRES_USER:-olympus}" "${POSTGRES_DB:-olympus}" > "${TARGET_DIR}/postgres.sql"
elif command -v pg_dump >/dev/null 2>&1 && [[ -n "${DATABASE_URL:-}" ]]; then
  echo "==> Creating PostgreSQL dump from DATABASE_URL"
  pg_dump "${DATABASE_URL}" > "${TARGET_DIR}/postgres.sql"
else
  echo "WARN: PostgreSQL dump skipped. Set POSTGRES_CONTAINER or install pg_dump with DATABASE_URL."
fi

if [[ -d "${STORAGE_HOST_PATH}" ]]; then
  echo "==> Archiving storage directory"
  tar -czf "${TARGET_DIR}/storage.tar.gz" -C "${STORAGE_HOST_PATH}" .
else
  echo "WARN: Storage directory ${STORAGE_HOST_PATH} not found; storage backup skipped."
fi

echo "INFO: .env is not copied automatically. Store production secrets separately and securely."
echo "==> Backup completed"
