# syntax=docker/dockerfile:1.7
FROM rocker/shiny:4.4.0

# System dependencies commonly required by R packages
RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    libcurl4-openssl-dev \
    libssl-dev \
    libxml2-dev \
    libgit2-dev \
    libfontconfig1-dev \
    libharfbuzz-dev \
    libfribidi-dev \
    libfreetype6-dev \
    libpng-dev \
    libjpeg-dev \
    libtiff5-dev \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /srv/shiny-server

# Copy dependency manifests first so package restore can be cached
COPY renv.lock /srv/shiny-server/renv.lock
COPY renv /srv/shiny-server/renv

# Prevent renv attempting to use pak
ENV RENV_CONFIG_PAK_ENABLED=FALSE
ENV RENV_DOWNLOAD_METHOD=libcurl
ENV RENV_PATHS_CACHE=/opt/renv/cache

# Some CRAN packages in this lockfile fail under Ubuntu hardening defaults
# because -Werror=format-security turns benign warnings into build failures.
RUN for f in /usr/local/lib/R/etc/Makeconf /usr/lib/R/etc/Makeconf; do \
      if [ -f "$f" ]; then \
        sed -i 's/-Werror=format-security/-Wno-error=format-security/g' "$f"; \
      fi; \
    done

# Install renv and restore project packages
RUN --mount=type=cache,target=/opt/renv/cache \
    --mount=type=cache,target=/root/.cache/R/renv \
    R --vanilla -e "install.packages('renv', repos='https://cran.rstudio.com')" && \
    R --vanilla -e "renv::restore(project='/srv/shiny-server', lockfile='/srv/shiny-server/renv.lock', prompt=FALSE)"

# Copy the application after dependencies so regular code changes do not
# invalidate the expensive restore layer.
COPY . /srv/shiny-server/

# Permissions
RUN chown -R shiny:shiny /srv/shiny-server

EXPOSE 3838

CMD ["/usr/bin/shiny-server"]