# Multi-stage build for smaller final image
FROM python:3.11-alpine3.21 AS builder

# Install build dependencies
RUN apk add --no-cache \
        pkgconfig \
        gcc \
        python3-dev \
        musl-dev \
        postgresql-dev \
        linux-headers \
        bash \
        git \
        curl

# Set working directory
WORKDIR /app

# Clone PieFed source
ARG PIEFED_VERSION=v1.5.1
RUN git clone https://codeberg.org/rimu/pyfedi.git /app \
    && cd /app \
    && git checkout ${PIEFED_VERSION} \
    && rm -rf .git

# Install Python dependencies to /app/venv and clean up cache/bytecode
RUN python -m venv /app/venv \
    && source /app/venv/bin/activate \
    && pip install --no-cache-dir -r requirements.txt \
    && pip install --no-cache-dir uwsgi \
    && find /app/venv -name "*.pyc" -delete \
    && find /app/venv -name "__pycache__" -type d -exec rm -rf {} + 2>/dev/null || true \
    && find /app -name "*.pyo" -delete 2>/dev/null || true

# Runtime stage - much smaller
FROM python:3.11-alpine3.21 AS runtime

# Set environment variables
ENV TZ=UTC
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV PATH="/app/venv/bin:$PATH"

# Install only runtime dependencies (no redis server, nginx, dcron, or tesseract - not needed)
# - redis: using external Redis cluster, only Python client needed
# - nginx: only needed in web container, installed there
# - dcron: using Kubernetes CronJobs for scheduling
# - tesseract: OCR not used by PieFed
RUN apk add --no-cache \
        ca-certificates \
        curl \
        su-exec \
        libpq \
        jpeg \
        freetype \
        lcms2 \
        openjpeg \
        tiff \
        supervisor \
        bash

# Create piefed user and set up directories in a single layer
# Note: /app/app/static/media is volume-mounted in K8s, fsGroup handles permissions there
# Other directories need explicit ownership for logging and temp files
RUN addgroup -g 1000 piefed \
    && adduser -u 1000 -G piefed -s /bin/sh -D piefed \
    && mkdir -p /app/logs /app/app/static/tmp /app/app/static/media \
        /var/log/piefed /var/run/piefed \
    && chown -R piefed:piefed /app/logs /app/app/static/tmp \
        /var/log/piefed /var/run/piefed

# Set working directory
WORKDIR /app

# Copy application and virtual environment from builder (venv is inside /app)
COPY --from=builder --chown=piefed:piefed /app /app

# Compile translations and set permissions in a single layer
RUN source /app/venv/bin/activate \
    && (pybabel compile -d app/translations || true) \
    && chmod 755 /app/logs /app/app/static/tmp

# Copy shared entrypoint utilities
COPY entrypoint-common.sh /usr/local/bin/entrypoint-common.sh
COPY entrypoint-init.sh /usr/local/bin/entrypoint-init.sh
RUN chmod +x /usr/local/bin/entrypoint-common.sh /usr/local/bin/entrypoint-init.sh 