# Start with the official n8n image
FROM n8nio/n8n:2.13.1

# Copy apk and its deps from Alpine 3.23
COPY --from=alpine:3.23 /sbin/apk /sbin/apk
COPY --from=alpine:3.23 /usr/lib/libapk.so* /usr/lib/

# Switch to root to install dependencies
USER root

# Install Chromium and necessary dependencies for Puppeteer
RUN set -x \
    && apk update \
    && apk upgrade \
    && apk add --no-cache \
    udev \
    chromium \
    nss \
    freetype \
    harfbuzz \
    ca-certificates \
    ttf-freefont \
    wget \
    nodejs \
    npm

# Set environment variable for Puppeteer to find Chromium
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
ENV XDG_CONFIG_HOME=/tmp/.chromium
ENV XDG_CACHE_HOME=/tmp/.chromium

# Install Puppeteer
RUN npm install puppeteer

# Install restic and rclone for backups
RUN apk add --no-cache \
    restic \
    curl \
    unzip

# Download and install rclone
RUN curl -O https://downloads.rclone.org/rclone-current-linux-amd64.zip \
    && unzip rclone-current-linux-amd64.zip \
    && cd rclone-*-linux-amd64 \
    && cp rclone /usr/local/bin/ \
    && chmod 755 /usr/local/bin/rclone \
    && cd .. && rm -rf rclone-*-linux-amd64*

# Revert back to non-root (default n8n user)
USER node
