VERSION 0.8

FROM ubuntu:22.04
WORKDIR /workspace

# Install OS-dependencies.
RUN apt-get update && \
    apt-get install -y apt-transport-https wget gnupg gcc g++ gzip openjdk-11-jdk xz-utils

# Install Bazel.
ARG TARGETARCH
IF [ "$TARGETARCH" = amd64 ]
    ARG BAZELARCH=x86_64
ELSE
    ARG BAZELARCH=$TARGETARCH
END
RUN wget -q https://github.com/bazelbuild/bazel/releases/download/5.3.2/bazel-5.3.2-linux-$BAZELARCH -O /usr/local/bin/bazel && \
    chmod +x /usr/local/bin/bazel && \
    bazel && \ # Causes bazel to self-extract.
    bazel --version

code:
    COPY --dir BUILD WORKSPACE ./
    COPY --dir src ./

build:
    FROM +code
    # Save Bazel's cache as a cache directory. This directory will be reused
    # between runs.
    ARG bazel_cache = "/root/.cache/bazel"
    CACHE --persist "$bazel_cache"
    RUN bazel build --@io_bazel_rules_docker//transitions:enable=false //:ProjectRunner
    ARG bazel_out = "$(readlink -f ./bazel-out)"
    ARG bazel_bin = "$(readlink -f ./bazel-bin)"
    RUN chmod -R u+w "$bazel_out" # Some directories come out unwriteable.
    SAVE ARTIFACT "$bazel_bin" AS LOCAL earthly-bazel-bin

run:
    FROM +build
    RUN ./bazel-bin/ProjectRunner

image:
    FROM +code
    ARG bazel_cache = "/root/.cache/bazel"
    CACHE --persist "$bazel_cache"
    RUN bazel build --@io_bazel_rules_docker//transitions:enable=false //:ProjectRunnerImage
    ARG bazel_out_tar = $(bazel cquery --@io_bazel_rules_docker//transitions:enable=false ProjectRunnerImage-layer.tar --output starlark --starlark:expr=target.files.to_list\\(\\\)[0].path)
    # TODO: Earthly has no way of loading an image from a tar currently.
    #       The tar's contents could be unpacked into a directory, however,
    #       and that directory could become an image.
    SAVE ARTIFACT "$bazel_out_tar" /image.tar AS LOCAL ./earthly-bazel-tar/image.tar
