#!/bin/bash
set -euo pipefail

# Build the PostgreSQL connection URL from the Cloudron postgresql addon.
export DATABASE_URL="postgres://${CLOUDRON_POSTGRESQL_USERNAME}:${CLOUDRON_POSTGRESQL_PASSWORD}@${CLOUDRON_POSTGRESQL_HOST}:${CLOUDRON_POSTGRESQL_PORT}/${CLOUDRON_POSTGRESQL_DATABASE}?sslmode=disable"

# Single-container server mode (server embeds a default worker).
export MODE="${MODE:-server}"

# Wait for PostgreSQL to accept connections before starting. Windmill runs SQL
# migrations on startup, so the DB must be reachable. Uses bash /dev/tcp (no
# pg_isready dependency).
echo "Waiting for PostgreSQL at ${CLOUDRON_POSTGRESQL_HOST}:${CLOUDRON_POSTGRESQL_PORT} ..."
for i in $(seq 1 60); do
  if (exec 3<>"/dev/tcp/${CLOUDRON_POSTGRESQL_HOST}/${CLOUDRON_POSTGRESQL_PORT}") 2>/dev/null; then
    exec 3>&- 3<&- || true
    echo "PostgreSQL is reachable."
    break
  fi
  echo "  not ready yet, retrying in 2s ($i/60)"
  sleep 2
done

cd /usr/src/app
exec windmill
