# 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=layertools -jar application.jar extract

# 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-alpine

# 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 apk add --no-cache su-exec tini shadow gcompat

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

WORKDIR /opt/gameyfin

# Create user and required directories
RUN groupadd -g "$GID" "$USER" && \
    useradd -u "$UID" -g "$GID" -M -s /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.sh /entrypoint.sh

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

EXPOSE 8080

ENTRYPOINT ["/sbin/tini", "--", "/entrypoint.sh"]
