# ============================================================================
# Tale Proxy Service (Caddy)
# ============================================================================
# This Dockerfile builds a Caddy reverse proxy for the Tale platform
# with configurable HTTPS support (self-signed or Let's Encrypt)
# ============================================================================

# Version argument - injected by CI from git tag, defaults to 'dev' for local builds
ARG VERSION=dev

FROM caddy:2.11-alpine

# Re-declare VERSION arg (ARGs don't persist after FROM)
ARG VERSION=dev
LABEL org.opencontainers.image.version="${VERSION}" \
      org.opencontainers.image.title="tale-proxy" \
      org.opencontainers.image.description="Tale Proxy — Caddy reverse proxy with auto-TLS" \
      org.opencontainers.image.source="https://github.com/tale-project/tale" \
      org.opencontainers.image.vendor="Tale" \
      org.opencontainers.image.licenses="MIT"

# Set environment variables with sensible defaults
ENV TALE_VERSION=${VERSION} \
    HOST=tale.local \
    TLS_MODE=selfsigned

# Copy Caddyfile
COPY services/proxy/Caddyfile /etc/caddy/Caddyfile

# Copy maintenance page for deployment transitions
# Shown when no healthy backends are available (e.g., during blue-green deployment)
COPY services/proxy/maintenance.html /var/www/maintenance.html

# Copy entrypoint script that fixes certificate permissions
COPY services/proxy/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# Expose HTTP and HTTPS ports
EXPOSE 80 443

# Caddy will automatically handle HTTPS certificate management
# Certificates are stored in /data/caddy
VOLUME /data

# Health check via dedicated internal port (not exposed externally)
# Uses :2020 to avoid interfering with Caddy's ACME challenge handling on :80
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://127.0.0.1:2020/health || exit 1

# Use custom entrypoint that:
# 1. Generates TLS config based on TLS_MODE
# 2. Makes CA certificates readable
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
# Config is at /config/Caddyfile (generated by entrypoint from /etc/caddy/Caddyfile template)
CMD ["caddy", "run", "--config", "/config/Caddyfile", "--adapter", "caddyfile"]
