# syntax=docker/dockerfile:1.4

FROM eclipse-temurin:21-jre-alpine as builder
WORKDIR /opt/gameyfin
ARG JAR_FILE=./app/build/libs/app.jar
COPY ${JAR_FILE} application.jar
RUN java -Djarmode=tools -jar application.jar extract --layers --launcher --destination extracted

# Pre-collect plugin JARs so final stage can copy them in a single layer
COPY --link ./plugins/ /tmp/plugins/
RUN mkdir -p /opt/gameyfin/plugins \
    && find /tmp/plugins -type f -path "*/build/libs/*.jar" -exec cp {} /opt/gameyfin/plugins/ \; \
    && rm -rf /tmp/plugins


FROM eclipse-temurin:21-jre

# OCI labels
LABEL maintainer="grimsi" \
      org.opencontainers.image.title="Gameyfin" \
      org.opencontainers.image.description="Manage your video games. simple/fast/FOSS" \
      org.opencontainers.image.url="https://gameyfin.org" \
      org.opencontainers.image.source="https://github.com/gameyfin/gameyfin" \
      org.opencontainers.image.licenses="AGPL-3.0-only" \
      org.opencontainers.image.vendor="Gameyfin" \
      org.opencontainers.image.authors="Gameyfin maintainers"

# Indicate docker runtime environment
ENV RUNTIME_ENV=docker

# Install necessary packages
RUN apt-get update && \
    apt-get install -y --no-install-recommends tini gosu && \
    rm -rf /var/lib/apt/lists/*

# Fixed runtime user/group
ENV USER=gameyfin
ARG UID=1337
ARG GID=1337

WORKDIR /opt/gameyfin

# Create user and required directories with fixed IDs
RUN groupadd -g "$GID" "$USER" && \
    useradd -u "$UID" -g "$GID" -M -s /usr/sbin/nologin "$USER" && \
    mkdir -p plugins plugindata db data logs && \
    chown -R "$UID:$GID" .

# Copy entrypoint script with proper perms and ownership
COPY --link --chown=${UID}:${GID} --chmod=0755 ./docker/entrypoint.ubuntu.sh /entrypoint.sh

# Copy application layers and plugin jars from builder stage
COPY --from=builder --link --chown=${UID}:${GID} /opt/gameyfin/extracted/dependencies/ ./
COPY --from=builder --link --chown=${UID}:${GID} /opt/gameyfin/extracted/spring-boot-loader/ ./
COPY --from=builder --link --chown=${UID}:${GID} /opt/gameyfin/extracted/snapshot-dependencies/ ./
COPY --from=builder --link --chown=${UID}:${GID} /opt/gameyfin/extracted/application/ ./
COPY --from=builder --link --chown=${UID}:${GID} /opt/gameyfin/plugins ./plugins

EXPOSE 8080

ENTRYPOINT ["/usr/bin/tini", "--", "/entrypoint.sh"]