# documentation: https://mosquitto.org/documentation/
# slogan: Mosquitto is lightweight and suitable for use on all devices, from low-power single-board computers to full servers.
# category: messaging
# tags: mosquitto, mqtt, open-source
# logo: svgs/mosquitto.svg
# port: 1883

services:
  mosquitto:
    image: eclipse-mosquitto
    environment:
      - SERVICE_URL_MOSQUITTO_1883
      - MQTT_USERNAME=${SERVICE_USER_MOSQUITTO}
      - MQTT_PASSWORD=${SERVICE_PASSWORD_MOSQUITTO}
      - REQUIRE_CERTIFICATE=${REQUIRE_CERTIFICATE:-false}
      - ALLOW_ANONYMOUS=${ALLOW_ANONYMOUS:-true}
    volumes:
      - mosquitto-config:/mosquitto/config
      - mosquitto-certs:/certs
    healthcheck:
      test: ["CMD-SHELL", "exit 0"]
      interval: 30s
      timeout: 10s
      retries: 3

    entrypoint: 'sh -c "
      if [ ''$REQUIRE_CERTIFICATE'' = ''true'' ]; then
      echo ''listener 8883'' > /mosquitto/config/mosquitto.conf &&
      echo ''cafile /certs/ca.crt'' >> /mosquitto/config/mosquitto.conf &&
      echo ''certfile /certs/server.crt'' >> /mosquitto/config/mosquitto.conf &&
      echo ''keyfile  /certs/server.key'' >> /mosquitto/config/mosquitto.conf;
      else
      echo ''listener 1883'' > /mosquitto/config/mosquitto.conf;
      fi &&
      echo ''require_certificate ''$REQUIRE_CERTIFICATE >> /mosquitto/config/mosquitto.conf &&
      echo ''allow_anonymous ''$ALLOW_ANONYMOUS >> /mosquitto/config/mosquitto.conf;
      if [ -n ''$SERVICE_USER_MOSQUITTO''] && [ -n ''$SERVICE_PASSWORD_MOSQUITTO'' ]; then
      echo ''password_file /mosquitto/config/passwords'' >> /mosquitto/config/mosquitto.conf &&
      touch /mosquitto/config/passwords &&
      chmod 0700 /mosquitto/config/passwords &&
      chown root:root /mosquitto/config/passwords &&
      mosquitto_passwd -b -c /mosquitto/config/passwords $SERVICE_USER_MOSQUITTO $SERVICE_PASSWORD_MOSQUITTO &&
      chown mosquitto:mosquitto /mosquitto/config/passwords;
      fi &&
      exec mosquitto -c /mosquitto/config/mosquitto.conf
      "'
    labels:
      - traefik.tcp.routers.mqtt.entrypoints=mqtt
      - traefik.tcp.routers.mqtts.entrypoints=mqtts
