services:
  rocketchat:
    image: ${IMAGE:-registry.rocket.chat/rocketchat/rocket.chat}:${RELEASE:-8.0.1}
    restart: always
    labels:
      prometheus.io/scrape: "true"
      prometheus.io/port: ${METRICS_PORT:-9458}
      container_tag: "${COMPOSE_PROJECT_NAME:-rocketchat}#rocketchat"
    environment:
      ROOT_URL: ${ROOT_URL:-http://localhost}
      PORT: ${PORT:-3000}
      DEPLOY_METHOD: docker
      DEPLOY_PLATFORM: compose
      REG_TOKEN: ${REG_TOKEN:-}
      LICENSE_DEBUG: true
      OVERWRITE_SETTING_Prometheus_Enabled: true
      OVERWRITE_SETTING_Prometheus_Port: "${METRICS_PORT:-9458}"
      MONGO_URL: ${MONGO_URL:-mongodb://mongodb:27017/rocketchat?replicaSet=rs0}
      TRANSPORTER: "${NATS_URL-monolith+nats://nats:4222}"
      INSTANCE_IP: "${INSTANCE_IP:-}"
    # depends_on:
    #   mongodb-init-container:
    #     condition: service_completed_successfully
    entrypoint: sh
    command:
      - -c
      - |
        protocol=$(echo $$MONGO_URL | awk -F'://' '{print $$1}')
        if [ "$$protocol" = "mongodb+srv" ]; then
          echo "=====> MongoDB is using SRV protocol, skipping healthcheck before attempting to start rocket.chat ...";
          exec node main.js;
        fi
        host_port=$(echo $$MONGO_URL | awk -F/ '{print $$3}')
        if echo $$host_port | grep -q @; then
          host_port=$(echo $$host_port | awk -F@ '{print $$2}')
        fi
        echo "=====> host_port: $$host_port";
        host=$${host_port%%:*}
        port=$${host_port##*:}
        port=$${port:-27017}
        echo "=====> Waiting for MongoDB ($$host:$$port) to be ready before starting Rocket.Chat...";
        for i in $(seq 1 60); do
          if nc -z $$host $$port >/dev/null 2>&1; then
            echo "=====> MongoDB is up - starting Rocket.Chat";
            exec node main.js;
          fi;
          echo "=====> MongoDB not ready yet, retrying in 5 seconds...";
          sleep 5;
        done;
        echo "=====> Giving up waiting for MongoDB after 5 minutes";
        exit 1
    expose:
      - ${PORT:-3000}
      - ${METRICS_PORT:-9458}
    ports:
      - "${BIND_IP:-0.0.0.0}:${HOST_PORT:-3000}:${PORT:-3000}"
      - "${BIND_IP:-0.0.0.0}:${METRICS_PORT:-9458}:${METRICS_PORT:-9458}"
    logging:
      driver: "json-file"
    # healthcheck:
    #   test: ["CMD", "nc", "-zv", "-w", "10", "rocketchat", "${PORT:-3000}"]
    #   interval: 30s
    #   timeout: 10s
    #   retries: 10
    #   start_period: 30s