# syntax=docker/dockerfile:1.6

FROM amazonlinux:2023.5.20241001.1 AS prepare
WORKDIR /pd-rs

RUN yum install -y findutils && yum clean all

COPY . .
RUN mkdir -p /output
RUN for component in $(find . -type f -name 'Cargo.toml' -exec dirname {} \; | sort -u); do \
  mkdir -p "/output/${component}/src" \
  && touch "/output/${component}/src/lib.rs" \
  && cp "${component}/Cargo.toml" "/output/${component}/Cargo.toml" \
  ; done
RUN cp Cargo.lock /output/Cargo.lock

FROM amazonlinux:2023.5.20241001.1 AS builder
WORKDIR /workspace/pd-rs

ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
ENV PATH=/root/.cargo/bin/:$PATH

RUN yum clean all && yum makecache
RUN yum install -y \
  make glibc-devel gcc gcc-c++ patch \
  perl cmake3 git curl-minimal unzip pkgconfig openssl-devel ca-certificates && \
  yum clean all

RUN ARCH=$(arch | sed s/aarch64/aarch_64/) && \
  curl -fLo /tmp/protoc.zip https://github.com/protocolbuffers/protobuf/releases/download/v3.14.0/protoc-3.14.0-linux-${ARCH}.zip && \
  unzip -o /tmp/protoc.zip -d /usr/local && \
  rm -f /tmp/protoc.zip

RUN curl https://sh.rustup.rs -sSf | sh -s -- --no-modify-path --default-toolchain stable -y

COPY --from=prepare /output/ ./

COPY . .

ARG PD_TSO_GIT_HASH=None
ARG PD_TSO_GIT_REF=None
ARG PD_TSO_BUILD_TIME=None
ENV PD_TSO_GIT_HASH=${PD_TSO_GIT_HASH}
ENV PD_TSO_GIT_REF=${PD_TSO_GIT_REF}
ENV PD_TSO_BUILD_TIME=${PD_TSO_BUILD_TIME}
RUN --mount=type=cache,target=/root/.cargo/registry \
  --mount=type=cache,target=/root/.cargo/git \
  --mount=type=cache,target=/workspace/pd-rs/target,sharing=locked \
  make build && \
  cp /workspace/pd-rs/target/release/pd-tso /pd-tso

FROM amazonlinux:2023.5.20241001.1

RUN dnf update -y && dnf install -y procps-ng ca-certificates && dnf clean all

ENV PD_TSO_LISTEN_ADDR=0.0.0.0:3379

COPY --from=builder /pd-tso /pd-tso

EXPOSE 3379

ENTRYPOINT ["/pd-tso"]
