# PostgreSQL with pgvector and gosu built from source
#
# gosu is built from source with Go 1.26 to eliminate 6 Go stdlib CVEs
# (CVE-2025-68121 CRITICAL + 5 HIGH) present in the tianon/gosu pre-built binary.

# Stage 1: Build gosu from source with Go 1.26
FROM golang:1.26-alpine AS gosu-builder
RUN apk add --no-cache git
RUN git clone --branch 1.17 https://github.com/tianon/gosu.git /src/gosu
WORKDIR /src/gosu
RUN go build -v -ldflags '-s -w' -o /bin/gosu .

FROM postgres:17.7-alpine3.22

LABEL maintainer="Mosaic Stack <dev@mosaic.local>"
LABEL description="PostgreSQL 17 with pgvector extension and patched gosu"

# Copy gosu binary built from source in the gosu-builder stage
COPY --from=gosu-builder /bin/gosu /usr/local/bin/gosu
RUN chmod +x /usr/local/bin/gosu && gosu nobody true

# Update Alpine packages for any remaining OS-level patches
RUN apk update && apk upgrade

# Install build dependencies for pgvector
RUN apk add --no-cache --virtual .build-deps \
    git \
    build-base

# Clone and build pgvector v0.7.4 (without LLVM bitcode compilation)
RUN git clone --branch v0.7.4 https://github.com/pgvector/pgvector.git /tmp/pgvector \
    && cd /tmp/pgvector \
    && make OPTFLAGS="" with_llvm=no \
    && make install with_llvm=no \
    && rm -rf /tmp/pgvector

# Clean up build dependencies to reduce image size
RUN apk del .build-deps

# Copy initialization scripts
COPY init-scripts/ /docker-entrypoint-initdb.d/

# Expose PostgreSQL port
EXPOSE 5432
