# This Dockerfile is intended for docker-compose only.
FROM index.docker.io/library/golang@sha256:68cb6d68bed024785b69195b89af7ac7a444f27791435f98647edff595aa0479 AS builder

USER root

WORKDIR /workspace

# Copy the Go Modules manifests
COPY go.mod go.mod
COPY go.sum go.sum
# cache deps before building and copying source so that we don't need to re-download as much
# and so that source changes don't invalidate our downloaded layer
RUN go mod download

ARG VERSION \
COMMIT \
BUILD_DATE

# Copy the entire Go module structure
COPY . .

# Build
RUN CGO_ENABLED=0 LDFLAGS="-s -w \
-X github.com/stacklok/toolhive/pkg/versions.Version=${VERSION} \
-X github.com/stacklok/toolhive/pkg/versions.Commit=${COMMIT} \
-X github.com/stacklok/toolhive/pkg/versions.BuildDate=${BUILD_DATE} \
-X github.com/stacklok/toolhive/pkg/versions.BuildType=release" \
GOOS=linux go build -ldflags "${LDFLAGS}" -o main ./cmd/thv-registry-api/main.go

# Use minimal base image to package the binary
FROM index.docker.io/library/alpine@sha256:5b10f432ef3da1b8d4c7eb6c487f2f5a8f096bc91145e68878dd4a5019afde11

COPY --from=builder /workspace/main /thv-registry-api
COPY LICENSE /licenses/LICENSE

# Create working directory, data directory, and home directory for user 1001
# User 1001 needs a home directory for the pgpass file
RUN mkdir -p /app/data /home/appuser && \
    chown -R 1001:1001 /app /home/appuser

# Create pgpass file for PostgreSQL authentication
# Format: hostname:port:database:username:password
RUN cat > /home/appuser/.pgpass <<'EOF'
postgres:5432:registry:db_app:app_password
postgres:5432:registry:db_migrator:migration_password
EOF

# Set proper ownership and permissions (0600) for pgpass file
RUN chown 1001:1001 /home/appuser/.pgpass && \
    chmod 0600 /home/appuser/.pgpass

WORKDIR /app

# Set HOME environment variable for user 1001
ENV HOME=/home/appuser

USER 1001

# Migrations run automatically when the server starts with "serve" command
ENTRYPOINT ["/thv-registry-api"]
