FROM ubuntu:jammy AS nodejs

RUN apt-get -q update \
  && apt-get upgrade -y

# Switch to bash instead of sh
RUN apt-get -q update \
  && DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends -y \
    ca-certificates \
    wget \
    unzip \
  && update-ca-certificates --fresh    

RUN wget -qO- https://deb.nodesource.com/setup_18.x | bash -

FROM nodejs AS runtime

RUN apt-get -q update \
  && DEBIAN_FRONTEND=noninteractive apt-get install \
    --no-install-recommends -y \
    nodejs \
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/{apt,dpkg,cache,log} \
  && npm install -g npm@latest

RUN apt-get -q update \
  && DEBIAN_FRONTEND=noninteractive apt-get install \
    --no-install-recommends -y \
    rsync \
    wget \
    curl \
    nginx \
    shellinabox \
    nano \
    less \
    iputils-ping \
    curl \
    jq \
    sqlite3 \
    tree \
    inotify-tools \
    gettext-base \
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/{apt,dpkg,cache,log}

# Build dependencies when running npm install
RUN apt-get -q update \
  && DEBIAN_FRONTEND=noninteractive apt-get install \
    --no-install-recommends -y \
    make \
    python-is-python3 \
    gcc \
    g++ \
    libc-dev \
  && apt-get clean \
  && rm -rf /var/lib/apt/lists/{apt,dpkg,cache,log}

SHELL [ "/bin/bash", "-c" ]

ARG DEVELOPMENT
ENV DEVELOPMENT=${DEVELOPMENT:-}
ARG CHAT_BASE
ENV CHAT_BASE=${CHAT_BASE}
ARG CHAT_URL
ENV CHAT_URL=${CHAT_URL}

COPY /.env /home/user/.env
RUN { \
  echo "REACT_APP_CHAT_URL=${CHAT_URL}" ; \
  echo "REACT_APP_CHAT_BASE=${CHAT_BASE}" ; \
  echo "PUBLIC_URL=${CHAT_BASE}" ; \
  echo "WDS_SOCKET_PATH=/ws" ; \
  echo "WDS_SOCKET_HOST=${CHAT_URL#http*://}" ; \
  echo "WDS_SOCKET_PORT=443" ; \
} | tee -a /home/user/.env

COPY /server /home/user/server
COPY /server/nginx.conf /etc/nginx/sites-enabled/default
WORKDIR /home/user/server
RUN npm install

COPY /client /home/user/client
WORKDIR /home/user/client
RUN npm install

# If not DEVELOPMENT mode, copy production config, else development
RUN \
  if [[ -z "${DEVELOPMENT}" ]]; then \
    echo "Building PRODUCTION" ; \
    cp /home/user/server/production.location \
      /etc/nginx/snippets/active.location ; \
  else \
    echo "Building DEVELOPMENT" ; \
    cp /home/user/server/development.location \
      /etc/nginx/snippets/active.location ; \
  fi

# If not DEVELOPMENT mode, then locally build project
RUN \
  if [[ -z "${DEVELOPMENT}" ]]; then \
    cd /home/user/client ; \
    npm run build ; \
  fi

COPY /scripts /opt/scripts

ENV PATH="${PATH}:/opt/scripts"

COPY /Dockerfile /home/user/Dockerfile

# alias out 'sudo' since USER is root and we want to copy/paste
# commands from our README.md that contains 'sudo'
RUN echo "alias sudo=" >> /root/.bashrc

# In DEVELOPMENT mode, entrypoint launches 'npm start'
WORKDIR /home/user
COPY /entrypoint.sh /
CMD [ "/opt/scripts/irepo-shell" ]
ENTRYPOINT [ "/entrypoint.sh" ]