# syntax=docker/dockerfile:1.3-labs

FROM debian:bookworm-slim AS base
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update -y && \
    apt-get install -y --no-install-recommends \
        curl tini ca-certificates && \
    rm -rf /var/lib/apt/lists/*


# We use bookworm since the icu dependency ver. between the base and golang images is the same
FROM golang:1.25-bookworm AS build-from-source
ENV DEBIAN_FRONTEND=noninteractive
ARG DOLT_VERSION

# COPY doesn't support conditionals, so we rely on the path context to maybe have a dolt/ directory
# to distinguish between source and binary builds using DOLT_VERSION=source too.
COPY dolt*/go*/go.mod* /tmp/dolt/go/
WORKDIR /tmp/dolt/go/

# Check for source to avoid unnecessary installation of build dependencies
RUN if [ "$DOLT_VERSION" = "source" ]; then \
        cd /tmp/dolt/go || { echo "Make sure the `dolt/` directory exists in your workspace to build from source."; exit 1; }; \
        apt-get update -y && \
        apt-get install -y libicu-dev && \
        rm -rf /var/lib/apt/lists/*; \
    fi

# Separate layers to avoid redundant downloads
RUN if [ "$DOLT_VERSION" = "source" ]; then \
        go mod download; \
    fi

COPY dolt*/go/ /tmp/dolt/go/

RUN if [ "$DOLT_VERSION" = "source" ]; then \
        go build -o /usr/local/bin/dolt ./cmd/dolt && \
        chmod +x /usr/local/bin/dolt; \
    fi


FROM base AS download-binary
ARG DOLT_VERSION
RUN if [ "$DOLT_VERSION" = "latest" ]; then \
        # Fetch latest version number from GitHub API
        DOLT_VERSION=$(curl -s https://api.github.com/repos/dolthub/dolt/releases/latest \
            | grep '"tag_name"' \
            | cut -d'"' -f4 \
            | sed 's/^v//'); \
    fi && \
    if [ "$DOLT_VERSION" != "source" ]; then \
        curl -L "https://github.com/dolthub/dolt/releases/download/v${DOLT_VERSION}/install.sh" | bash; \
    fi


FROM base AS runtime
ARG DOLT_VERSION

RUN apt-get update -y && apt-get install -y --no-install-recommends bzip2 gzip xz-utils zstd \
  && rm -rf /var/lib/apt/lists/*
# icu dependency for source builds
RUN if [ "$DOLT_VERSION" = "source" ]; then \
        apt-get update -y && \
        apt-get install -y --no-install-recommends libicu-dev && \
        rm -rf /var/lib/apt/lists/*; \
    fi

# Only one binary is possible due to DOLT_VERSION, so we optionally copy from either stage
COPY --from=download-binary /usr/local/bin/dolt* /usr/local/bin/
COPY --from=build-from-source /usr/local/bin/dolt* /usr/local/bin/

RUN /usr/local/bin/dolt version

RUN mkdir /docker-entrypoint-initdb.d && \
    mkdir -p /var/lib/dolt && \
    chmod 755 /var/lib/dolt

COPY docker*/docker-entrypoint*.sh /usr/local/bin/
COPY dolt*/docker*/docker-entrypoint*.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

VOLUME /var/lib/dolt
EXPOSE 3306 33060 7007
WORKDIR /var/lib/dolt
ENTRYPOINT ["tini", "--", "docker-entrypoint.sh"]
