# Source image to build the Golang password sync app.
FROM golang:1.16-alpine as builder

# Deploy and build the password sync app
WORKDIR /app
COPY secret2file/* ./
RUN go build -o secret2file .

# Target image based on Nginx.
# Use the latest mainline version to avoid stale versioning.
FROM nginx:mainline-alpine

# Install bash to run management scripts.
RUN apk add --no-cache bash

# Fetch the password sync app from the build stage.
COPY --from=builder /app/secret2file /usr/local/bin/

# Deploy Nginx configuration.
RUN mkdir /etc/nginx/auth /etc/nginx/templates
COPY nginx/nginx.conf /etc/nginx/
COPY nginx/conf.d/* /etc/nginx/templates/

# Deploy Nginx config entrypoint script.
COPY 99-print-config.sh /docker-entrypoint.d/
RUN chown root:root /docker-entrypoint.d/99-print-config.sh \
  && chmod 755 /docker-entrypoint.d/99-print-config.sh

# Deploy password sync entrypoint script.
COPY 90-start-sync.sh /docker-entrypoint.d/
RUN chown root:root /docker-entrypoint.d/90-start-sync.sh \
  && chmod 755 /docker-entrypoint.d/90-start-sync.sh

# Deploy password sync script.
COPY sync-htpasswd.sh /usr/local/bin/
RUN chown root:root /usr/local/bin/sync-htpasswd.sh \
  && chmod 755 /usr/local/bin/sync-htpasswd.sh

# Configure Nginx settings using environment variables.
ENV NGINX_PROXY_HTTP_VERSION=1.1 \
  NGINX_PROXY_BUFFER_SIZE=16k \
  NGINX_PROXY_BUSY_BUFFERS_SIZE=24k \
  NGINX_PROXY_BUFFERS="64 4k" \
  NGINX_PROXY_CONNECT_TIMEOUT=60s \
  NGINX_PROXY_SEND_TIMEOUT=5m \
  NGINX_PROXY_READ_TIMEOUT=5m \
  NGINX_CLIENT_MAX_BODY_SIZE=8m \
  NGINX_CLIENT_BODY_BUFFER_SIZE=128k

# Configure scripts settings using environment variables.
ENV SYNC_DELAY=60s
