######
# BASE
######
FROM ubuntu:20.04 AS base

ENV UNITY_PATH /opt/unity

ENV DEBIAN_FRONTEND noninteractive
ENV DEBCONF_NONINTERACTIVE_SEEN true

RUN apt-get -q update \
    && apt-get -q install -y --no-install-recommends apt-utils \
    && apt-get -q install -y --no-install-recommends --allow-downgrades \
        ca-certificates \
        libasound2 \
        libgconf-2-4 \
        libgtk-3-0 \
        libnss3 \
        libxtst6 \
        libxss1 \
        atop \
        cpio \
        curl \
        lsb-release \
        wget \
        xvfb \
        xz-utils \
        # NB: there's a bug in WebGL build pipeline that requires ncurses5
        libncurses5 \
        # NB: the linking phase of the WebGL build requires python2 for some reason
        python2 \
    && apt-get clean

RUN cd /usr/bin && ln -s /usr/bin/python2 python

RUN echo "a2c13f6d23ba43658da088d2cb4b9890" > /etc/machine-id && ln -sf /etc/machine-id /var/lib/dbus/machine-id

#####
# HUB
#####
FROM base AS hub

ARG unity_version=2019.4.13f1
ARG unity_module=webgl

RUN apt-get -q update \
    && apt-get -q install -y --no-install-recommends --allow-downgrades zenity \
    && apt-get clean

RUN wget --no-verbose -O /tmp/UnityHub.AppImage "https://public-cdn.cloud.unity3d.com/hub/prod/UnityHub.AppImage" \
    && chmod +x /tmp/UnityHub.AppImage \
    && cd /tmp \
    && /tmp/UnityHub.AppImage --appimage-extract \
    && cp -R /tmp/squashfs-root/* / \
    && rm -rf /tmp/squashfs-root /tmp/UnityHub.AppImage \
    && mkdir -p "$UNITY_PATH" \
    && mv /AppRun /opt/unity/UnityHub

RUN echo '#!/bin/bash\nxvfb-run -ae /dev/stdout /opt/unity/UnityHub --no-sandbox --headless "$@"' > /usr/bin/unity-hub \
    && chmod +x /usr/bin/unity-hub

RUN mkdir -p "/root/.config/Unity Hub" \
    && touch "/root/.config/Unity Hub/eulaAccepted"

RUN mkdir -p "${UNITY_PATH}/editors" \
    && unity-hub install-path --set "${UNITY_PATH}/editors/" \
    && find /tmp -mindepth 1 -delete

# ARG changeSet

RUN unity-hub install \
    --version "${unity_version}" \
    # --changeset "$changeSet" \
        | grep 'Error' \
        | exit $(wc -l)

RUN unity-hub install-modules \
    --version "${unity_version}" \
    --module "${unity_module}" --childModules \
        | grep 'Missing module' \
        | exit $(wc -l)

########
# EDITOR
########
FROM base

ARG unity_version=2019.4.13f1

COPY --from=hub /opt/unity/editors/${unity_version} "$UNITY_PATH/"

RUN echo "${unity_version}" > "$UNITY_PATH/version"

RUN echo '#!/bin/bash\nxvfb-run -ae /dev/stdout "$UNITY_PATH/Editor/Unity" -batchmode "$@"' > /usr/bin/unity-editor \
    && chmod +x /usr/bin/unity-editor
