# 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
COPY .Rprofile /srv/shiny-server/.Rprofile

# Prevent renv attempting to use pak
ENV RENV_CONFIG_PAK_ENABLED=FALSE
ENV RENV_DOWNLOAD_METHOD=libcurl
ENV RENV_PATHS_CACHE=/srv/shiny-server/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 R --vanilla -e "install.packages('renv', repos='https://cran.rstudio.com')" && \
    R --vanilla -e "source('.Rprofile'); renv::restore(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

# Fail the image build if the app cannot start in the same user context as
# Shiny Server, rather than discovering startup errors after deployment.
RUN su -s /bin/sh shiny -c "cd /srv/shiny-server && R --vanilla -e 'source(\".Rprofile\"); source(\"global.R\")'"

EXPOSE 3838

HEALTHCHECK --interval=30s --timeout=5s --start-period=90s --retries=3 \
  CMD curl --fail --silent --show-error http://127.0.0.1:3838/ || exit 1

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