#!/bin/sh
# Datahub backend container entrypoint.
# Flow: wait_tcp pg/mq -> migrate --force -> app:install -> exec swoole.
set -eu

wait_tcp() {
    host="$1"
    port="$2"
    label="$3"
    timeout="${4:-90}"
    echo "[entrypoint] waiting for ${label} @ ${host}:${port} (up to ${timeout}s)"
    i=0
    while [ "$i" -lt "$timeout" ]; do
        if php -r "exit(@fsockopen('${host}', ${port}, \$e, \$s, 1) ? 0 : 1);" 2>/dev/null; then
            echo "[entrypoint] ${label} reachable"
            return 0
        fi
        i=$((i + 1))
        sleep 1
    done
    echo "[entrypoint] ${label} @ ${host}:${port} unreachable after ${timeout}s" >&2
    return 1
}

DB_HOST="${DB_HOST:-host.containers.internal}"
DB_PORT="${DB_PORT:-5432}"
AMQP_HOST="${AMQP_HOST:-host.containers.internal}"
AMQP_PORT="${AMQP_PORT:-5672}"
WAIT_TIMEOUT="${ENTRYPOINT_WAIT_TIMEOUT:-90}"

wait_tcp "${DB_HOST}" "${DB_PORT}" "postgres" "${WAIT_TIMEOUT}"
wait_tcp "${AMQP_HOST}" "${AMQP_PORT}" "rabbitmq" "${WAIT_TIMEOUT}"

echo "[entrypoint] running migrate --force"
php /var/www/bin/hyperf.php migrate --force

echo "[entrypoint] running app:install"
php /var/www/bin/hyperf.php app:install

echo "[entrypoint] handing off to: $*"
exec "$@"
