ARG AWS_ACCOUNT=086679231553

ARG BASE_IMAGE=${AWS_ACCOUNT}.dkr.ecr.us-east-1.amazonaws.com/docker-parent-images:java25


# Build stage
FROM --platform=linux/amd64 ${BASE_IMAGE} AS build
WORKDIR /workspace

# Copy Maven Wrapper and files needed for dependency resolution first.
COPY .mvn .mvn
COPY mvnw mvnw.cmd ./
COPY pom.xml ./
COPY style-suppressions.xml ./

# Make Maven Wrapper executable.
# Make Maven Wrapper executable and ensure worker owns workspace.
USER root
RUN useradd -m -s /bin/bash worker || true && \
    sed -i 's/\r$//' ./mvnw && \
    chmod +x ./mvnw && \
    chown -R worker:worker /workspace

USER worker

# Download Maven via wrapper and cache dependencies.
RUN ./mvnw dependency:go-offline

# Copy source after dependency layer for better Docker cache usage.
COPY src ./src

# Build the Spring Boot application and skip tests.
RUN mkdir -p /workspace/target && ./mvnw -DskipTests package

# Test stage for running tests in docker-compose
FROM build AS tests
WORKDIR /workspace

USER root
RUN mkdir -p /var/app/reports /var/app/sonar-classes && \
    chown -R worker:worker /var/app/reports /var/app/sonar-classes

COPY test_scripts/ ./test_scripts/
RUN chmod +x ./test_scripts/*.sh && \
    chown -R worker:worker ./test_scripts

RUN cp -r /workspace/target/classes/* /var/app/sonar-classes/

USER worker

# Runtime stage
FROM --platform=linux/amd64 ${BASE_IMAGE}
WORKDIR /app

# The following Spring Boot properties are loaded from the container environment at runtime.
# Provide them with docker run -e, docker compose, Kubernetes env, or your host/container environment.
#   KAFKA_BOOTSTRAP_SERVERS
#   MONGODB_URI
#   KAFKA_TOPIC_CLEARANCE
#   LOGGING_LEVEL_HIERDISPATCHER
#   LOGGING_LEVEL_KAFKA

# Copy the built jar from the build stage.
COPY --from=build /workspace/target/*.jar app.jar

# Expose common Spring Boot port. Override as needed with Docker run options.
EXPOSE 8080

# Download Datadog Java APM agent for distributed tracing
# Patch vulnerable system packages (libssh2, perl, curl)
USER root
RUN apt-get update && \
    apt-get upgrade -y && \
    apt-get install -y curl && \
    curl -Lo /app/dd-java-agent.jar https://dtdg.co/latest-java-tracer && \
    chown worker:worker /app/dd-java-agent.jar && \
    rm -rf /var/lib/apt/lists/*

USER worker

# Use Datadog Java agent with the application

ENTRYPOINT ["java", "-javaagent:/app/dd-java-agent.jar", "-jar", "/app/app.jar"]
