# Database Gateway Cloudron Package
#
# Database Gateway (dbgw) is a web gateway for secure, policy-controlled
# access to PostgreSQL databases: users log in via OIDC and every query is
# parsed and authorized by embedded OPA policies (per user, target,
# operation and table) before it reaches a remote database. Query results
# are stored in a local PostgreSQL storage with shareable links.
#
# Upstream: https://github.com/kazhuravlev/database-gateway (v0.24.0, Go 1.26, Echo)
#   - Single Go binary; the frontend is already built and embedded in the
#     repo (internal/facade/ui/dist via go:embed), so no Node stage needed
#   - Listens on 0.0.0.0:8080; config file passed with `-c config.json`
#   - Storage schema applied via the `migrate-up` subcommand (embedded SQL)
#
# Authentication: NATIVE OIDC (preferred). start.sh wires the Cloudron
# platform OIDC provider (CLOUDRON_OIDC_ISSUER / CLIENT_ID / CLIENT_SECRET)
# into /app/data/config.json on first run; roles map from the Cloudron
# `groups` claim (admins -> admin, users -> user).
#
# NOTE on base images: the SQL parser is a cgo binding (libpg_query), so the
# binary MUST be built with CGO_ENABLED=1 — a static CGO_ENABLED=0 build
# fails with `undefined: pg.Parse`. A musl-linked binary then needs a musl
# runtime, hence alpine:3.23 (same as upstream's own image) instead of the
# usual cloudron/base (Ubuntu/glibc).
FROM golang:1.26-alpine AS builder

ARG VERSION=v0.24.0

WORKDIR /src

# Mirrors the upstream Dockerfile build dependencies (git for module
# fetches, gcc/musl-dev for the CGO-enabled build).
RUN apk add --no-cache ca-certificates git gcc musl-dev

# Cache dependency downloads separately from source changes.
COPY repo/go.mod repo/go.sum ./
RUN go mod download

COPY repo/ .
RUN CGO_ENABLED=1 go build \
        -ldflags "-s -w -X github.com/dev-services42/version.version=${VERSION}" \
        -o /out/database-gateway \
        ./cmd/gateway

# Same runtime base as the upstream image. The tools back start.sh:
# bash (script), postgresql16-client (wait for the Cloudron PG addon),
# jq (seed config.json), openssl (cookie secret).
FROM alpine:3.23

RUN apk add --no-cache bash ca-certificates jq openssl postgresql16-client

COPY --from=builder /out/database-gateway /usr/local/bin/database-gateway

# start.sh waits for the postgresql addon, seeds /app/data/config.json and
# /app/data/opa/ on first run, applies migrations, then execs the gateway.
# Made executable on the host, not at build time (Cloudron builds hit
# permission errors on RUN chmod).
COPY start.sh /app/start.sh

ENV WORKDIR=/app/data
WORKDIR ${WORKDIR}

EXPOSE 8080

CMD ["/bin/bash", "/app/start.sh"]
