#!/bin/sh
# wait-for-db.sh - Wait for PostgreSQL to be ready

set -e

host="${POSTGRES_HOST:-postgres}"
port="${POSTGRES_PORT:-5432}"
max_attempts="${DB_MAX_ATTEMPTS:-30}"
wait_seconds="${DB_WAIT_SECONDS:-2}"

echo "Waiting for database at ${host}:${port}..."

attempt=1
while ! nc -z "${host}" "${port}"; do
    if [ "${attempt}" -ge "${max_attempts}" ]; then
        echo "ERROR: Database not available after ${max_attempts} attempts. Exiting."
        exit 1
    fi
    echo "  Attempt ${attempt}/${max_attempts}: Database not ready yet, waiting ${wait_seconds}s..."
    sleep "${wait_seconds}"
    attempt=$((attempt + 1))
done

echo "Database is ready!"
exec "$@"
