FROM eclipse-temurin:24 AS build

WORKDIR /build

# Create as small a runtime as possible but Spring/Tomcat needs a lot of modules
RUN jlink \
    --output jre \
    --add-modules java.sql,java.desktop,java.management,java.naming,java.security.jgss,java.instrument

COPY pom.xml mvnw ./
COPY .mvn .mvn

RUN ./mvnw dependency:copy-dependencies \
    --activate-profiles=!persistent \
    --define includeScope=compile \
    --define outputDirectory=lib

RUN ./mvnw dependency:build-classpath \
    --activate-profiles=!persistent \
    --define includeScope=compile \
    --define mdep.outputFile=classpath \
    --define mdep.prefix=lib

COPY src src

RUN ./mvnw compile

FROM eclipse-temurin:24 AS training

WORKDIR /build
COPY --from=build /build/jre jre
COPY --from=build /build/lib lib
COPY --from=build /build/classpath classpath
COPY --from=build /build/target/classes classes

# There can be no directories on the classpath when training
RUN cd classes && jar -cf /build/app.jar *

# Adds the new jar to the classpath
RUN echo ":app.jar" >> classpath

RUN [ "./jre/bin/java" \
    , "-cp", "@classpath" \
    , "-XX:AOTMode=record" \
    , "-XX:AOTConfiguration=app.aotconf" \
    , "se.su.dsv.oauth2.Training" \
    , "--spring.profiles.active=dev,embedded" \
    ]

RUN [ "./jre/bin/java" \
    , "-cp", "@classpath" \
    , "-XX:AOTMode=create" \
    , "-XX:AOTConfiguration=app.aotconf" \
    , "-XX:AOTCache=app.aot" \
    , "se.su.dsv.oauth2.Training" \
    , "--spring.profiles.active=dev,embedded" \
    ]

FROM debian:stable-slim AS runtime

WORKDIR /app

COPY --from=training /build/jre jre
COPY --from=training /build/lib lib
COPY --from=training /build/classpath classpath
COPY --from=training /build/app.jar app.jar
COPY --from=training /build/app.aot app.aot

EXPOSE 8080

CMD [ "./jre/bin/java" \
    , "-cp", "@classpath" \
    , "-XX:AOTCache=app.aot" \
    , "se.su.dsv.oauth2.AuthorizationServer" \
    , "--spring.profiles.active=dev,embedded" \
    ]