# The Traefik Configurator agent.
#
# A container that sits beside Traefik and does the work the WordPress plugin
# asks for: read and write the static configuration, write dynamic files,
# manage Traefik's own plugins, restart, and roll back when a change does not
# come up.
#
# It is deliberately tiny and deliberately dull. No language runtime, no
# framework, no package manager at run time - busybox's own web server in front
# of one shell script that accepts twelve verbs and nothing else.
#
# Build from the plugin folder:
#   docker build -f docker/Dockerfile -t tpv-traefik-agent .
#
# Author: Tanveer Ahmed

FROM alpine:3.20

RUN apk add --no-cache curl tini \
 && addgroup -S tpv && adduser -S -G tpv tpv \
 && mkdir -p /srv/www/cgi-bin /var/lib/tpv-traefik/backups \
 && chown -R tpv:tpv /var/lib/tpv-traefik

COPY host/tpv-traefik-hostctl.sh /usr/local/sbin/tpv-traefik-hostctl.sh
COPY docker/agent-cgi.sh          /srv/www/cgi-bin/tpv

RUN chmod 0755 /usr/local/sbin/tpv-traefik-hostctl.sh /srv/www/cgi-bin/tpv

# The document root holds one thing: cgi-bin/tpv. There is no static file to
# serve and no index, so the only reachable path is the script itself.

# Where the proxy is, from in here. Every one of these can be overridden at
# run time, and the agent reports what it found on its capabilities verb.
ENV TPV_STATIC=/etc/traefik/traefik.yml \
    TPV_DYNAMIC_DIR=/etc/traefik/dynamic \
    TPV_STATE_DIR=/var/lib/tpv-traefik \
    TPV_DOCKER_SOCK=/var/run/docker.sock \
    TPV_AGENT_READONLY=no

EXPOSE 9443

HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
  CMD wget -qO- http://127.0.0.1:9443/cgi-bin/tpv/v1/health | grep -q 'ok=yes' || exit 1

# Runs as root by default because writing /etc/traefik and restarting a
# container both need it. Run it as an unprivileged user with
# `user: "1000:1000"` in compose when the files allow that - the agent works
# either way and its capabilities verb will tell you which of them it can do.
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["/usr/sbin/httpd", "-f", "-vv", "-p", "9443", "-h", "/srv/www"]
