FROM nginx:1.25-alpine

# Install necessary packages for SSL and security
RUN apk add --no-cache \
    tini \
    openssl \
    certbot \
    certbot-nginx \
    && rm -rf /var/cache/apk/*

# Create non-root user
RUN addgroup -g 1001 -S nginx-user && \
    adduser -S -D -H -u 1001 -h /var/cache/nginx -s /sbin/nologin -G nginx-user nginx-user

# Create directories
RUN mkdir -p /etc/nginx/conf.d \
             /etc/nginx/sites-enabled \
             /var/log/nginx \
             /etc/letsencrypt \
             /var/www/certbot

# Copy configuration files
COPY conf/nginx.conf /etc/nginx/nginx.conf
COPY conf/sites-enabled/ /etc/nginx/sites-enabled/
COPY conf/ssl.conf /etc/nginx/conf.d/ssl.conf
COPY conf/upstream.conf /etc/nginx/conf.d/upstream.conf
COPY conf/security.conf /etc/nginx/conf.d/security.conf

# Copy SSL maintenance scripts
COPY scripts/ssl-renew.sh /usr/local/bin/ssl-renew.sh
RUN chmod +x /usr/local/bin/ssl-renew.sh

# Set proper permissions
RUN chown -R nginx-user:nginx-user /var/cache/nginx \
                                   /var/log/nginx \
                                   /etc/nginx/conf.d \
                                   /etc/nginx/sites-enabled \
                                   /var/www/certbot

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost/health || exit 1

# Expose ports
EXPOSE 80 443

# Use tini as init system
ENTRYPOINT ["/sbin/tini", "--"]

# Start Nginx (run as root for port binding, nginx will drop privileges)
CMD ["nginx", "-g", "daemon off;"]