FROM rust:1.70-alpine3.18 AS builder

ARG DI_VER=1.2.5

WORKDIR /app

COPY . ./

RUN apk add --no-cache build-base unzip curl && \
    curl -Lo - "https://github.com/Yelp/dumb-init/archive/refs/tags/v${DI_VER}.tar.gz" | tar -xzf - && \
    cd "dumb-init-${DI_VER}" && \
    make SHELL=/bin/sh && \
    mv dumb-init ..

RUN cargo build && \
    [ "$(readelf -d target/debug/alex | grep NEEDED | wc -l)" = 0 ]


# We use ${:-} instead of a default value because the argument is always passed
# to the build, it'll just be blank most likely
FROM eclipse-temurin:18-jre-alpine

# Build arguments
ARG MC_VERSION=1.19.4
ARG PAPERMC_VERSION=525

RUN addgroup -Sg 1000 paper && \
    adduser -SHG paper -u 1000 paper

# Create worlds and config directory
WORKDIR /app
RUN mkdir -p worlds config/cache backups

# Download server file
ADD "https://papermc.io/api/v2/projects/paper/versions/$MC_VERSION/builds/$PAPERMC_VERSION/downloads/paper-$MC_VERSION-$PAPERMC_VERSION.jar" server.jar

# Make sure the server user can access all necessary folders
RUN chown -R paper:paper /app

# Store the cache in an anonymous volume, which means it won't get stored in the other volumes
VOLUME /app/config/cache
VOLUME /app/backups

COPY --from=builder /app/dumb-init /bin/dumb-init
COPY --from=builder /app/target/debug/alex /bin/alex

RUN chmod +x /bin/alex

# Default value to keep users from eating up all ram accidentally
ENV ALEX_XMS=1024 \
    ALEX_XMX=2048 \
    ALEX_JAR=/app/server.jar \
    ALEX_CONFIG_DIR=/app/config \
    ALEX_WORLD_DIR=/app/worlds \
    ALEX_BACKUPS_DIR=/app/backups \
    ALEX_SERVER_VERSION="${MC_VERSION}-${PAPERMC_VERSION}"

# Document exposed ports
EXPOSE 25565

# Switch to non-root user
USER paper:paper

ENTRYPOINT ["/bin/dumb-init", "--"]
CMD ["/bin/alex", "paper"]