# Build stage
ARG DOCKER_MIRROR=""
FROM ${DOCKER_MIRROR}rust:1.85-alpine AS builder

# Use Aliyun mirrors for faster package downloads in China
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

RUN apk add --no-cache musl-dev pkgconfig openssl-dev openssl-libs-static

# Configure cargo to use rsproxy.cn mirror for crates
RUN mkdir -p /usr/local/cargo && printf '[source.crates-io]\nreplace-with = "rsproxy-sparse"\n\n[source.rsproxy-sparse]\nregistry = "sparse+https://rsproxy.cn/index/"\n\n[net]\ngit-fetch-with-cli = true\n' > /usr/local/cargo/config.toml

# Static OpenSSL linking
ENV OPENSSL_STATIC=1

WORKDIR /app

# Copy manifests
COPY Cargo.toml Cargo.lock ./
COPY migration/Cargo.toml ./migration/

# Create dummy files to build dependencies
RUN mkdir src && echo "fn main() {}" > src/main.rs
RUN mkdir -p migration/src && echo "fn main() {}" > migration/src/main.rs && echo "" > migration/src/lib.rs

# Downgrade home crate to version compatible with Rust 1.85
RUN cargo update home@0.5.12 --precise 0.5.9 || true

# Build dependencies only
RUN cargo build --release

# Remove dummy files
RUN rm -rf src migration/src

# Copy actual source code
COPY src ./src
COPY migration/src ./migration/src

# Build the actual application
RUN touch src/main.rs migration/src/main.rs migration/src/lib.rs
RUN cargo build --release

# Runtime stage
FROM ${DOCKER_MIRROR}alpine:3.21

# Use Aliyun mirrors
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

RUN apk add --no-cache ca-certificates libgcc

WORKDIR /app

# Copy the binary from builder
COPY --from=builder /app/target/release/backend_rust /app/backend_rust

# Create uploads directory
RUN mkdir -p /app/uploads/avatars

EXPOSE 4000

CMD ["/app/backend_rust"]
