#!/bin/bash
set -e

# Use the environment variables set in CapRover for the host and user
host="${POSTGRES_HOST}"
user="${POSTGRES_USER}"

echo "Waiting for PostgreSQL database at $host to be ready..."

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

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