FROM rust:1.92-alpine3.23 AS builder

# Install build deps and binutils (for strip)
RUN apk add --no-cache build-base musl-dev openssl-dev pkgconfig ca-certificates curl binutils
WORKDIR /app

# Copy manifest first to leverage Docker layer caching for dependencies
COPY ./Cargo.toml ./
RUN cargo fetch --locked || true

COPY ./src ./src

# Build the release binary and strip it to reduce size
RUN cargo build --release --bin yanpm-agent && \
  strip target/release/yanpm-agent || true

FROM nginx:mainline-alpine3.23 AS base

# Expose typical HTTP ports used by nginx
EXPOSE 80 443

ENV S6_KEEP_ENV=1
ENV YANPM_AGENT_SOCK=/var/run/yanpm/yanpm-agent.sock
ENV YANPM_NGINX_CONFIG_DIR=/etc/nginx/conf.d
ENV YANPM_AGENT_SOCK_PERM=660
ENV YANPM_AGENT_SOCK_GID=""
ENV YANPM_AGENT_UID=1000
ENV YANPM_AGENT_GID=1000

WORKDIR /app

# Install ca-certificates for TLS and minimal tools
RUN apk add --no-cache ca-certificates curl

# Install s6-overlay
ENV S6_OVERLAY_VERSION=v3.2.1.0
ADD https://github.com/just-containers/s6-overlay/releases/download/${S6_OVERLAY_VERSION}/s6-overlay-noarch.tar.xz /tmp
RUN tar -C / -Jxpf /tmp/s6-overlay-noarch.tar.xz && rm /tmp/s6-overlay-noarch.tar.xz
ADD https://github.com/just-containers/s6-overlay/releases/download/${S6_OVERLAY_VERSION}/s6-overlay-x86_64.tar.xz /tmp/s6-overlay.tar.xz
RUN tar -C / -Jxpf /tmp/s6-overlay.tar.xz && rm /tmp/s6-overlay.tar.xz

# Runtime user creation handled by s6 cont-init (see /etc/cont-init.d)
# create directory for yanpm agent socket; ownership will be fixed at container start
RUN mkdir -p /var/run/yanpm

# Copy s6 service definitions (created in repo under s6/) into image
COPY ./docker/s6/services.d /etc/services.d
COPY ./docker/s6/cont-init.d /etc/cont-init.d
RUN chmod +x /etc/services.d/*/run && chmod +x /etc/cont-init.d/*

COPY --from=builder /app/target/release/yanpm-agent ./yanpm-agent

RUN chmod +x /app/yanpm-agent

# s6-overlay provides /init as the init process
ENTRYPOINT ["/init"]
