FROM devxygmbh/r-alpine:4.4-3.20 AS build

# ARG GITHUB_PAT
RUN apk add --no-cache curl ca-certificates \
  && curl -fsSL https://raw.githubusercontent.com/nbafrank/uvr/main/install.sh \
    | UVR_INSTALL_DIR=/usr/local/bin sh

# One uvr project drives both dependency installs below. UVR_LIBRARY points the
# syncs at the image's R library instead of the project-local .uvr/library/, so
# `Rscript app.R` finds the packages without a uvr-aware .Rprofile.
ENV UVR_LIBRARY=/usr/lib/R/library
RUN mkdir -p /uvr && cd /uvr && uvr init --here

COPY --link ./DESCRIPTION .
COPY --link ./R ./R
# COPY --link ./man .
COPY --link ./NAMESPACE .
COPY --link ./shiny/app.R /app/app.R

RUN ls -la

# install R package deps. uvr has no equivalent of bare `pak::pak()`, which
# reads the DESCRIPTION in the working directory, so extract the dependency
# names and hand them to `uvr add`.
RUN R -q --no-echo -e "d <- read.dcf('DESCRIPTION'); f <- intersect(colnames(d), c('Depends', 'Imports', 'LinkingTo')); p <- trimws(sub('[(].*', '', unlist(strsplit(paste(d[, f], collapse = ','), ',')))); writeLines(setdiff(p[nzchar(p)], c('R', rownames(installed.packages()))), '/tmp/deps.txt')" \
  && cd /uvr && xargs -r uvr add --no-install < /tmp/deps.txt \
  && uvr sync --install-system-deps

RUN R CMD INSTALL --no-docs --without-keep.source  .

# install shiny app deps
RUN R -q -e "install.packages('renv'); pkgs <- renv::dependencies('/app/app.R')[['Package']]; pkgs = setdiff(pkgs, 'bincraft'); writeLines(pkgs, '/tmp/app-deps.txt')" \
  && cd /uvr && xargs -r uvr add --no-install < /tmp/app-deps.txt \
  && uvr sync --install-system-deps

ENV PGPASS=""

RUN echo "options(shiny.port=3838, shiny.host='0.0.0.0')" >> /root/.Rprofile

WORKDIR /app
EXPOSE 3838

CMD Rscript app.R
