FROM alpine:3.9 AS common

RUN apk add gnupg ffmpeg

# Add peertube user
RUN addgroup -S peertube && \
    adduser -S -G peertube -h /var/lib/peertube peertube


FROM common AS builder

##
## Download target release
##

ENV PEERTUBE_RELEASE=v2.1.1


RUN apk add wget
COPY ./*.patch /tmp
RUN mkdir -p /opt/apps/peertube && \
    cd /opt/apps/peertube && \
    wget https://github.com/Chocobozzz/PeerTube/releases/download/${PEERTUBE_RELEASE}/peertube-${PEERTUBE_RELEASE}.tar.xz && \
    tar -xJf peertube-${PEERTUBE_RELEASE}.tar.xz && \
    rm peertube-${PEERTUBE_RELEASE}.tar.xz && \
    mv peertube-${PEERTUBE_RELEASE}/* . && \
    rmdir peertube-${PEERTUBE_RELEASE} && \
    cat /tmp/*.patch | patch -p1 && \
    mkdir -p /etc/peertube /var/lib/peertube && \
    ln -sf /var/lib/peertube /opt/apps/peertube/storage

RUN apk add yarn                        ## Build command
RUN apk add git build-base python bash  ## Build deps

RUN chown -R peertube:peertube /opt/apps/peertube

RUN apk add npm  ## only needed to install things that should be in yarn

USER peertube

RUN cd /opt/apps/peertube && \
    npm install bcrypt && \
    yarn install --production --pure-lockfile && \
    yarn cache clean

## XXXvlab: without this in current docker version, it'll
## permeate in next image to be built.
USER root

# RUN apk add nodejs yarn
#
## Source build (very long)
#
# ## To download source
# RUN apk add git
# RUN git clone https://github.com/chocobozzz/PeerTube /tmp/peertube --depth 1

# ## for installation of dependencies
# RUN apk add build-base python
# RUN cd /tmp/peertube && \
#     yarn install --pure-lockfile

# ## for scripts run by ``npm run build``
# RUN apk add bash
# RUN cd /tmp/peertube && \
#     npm run build

# RUN cd /tmp/peertube && \
#     rm -r ./node_modules ./client/node_modules && \
#     yarn install --pure-lockfile --production && \
#     yarn cache clean


FROM common

# Install PeerTube
COPY --from=builder /opt/apps/peertube /opt/apps/peertube


# RUN mkdir -p /var/lib/peertube /etc/peertube && \
#     chown -R peertube:peertube /var/lib/peertube /etc/peertube

# ENV PEERTUBE_APP_DIR=/opt/apps/peertube
# ENV PEERTUBE_DATA_DIR=/var/lib/peertube

## This is important to set config dir of peertube
ENV NODE_CONFIG_DIR=/etc/peertube
ENV NODE_ENV=prod

VOLUME /var/lib/peertube
VOLUME /etc/peertube

EXPOSE 9000

RUN apk add nodejs-npm

## runtime deps
RUN apk add openssl

## to check if postgres is fine BEFORE running the app
RUN apk add postgresql-client

COPY src/ .

USER peertube
WORKDIR /opt/apps/peertube

CMD ["/entrypoint.sh"]