# Stage 1: Builder
FROM golang:1.27.4-trixie AS builder

# Install build tools and download utilities used by setup/build steps.
RUN apt-get update \
    && apt-get install -y --no-install-recommends build-essential curl ca-certificates git make \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Download the Linux FFI library so a fresh clone can build and open the dev container.
ARG TARGETARCH
ARG RELATE_VERSION=v1.5.0
RUN case "${TARGETARCH}" in \
      amd64) RELATE_TARGET="x86_64-unknown-linux-gnu" ;; \
      arm64) RELATE_TARGET="aarch64-unknown-linux-gnu" ;; \
      *) echo "Unsupported target architecture: ${TARGETARCH}" >&2; exit 1 ;; \
    esac \
    && curl -fsSL "https://github.com/relatedb/relate/releases/download/${RELATE_VERSION}/relate-ffi-${RELATE_TARGET}.tar.gz" -o /tmp/relate-ffi.tar.gz \
    && mkdir -p /tmp/relate-ffi \
    && tar -xzf /tmp/relate-ffi.tar.gz -C /tmp/relate-ffi --strip-components=1 \
    && cp /tmp/relate-ffi/librelate_ffi.so /usr/local/lib/librelate_ffi.so

# Copy the Go module files
COPY go.mod go.sum ./

# Initialize module and download dependencies
RUN go mod download

# Copy the CLI sources.
COPY cmd/ ./cmd/
COPY internal/ ./internal/
COPY docs/ ./docs/

# The Go module's cgo directives add -lrelate_ffi; provide the staged library path.
ENV CGO_LDFLAGS="-L/usr/local/lib"

ARG VERSION=dev
ARG COMMIT=none
ARG DATE=unknown

# Build the CLI.
RUN go build \
    -ldflags="-X main.Version=${VERSION} -X main.Commit=${COMMIT} -X main.Date=${DATE}" \
    -o /app/okf-relate ./cmd/okf-relate

# Stage 2: Runtime
# Use a minimal image that supports the C library dependencies
FROM debian:trixie-slim

# Install runtime dependencies for the C library (e.g., libgcc)
RUN apt-get update && apt-get install -y --no-install-recommends libgcc-s1 \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy the compiled CLI from the builder stage
COPY --from=builder /app/okf-relate /usr/local/bin/okf-relate

# Copy the Relate library downloaded in the builder stage.
COPY --from=builder /usr/local/lib/librelate_ffi.so /usr/local/lib/

# Set environment variables for the dynamic linker to find the library
ENV LD_LIBRARY_PATH="/usr/local/lib"

ENTRYPOINT ["okf-relate"]
CMD ["help"]