# syntax=docker/dockerfile:1.7

ARG ALPINE_VERSION=3.23
ARG RUST_VERSION=1.90.0

FROM alpine:${ALPINE_VERSION} AS builder

ARG GREPTIMEDB_REF=main
ARG RUST_VERSION

RUN apk add --no-cache \
    bash \
    ca-certificates \
    curl \
    git \
    build-base \
    linux-headers \
    clang \
    lld \
    mold \
    cmake \
    make \
    perl \
    pkgconf \
    protobuf \
    protobuf-dev \
    zlib-dev \
    zlib-static \
    zstd-dev \
    zstd-static \
    openssl-dev \
    openssl-libs-static \
    binutils \
    coreutils

ENV RUSTUP_HOME=/usr/local/rustup
ENV CARGO_HOME=/usr/local/cargo
ENV PATH=/usr/local/cargo/bin:${PATH}
ENV CARGO_BUILD_JOBS=2
ENV LIBRARY_PATH=/usr/lib

RUN curl https://sh.rustup.rs -sSf | sh -s -- \
    -y \
    --profile minimal \
    --default-toolchain ${RUST_VERSION}

WORKDIR /src

RUN git clone https://github.com/GreptimeTeam/greptimedb.git . \
    && git checkout ${GREPTIMEDB_REF}

RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/usr/local/cargo/git \
    cargo build \
      --release \
      --locked \
      --bin greptime \
      --features servers/dashboard

RUN mkdir -p /out \
    && cp /src/target/release/greptime /out/greptime.debug \
    && cp /src/target/release/greptime /out/greptime \
    && strip /out/greptime \
    && ls -lh /out \
    && file /out/greptime \
    && ldd /out/greptime || true


FROM scratch AS artifact
COPY --from=builder /out/greptime /greptime
COPY --from=builder /out/greptime.debug /greptime.debug


FROM alpine:${ALPINE_VERSION} AS runtime
RUN apk add --no-cache ca-certificates
COPY --from=builder /out/greptime /usr/local/bin/greptime
ENTRYPOINT ["/usr/local/bin/greptime"]