# syntax = docker/dockerfile:1.11-labs

FROM input AS rustup
ARG RUST_HOME
ARG rust_target
ARG rustup_version="1.28.2"
ARG rustup_profile="minimal"

WORKDIR /
COPY --link --from=input . .

WORKDIR ${RUST_HOME}
RUN <<EOF
    set -eux

    var="${rustup_version}/${rust_target}"
    url="https://static.rust-lang.org/rustup/archive/$var/rustup-init"
    curl -S -O -s "$url"
    chmod a+rx rustup-init
EOF

FROM input AS rust
ARG rust_toolchain
ARG rust_target
ARG RUST_HOME
ARG RUSTUP_HOME
ARG CARGO_HOME
ARG CARGO_TARGET
ARG rustup_version="1.28.1"
ARG rustup_profile="minimal"
ARG CARGO_TERM_VERBOSE
ARG rustup_components
ARG cargo_installs

WORKDIR /
COPY --link --from=input . .

WORKDIR ${RUST_HOME}
ENV CARGO_TARGET="${rust_target}"
ENV RUSTUP_HOME="${RUSTUP_HOME}"
ENV CARGO_HOME="${CARGO_HOME}"
ENV PATH="${CARGO_HOME}/bin:$PATH"
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
    ./rustup-init -y \
        --quiet \
        --profile "${rustup_profile}" \
        --default-host "${CARGO_TARGET}" \
        --default-toolchain "${rust_toolchain}" \
        --no-update-default-toolchain \
        --no-modify-path

    chmod -R a+rw $CARGO_HOME $RUSTUP_HOME
    rm rustup-init

    rustup component add \
        --toolchain ${rust_toolchain} \
        --target ${rust_target} \
        ${rustup_components} \
        ;

    rustup run --install ${rust_toolchain} \
        cargo install \
            --locked \
            --target ${rust_target} \
            ${cargo_installs} \
            ;
EOF
