FROM julia:1.12.5-trixie AS builder

RUN apt-get update && apt-get install -y build-essential && rm -rf /var/lib/apt/lists/*

ENV JULIA_DEPOT_PATH="/opt/julia_depot"
ENV HOME="/tmp"

WORKDIR /app

COPY Project.toml Manifest.toml ./
RUN julia -e 'using Pkg; Pkg.add("PackageCompiler")'
RUN julia --project=/app -e 'using Pkg; Pkg.instantiate()'

# Use a placeholder source file so dependency setup is stable until server code changes.
RUN mkdir -p src && echo "module CodeExecutionServer; end" > src/CodeExecutionServer.jl
COPY scripts/build_sysimage.jl scripts/precompile_workload.jl ./scripts/

# Build worker-only sysimage (Oscar/IOCapture/Distributed).
RUN julia --project=/app scripts/build_sysimage.jl

COPY src/ ./src/
COPY scripts/run_server.jl ./scripts/run_server.jl

# Precompile project with real server code (native cache for server deps).
RUN julia --project=/app -e 'using Pkg; Pkg.precompile()'

# Warm worker startup path so first addprocs does not trigger costly first-load compilation.
RUN julia --sysimage=/app/worker_sysimage.so --project=/app -e 'using CodeExecutionServer'


FROM julia:1.12.5-trixie AS runtime

ENV JULIA_DEPOT_PATH="/opt/julia_depot"
ENV HOME="/tmp"

WORKDIR /app

RUN useradd -m -s /bin/bash sandbox

# Copy only runtime artifacts from builder stage.
COPY --from=builder --chown=sandbox:sandbox /opt/julia_depot /opt/julia_depot
COPY --from=builder --chown=sandbox:sandbox /app/Project.toml /app/Manifest.toml ./
COPY --from=builder --chown=sandbox:sandbox /app/src ./src
COPY --from=builder --chown=sandbox:sandbox /app/scripts/run_server.jl ./scripts/
COPY --from=builder --chown=sandbox:sandbox /app/worker_sysimage.so /app/worker_sysimage.so

ENV WORKER_SYSIMAGE_PATH="/app/worker_sysimage.so"

USER sandbox

EXPOSE 8080

CMD ["julia", "--project=/app", "scripts/run_server.jl"]
