FROM ci.nxtgauge.com/admin/rust:alpine AS builder

WORKDIR /app

RUN apk add --no-cache curl ca-certificates bash build-base musl-dev pkgconfig openssl-dev openssl-libs-static
RUN update-ca-certificates
RUN curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
ENV PATH="/root/.cargo/bin:${PATH}"
RUN rustup target add x86_64-unknown-linux-musl

COPY Cargo.toml Cargo.lock ./
COPY crates/db-migrate ./crates/db-migrate

# The root Cargo.toml's [workspace] members list includes every apps/* service,
# none of which are copied into this image (db-migrate has no path dependency
# on them - see crates/db-migrate/Cargo.toml). Restrict the workspace to just
# this crate so cargo doesn't fail trying to resolve manifests that don't exist
# in this build context (same trick Dockerfile.simple uses per-service).
RUN awk '\
  BEGIN { in_members = 0 } \
  /^members = \[/ { print "members = [\n  \"crates/db-migrate\"\n]"; in_members = 1; next } \
  in_members && /^\]/ { in_members = 0; next } \
  in_members { next } \
  { print } \
' Cargo.toml > Cargo.toml.trimmed && mv Cargo.toml.trimmed Cargo.toml

WORKDIR /app/crates/db-migrate
ENV OPENSSL_STATIC=1
ENV OPENSSL_DIR=/usr
RUN cargo build --release --bin db-migrate --target x86_64-unknown-linux-musl

FROM ci.nxtgauge.com/admin/alpine:3.20
RUN apk add --no-cache ca-certificates libpq

COPY --from=builder /app/target/x86_64-unknown-linux-musl/release/db-migrate /usr/local/bin/
COPY crates/db/migrations /migrations

ENTRYPOINT ["db-migrate"]
