#!/bin/sh
set -e

# Wait for PostgreSQL to be ready
if [ -n "$DATABASE_URI" ]; then
  echo "Waiting for PostgreSQL to be ready..."
  until wget -q --spider http://postgresql:5432 2>/dev/null || nc -z postgresql 5432; do
    echo "PostgreSQL is unavailable - sleeping"
    sleep 2
  done
  echo "PostgreSQL is up"
fi

# Wait for MinIO to be ready
if [ -n "$MINIO_ENDPOINT" ]; then
  echo "Waiting for MinIO to be ready..."
  until wget -q --spider "$MINIO_ENDPOINT/minio/health/live" 2>/dev/null; do
    echo "MinIO is unavailable - sleeping"
    sleep 2
  done
  echo "MinIO is up"
fi

# Start the application
exec "$@"
