FROM caddy:2.7-alpine

# Install dependencies including Chromium and required libraries for Puppeteer
RUN apk add --no-cache \
    nodejs \
    npm \
    bash \
    chromium \
    nss \
    freetype \
    freetype-dev \
    harfbuzz \
    ca-certificates \
    ttf-freefont

# Set Puppeteer to use system Chromium
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser

# Set working directory
WORKDIR /srv

# Copy website files
COPY . /srv

# Install npm dependencies for PDF generation
RUN cd /srv && npm install --production

# Run all update scripts (sitemap, navigation, stories, CSP hashes, accessibility fixes)
RUN cd /srv && \
    chmod +x update-all.sh && \
    ./update-all.sh

# Generate PDFs for all pages (only if they don't already exist)
RUN if [ ! -d "/srv/pdfs" ] || [ -z "$(ls -A /srv/pdfs 2>/dev/null)" ]; then \
        cd /srv && npm run generate-pdfs; \
    else \
        echo "PDFs already exist, skipping generation"; \
    fi

# Expose port
EXPOSE 8080

# Start Caddy with the local Caddyfile
CMD ["caddy", "run", "--config", "/srv/Caddyfile.local"]
