FROM --platform=$BUILDPLATFORM nixos/nix:latest AS nix

WORKDIR /src
COPY flake.nix flake.lock ./

FROM nix AS deps

ARG EXTRA_PLATFORMS="i686-linux"

RUN rootfs=$(nix build --impure --extra-experimental-features "nix-command flakes" \
              --option sandbox false --option extra-platforms "${EXTRA_PLATFORMS}" \
              --print-out-paths --no-link ".#packages.x86_64-linux.base-rootfs") \
 && printf '%s' "$rootfs" > /base-rootfs

FROM deps AS base

RUN rootfs=$(cat /base-rootfs) \
 && mkdir -p /out \
 && cp -a --parents $(nix-store -qR "$rootfs") /out \
 && cp -a "$rootfs/." /out/

FROM deps AS target

# Keep source changes out of the shared dependency and runtime stages.
COPY overflow.c ./

ARG TASK=1
ARG PART=A
ARG BUFSIZE=64
ARG FLAG="flag{this_is_still_not_the_real_flag}"
ARG FLAGNAME=""
ARG EXTRA_PLATFORMS="i686-linux"

RUN binary=$(PART="$PART" FLAG="$FLAG" FLAGNAME="$FLAGNAME" BUFSIZE="$BUFSIZE" nix build --impure --extra-experimental-features "nix-command flakes" \
              --option sandbox false --option extra-platforms "${EXTRA_PLATFORMS}" \
              --print-out-paths --no-link ".#packages.x86_64-linux.task${TASK}-b${BUFSIZE}") \
 && mkdir -p /out/bin \
 && cp -a --parents $(nix-store -qR "$binary") /out \
 && ln -s "$binary/bin/overflow" /out/bin/overflow \
 && if [ "$TASK" = 3 ] && [ "$PART" = B ]; then BIN=4755; else BIN=0555; fi \
 && chown 0:0 "/out$(readlink /out/bin/overflow)" \
 && chmod "$BIN" "/out$(readlink /out/bin/overflow)"

FROM deps AS flags

ARG TASK=1
ARG PART=A
ARG FLAG="flag{this_is_still_not_the_real_flag}"
ARG FLAGNAME=""

RUN files=$(PART="$PART" FLAG="$FLAG" FLAGNAME="$FLAGNAME" nix build --impure --extra-experimental-features "nix-command flakes" \
              --option sandbox false \
              --print-out-paths --no-link ".#packages.x86_64-linux.flag-rootfs") \
 && mkdir -p /out \
 && cp -a --parents $(nix-store -qR "$files") /out \
 && cp -a "$files/." /out/ \
 && if [ "$TASK" = 3 ] && [ "$PART" = B ]; then OWNER=0:0; else OWNER=1000:1000; fi \
 && chown "$OWNER" "/out$(readlink /out/home/player/*)" \
 && chmod 0400 "/out$(readlink /out/home/player/*)"

FROM scratch

COPY --from=base /out/ /
COPY --from=target /out/ /
COPY --from=flags /out/ /

USER player
WORKDIR /home/player
EXPOSE 1337

CMD ["/bin/socat", "TCP-LISTEN:1337,reuseaddr,fork", "EXEC:/bin/overflow,stderr"]
