FROM chirpstack/chirpstack:4 as base

FROM alpine:3.23.4

COPY --from=base /usr/bin/chirpstack /usr/bin/chirpstack

RUN apk --no-cache add ca-certificates

# Create config directory and file
# Build DSN piece by piece to avoid Docker secret masking
RUN mkdir -p /etc/chirpstack && \
    echo '[logging]' > /etc/chirpstack/chirpstack.toml && \
    echo '  level="info"' >> /etc/chirpstack/chirpstack.toml && \
    echo '' >> /etc/chirpstack/chirpstack.toml && \
    echo '[postgresql]' >> /etc/chirpstack/chirpstack.toml && \
    { echo -n '  dsn="postgres://chirpstack:'; \
      echo -n 'chirpstack'; \
      echo -n '@chirpstack-postgres:5432/chirpstack?sslmode=disable"'; \
      echo; } >> /etc/chirpstack/chirpstack.toml && \
    echo '  max_open_connections=10' >> /etc/chirpstack/chirpstack.toml && \
    echo '  min_idle_connections=0' >> /etc/chirpstack/chirpstack.toml && \
    echo '' >> /etc/chirpstack/chirpstack.toml && \
    echo '[redis]' >> /etc/chirpstack/chirpstack.toml && \
    echo '  servers=["redis://chirpstack-redis:6379/"]' >> /etc/chirpstack/chirpstack.toml && \
    echo '  tls_enabled=false' >> /etc/chirpstack/chirpstack.toml && \
    echo '  cluster=false' >> /etc/chirpstack/chirpstack.toml && \
    echo '' >> /etc/chirpstack/chirpstack.toml && \
    echo '[network]' >> /etc/chirpstack/chirpstack.toml && \
    echo '  net_id="000000"' >> /etc/chirpstack/chirpstack.toml && \
    echo '  enabled_regions=["eu868"]' >> /etc/chirpstack/chirpstack.toml && \
    echo '' >> /etc/chirpstack/chirpstack.toml && \
    echo '[api]' >> /etc/chirpstack/chirpstack.toml && \
    echo '  bind="0.0.0.0:8080"' >> /etc/chirpstack/chirpstack.toml && \
    echo '  secret="you-must-replace-this"' >> /etc/chirpstack/chirpstack.toml && \
    echo '' >> /etc/chirpstack/chirpstack.toml && \
    echo '[integration]' >> /etc/chirpstack/chirpstack.toml && \
    echo '  enabled=["mqtt"]' >> /etc/chirpstack/chirpstack.toml && \
    echo '  [integration.mqtt]' >> /etc/chirpstack/chirpstack.toml && \
    echo '    server="tcp://mosquitto:1883/"' >> /etc/chirpstack/chirpstack.toml && \
    echo '    json=true' >> /etc/chirpstack/chirpstack.toml

USER nobody:nogroup
ENTRYPOINT ["/usr/bin/chirpstack"]
