# Multi-stage build for smaller final image
FROM python:3.11-alpine AS builder

# Use HTTP repositories to avoid SSL issues, then install dependencies
RUN echo "http://dl-cdn.alpinelinux.org/alpine/v3.22/main" > /etc/apk/repositories \
    && echo "http://dl-cdn.alpinelinux.org/alpine/v3.22/community" >> /etc/apk/repositories \
    && apk update \
    && apk add --no-cache \
        pkgconfig \
        gcc \
        python3-dev \
        musl-dev \
        postgresql-dev \
        linux-headers \
        bash \
        git \
        curl

# Set working directory
WORKDIR /app

# v1.3.x
ARG PIEFED_VERSION=main
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
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

# Runtime stage - much smaller
FROM python:3.11-alpine AS runtime

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

# Install only runtime dependencies
RUN echo "http://dl-cdn.alpinelinux.org/alpine/v3.22/main" > /etc/apk/repositories \
    && echo "http://dl-cdn.alpinelinux.org/alpine/v3.22/community" >> /etc/apk/repositories \
    && apk update \
    && apk add --no-cache \
        ca-certificates \
        curl \
        su-exec \
        dcron \
        libpq \
        jpeg \
        freetype \
        lcms2 \
        openjpeg \
        tiff \
        nginx \
        supervisor \
        redis \
        bash \
        tesseract-ocr \
        tesseract-ocr-data-eng

# Create piefed user
RUN addgroup -g 1000 piefed \
    && adduser -u 1000 -G piefed -s /bin/sh -D piefed

# Set working directory
WORKDIR /app

# Copy application and virtual environment from builder
COPY --from=builder /app /app
COPY --from=builder /app/venv /app/venv

# Compile translations (matching official Dockerfile)
RUN source /app/venv/bin/activate && \
    (pybabel compile -d app/translations || true)

# Set proper permissions - ensure logs directory is writable for dual logging
RUN chown -R piefed:piefed /app \
    && mkdir -p /app/logs /app/app/static/tmp /app/app/static/media \
    && chown -R piefed:piefed /app/logs /app/app/static/tmp /app/app/static/media \
    && chmod -R 755 /app/logs /app/app/static/tmp /app/app/static/media \
    && chmod 777 /app/logs

# 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

# Create directories for logs and runtime
RUN mkdir -p /var/log/piefed /var/run/piefed \
    && chown -R piefed:piefed /var/log/piefed /var/run/piefed 