#!/bin/sh
# wait-for-mqtt.sh: wait for MQTT broker from $MQTT_BROKER (default tcp://mosquitto:1883)
set -e

BROKER=${MQTT_BROKER:-tcp://mosquitto:1883}
# strip tcp:// if present
BROKER=${BROKER#tcp://}
HOST=${BROKER%%:*}
PORT=${BROKER#*:}
if [ "$HOST" = "$PORT" ]; then
  # no port provided
  PORT=1883
fi

echo "Waiting for MQTT broker $HOST:$PORT..."
while ! nc -z "$HOST" "$PORT"; do
  echo "broker not ready, retrying..."
  sleep 1
done

echo "Broker $HOST:$PORT is up"

# Optionally wait for MySQL if DB_HOST/DB_PORT are set
DB_HOST=${DB_HOST:-}
DB_PORT=${DB_PORT:-}
if [ -n "$DB_HOST" ]; then
  if [ -z "$DB_PORT" ]; then
    DB_PORT=3306
  fi
  echo "Waiting for MySQL $DB_HOST:$DB_PORT..."
  while ! nc -z "$DB_HOST" "$DB_PORT"; do
    echo "mysql not ready, retrying..."
    sleep 1
  done
  echo "MySQL $DB_HOST:$DB_PORT is up"
fi

echo "Starting server"
exec /usr/local/bin/server
