#!/bin/bash
set -e

host="postgres"
user="${POSTGRES_USER}"
db="${POSTGRES_DB}"
password="${POSTGRES_PASSWORD}"

echo "Waiting for PostgreSQL database to be ready..."

# Wait for the database server to be available
until PGPASSWORD="$password" pg_isready -h "$host" -U "$user"; do
  echo "PostgreSQL server is unavailable - sleeping"
  sleep 1
done

# Wait for the specific database to be available
until PGPASSWORD="$password" psql -h "$host" -U "$user" -d "$db" -c '\q'; do
  echo "Database '$db' is not yet available - sleeping"
  sleep 1
done

echo "PostgreSQL database is up and ready - executing command"
exec "$@"