ARG VELOCITY_VERSION=latest
ARG JAVA_VERSION=21

FROM alpine AS tools
RUN apk add --update-cache --no-cache \
        curl \
        jq

FROM tools AS waterfall
RUN if test -z "${VELOCITY_VERSION}" || test "${VELOCITY_VERSION}" == "latest"; then \
        echo "### Fetching latest version"; \
        WATERFALL_VERSION=$(\
            curl -sl https://fill.papermc.io/v3/projects/velocity | \
            jq -r '.versions["3.0.0"][0]' \
        ); \
    fi && \
    echo "### Using version <${VELOCITY_VERSION}>" && \
    DOWNLOAD_URL=$(\
        curl -sl "https://fill.papermc.io/v3/projects/velocity/versions/${WATERFALL_VERSION}/builds" | \
        jq -r 'first(.[] | select(.channel == "STABLE") | .downloads."server:default".url) // "null"' \
    ) && \
    echo "### Downloading <${DOWNLOAD_URL}>" && \
    curl -lfso velocity.jar "${DOWNLOAD_URL}"

FROM eclipse-temurin:${JAVA_VERSION}
RUN useradd --create-home --shell /bin/bash minecraft \
 && mkdir -p /opt/velocity /velocity \
 && chown -R minecraft /velocity/
COPY --from=waterfall /velocity.jar /opt/velocity/
USER minecraft
WORKDIR /velocity
VOLUME /velocity
EXPOSE 25565
ENV JAVA_MEM=1G
CMD java -Xms${JAVA_MEM} -Xmx${JAVA_MEM} -jar /opt/velocity/velocity.jar
