# syntax = docker/dockerfile:1.11-labs

FROM input AS source
ARG git_checkout

ADD --link --keep-git-dir . /usr/src/tuwunel
WORKDIR /usr/src/tuwunel
RUN <<EOF
    set -eux
    git reset \
        --hard \
        --no-recurse-submodules \
        ${git_checkout}
EOF


FROM input AS ingredients
ARG rust_target
ARG rust_toolchain
ARG RUST_HOME
ARG RUSTUP_HOME
ARG CARGO_HOME
ARG CARGO_TARGET
ARG CARGO_TERM_VERBOSE=0
ARG RUST_BACKTRACE
ARG JEMALLOC_OVERRIDE
ARG ROCKSDB_LIB_DIR

WORKDIR /
COPY --link --from=rust ${RUST_HOME} ${RUST_HOME}
COPY --link --from=source /usr/src/tuwunel /usr/src/tuwunel

WORKDIR /usr/src/tuwunel
ENV PATH="${CARGO_HOME}/bin:$PATH"
ENV CARGO_TERM_VERBOSE="${CARGO_TERM_VERBOSE}"
ENV RUST_BACKTRACE="${RUST_BACKTRACE}"
ENV JEMALLOC_OVERRIDE="${JEMALLOC_OVERRIDE}"
ENV ROCKSDB_LIB_DIR="${ROCKSDB_LIB_DIR}"
RUN \
--mount=type=cache,dst=${RUSTUP_HOME}/downloads,sharing=locked \
--mount=type=cache,dst=${CARGO_HOME}/registry,sharing=locked \
--mount=type=cache,dst=${CARGO_HOME}/git,sharing=locked \
<<EOF
    set -eux
    git submodule update \
        --remote \
        --no-fetch \
        --recursive \
        --checkout \
        --init

    rustup run ${rust_toolchain} \
        cargo fetch \
            --locked \
            --target ${CARGO_TARGET}
EOF


FROM input AS preparing
ARG rust_target
ARG rust_toolchain
ARG RUSTUP_HOME
ARG CARGO_HOME
ARG CARGO_TARGET

WORKDIR /usr/src/tuwunel
RUN \
--mount=type=cache,dst=${RUSTUP_HOME}/downloads,sharing=locked \
--mount=type=cache,dst=${CARGO_HOME}/registry,sharing=locked \
--mount=type=cache,dst=${CARGO_HOME}/git,sharing=locked \
<<EOF
    set -euxo pipefail
    rustup run ${rust_toolchain} \
        cargo chef prepare \
            --recipe-path recipe.json

    manifest="Cargo.toml"
    package="rust-librocksdb-sys"
    cmd="cargo tree --manifest-path ${manifest} -f {r} -p ${package}"
    url="$(rustup run ${rust_toolchain} ${cmd} | head -n 1)"
    url="https://github.com/matrix-construct/rust-rocksdb" #TODO fixme
    echo "$url" > rocksdb.url

    sha1sum recipe.json rocksdb.url
EOF


FROM scratch AS recipe

WORKDIR /
COPY --from=preparing /usr/src/tuwunel/recipe.json .
COPY --from=preparing /usr/src/tuwunel/rocksdb.url .
