# Dockerfile for cross-compiling Go program with CGO dependencies
FROM golang:1.24-bookworm AS go-builder

# Install cross-compilation tools and dependencies
RUN apt-get update && apt-get install -y \
    gcc-x86-64-linux-gnu \
    g++-x86-64-linux-gnu \
    libc6-dev-amd64-cross \
    pkg-config \
    build-essential \
    && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /app

# Copy Go module files first for better caching
COPY go.mod go.sum ./

# Copy only necessary delta-rs-golang Go files (exclude target directory)
# This must be done before go mod download because of the replace directive
COPY delta-rs-golang/go.mod delta-rs-golang/go.sum ./delta-rs-golang/
COPY delta-rs-golang/*.go ./delta-rs-golang/
COPY delta-rs-golang/include/ ./delta-rs-golang/include/

# Copy vendor directory to avoid network dependencies during build
# Copy vendor_cross_compile directly as vendor
COPY vendor_cross_compile/ ./vendor/

# Copy only necessary source files for Go build
COPY cmd/ ./cmd/
COPY pkg/ ./pkg/

# Set environment variables for cross-compilation
ENV CGO_ENABLED=1
ENV GOOS=linux
ENV GOARCH=amd64
ENV CC=x86_64-linux-gnu-gcc
ENV CXX=x86_64-linux-gnu-g++
ENV CGO_LDFLAGS="-lstdc++"
ENV PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig

# For CGO linking during build, we need the library
# Place it in vendor's expected location
RUN mkdir -p vendor/github.com/tidbcloud/metering/delta-rs-golang/target/debug
COPY build/so/libdeltalake_golang.so vendor/github.com/tidbcloud/metering/delta-rs-golang/target/debug/libdeltalake_golang.so

# Build the Go binary with CGO
RUN go build -mod=vendor -v -o /tmp/nextgen-metering-server ./cmd/nextgenmetering

# Create output stage
FROM alpine:3.18 AS output
RUN apk add --no-cache file
COPY --from=go-builder /tmp/nextgen-metering-server /tmp/
RUN file /tmp/nextgen-metering-server
CMD ["sh"]