# BookWyrm Web Container - Production Optimized
# Nginx + Django/Gunicorn web server

FROM bookwyrm-base AS bookwyrm-web

# Switch to root for system package installation
USER root

# Install nginx and supervisor with minimal footprint
RUN apt-get update && apt-get install -y --no-install-recommends \
    nginx-light \
    supervisor \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean \
    && apt-get autoremove -y

# Install Gunicorn in virtual environment
RUN /opt/venv/bin/pip install --no-cache-dir gunicorn

# Copy configuration files
COPY nginx.conf /etc/nginx/nginx.conf
COPY supervisord-web.conf /etc/supervisor/conf.d/supervisord.conf
COPY entrypoint-web.sh /entrypoint.sh

# Create necessary directories and set permissions efficiently
# Logs go to stdout/stderr, so only create cache and temp directories
RUN chmod +x /entrypoint.sh \
    && mkdir -p /var/cache/nginx /var/lib/nginx \
    && mkdir -p /tmp/nginx_client_temp /tmp/nginx_proxy_temp /tmp/nginx_fastcgi_temp /tmp/nginx_uwsgi_temp /tmp/nginx_scgi_temp /tmp/nginx_cache \
    && chown -R www-data:www-data /var/cache/nginx /var/lib/nginx \
    && chown -R bookwyrm:bookwyrm /app \
    && chmod 755 /tmp/nginx_*

# Clean up nginx default files to reduce image size
RUN rm -rf /var/www/html \
    && rm -f /etc/nginx/sites-enabled/default \
    && rm -f /etc/nginx/sites-available/default

# Expose HTTP port
EXPOSE 80

# Health check optimized for web container
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD curl -f http://localhost:80/health/ || curl -f http://localhost:80/ || exit 1

# Run as root to manage nginx and gunicorn via supervisor
USER root

ENTRYPOINT ["/entrypoint.sh"]
CMD ["supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]