#!/usr/bin/env bash
# Ensure auxiliary Postgres databases exist (idempotent).
# Safe to run after postgres is healthy — init-db.sh only runs on first volume init.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

if [[ ! -f .env.resolved ]]; then
  echo "Missing .env.resolved — run ./deploy/compose-up.sh first" >&2
  exit 1
fi

# shellcheck disable=SC1091
set -a
source .env.resolved
set +a

postgres_container="$(docker compose --env-file .env.resolved -f deploy/docker-compose.yml ps -q postgres 2>/dev/null || true)"
if [[ -z "$postgres_container" ]]; then
  echo "postgres container not running — skip ensure-databases" >&2
  exit 0
fi

for db in authentik nextcloud immich openwebui; do
  exists="$(docker exec "$postgres_container" psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Atc \
    "SELECT 1 FROM pg_database WHERE datname = '${db}'" 2>/dev/null || true)"
  if [[ "$exists" != "1" ]]; then
    echo "Creating database ${db}..."
    docker exec "$postgres_container" psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "CREATE DATABASE ${db};"
  fi
done
