# Based on https://github.com/Haoen-Cui/baker-bayesian-analysis-in-docker/blob/master/Dockerfile and https://github.com/jflournoy/verse-cmdstan/blob/main/Dockerfile.

FROM rocker/verse:4.3.1


# Install g++ compiler
RUN apt-get update \
	&& apt-get install g++ \
	&& rm -rf /var/lib/apt/lists/*
	
	
# install system dependencies for R packages 
RUN apt-get update \
    && apt-get install -y --no-install-recommends gfortran libudunits2-dev libgdal-dev \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/ 


# global site-wide config, neeeded for building packages
RUN mkdir -p $HOME/.R/ \
    && echo "\nCXX14=g++ -ftemplate-depth-256" >> $HOME/.R/Makevars \
    && echo "CXX14FLAGS=-O3 -mtune=native -march=native -fPIC -Wno-unused-variable -Wno-unused-function -Wno-unused-local-typedefs -Wno-ignored-attributes -Wno-deprecated-declarations" >> $HOME/.R/Makevars 


# Install rstan
RUN R -e "install.packages('V8')"
RUN R -e "install.packages('rstan', repos = c('https://mc-stan.org/r-packages/', getOption('repos')))"


# Install cmdstanr
WORKDIR /cmdstan

ENV CMDSTANVER="2.33.1"
RUN apt-get update
RUN apt-get -y install htop
RUN apt-get install --no-install-recommends -qq wget ca-certificates make
RUN R -e "install.packages('remotes')"
RUN R -e "remotes::install_github('stan-dev/cmdstanr')"
RUN Rscript -e "cmdstanr::install_cmdstan('/cmdstan', cores=2)"
ENV CMDSTAN /cmdstan/cmdstan-${CMDSTANVER}
RUN chmod a+w -R ${CMDSTAN}
RUN echo "CMDSTAN=/cmdstan/cmdstan-${CMDSTANVER}" >> ${R_HOME}/etc/Renviron

WORKDIR /
	

# Config for rstudio user
RUN mkdir -p /home/rstudio/.R/ \
    && echo "\nCXX14=g++\n" >> /home/rstudio/.R/Makevars \
    && echo "CXX14FLAGS=-O3\n" >> /home/rstudio/.R/Makevars


# Install the rethinking package
RUN R -e "install.packages(c('coda', 'mvtnorm', 'devtools', 'loo', 'dagitty'))"
RUN R -e "devtools::install_github('rmcelreath/rethinking')"


# Install packages for markdown files
RUN R -e "install.packages('markdown')"
RUN R -e "install.packages('rmarkdown')"


# To wrap lines
RUN R -e "install.packages('formatR')"
