# syntax=docker/dockerfile:1

# ---------------------------------------------------------------------------
# Stage 1 — compile the Tailwind stylesheet.
#
# Tailwind scans the server-side templates in pb_hooks/ (all markup is produced
# by render.js) and the browser glue in public/. Styling therefore lives in two
# places only: the design tokens in tailwind/input.css and the class names used
# in pb_hooks/lib/render.js.
# ---------------------------------------------------------------------------
FROM node:22-alpine AS css

WORKDIR /build

# Same relative layout as the repo root so the @source globs in input.css
# (../pb_hooks, ../public) resolve identically here and in the editor.
COPY tailwind ./tailwind
COPY pb_hooks ./pb_hooks
COPY public ./public

RUN cd ./tailwind \
 && npm install --no-audit --no-fund \
 && npx @tailwindcss/cli -i ./input.css -o ../public/assets/app.css --minify

# ---------------------------------------------------------------------------
# Stage 2 — PocketBase runtime.
#
# PocketBase ships no official image, so we unpack the pinned release zip and
# bake pb_hooks/, pb_migrations/ and public/ next to the binary. Only pb_data
# is a volume, which keeps the running container fully immutable.
# ---------------------------------------------------------------------------
FROM alpine:3.21

ARG PB_VERSION

RUN apk add --no-cache ca-certificates tzdata

# unzip and wget come from busybox. Map the build host arch to a release arch.
RUN set -eux; \
    case "$(uname -m)" in \
      x86_64)  PB_ARCH=amd64 ;; \
      aarch64) PB_ARCH=arm64 ;; \
      armv7l)  PB_ARCH=armv7 ;; \
      *) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;; \
    esac; \
    wget -q -O /tmp/pb.zip \
      "https://github.com/pocketbase/pocketbase/releases/download/v${PB_VERSION}/pocketbase_${PB_VERSION}_linux_${PB_ARCH}.zip"; \
    unzip -q /tmp/pb.zip -d /pb; \
    rm -f /tmp/pb.zip; \
    chmod +x /pb/pocketbase; \
    /pb/pocketbase --version

WORKDIR /pb

# htmx is self-hosted so the site has no runtime CDN dependency. Pinned to an
# exact version; bump HTMX_VERSION here when upgrading.
ARG HTMX_VERSION=2.0.4
RUN set -eux; \
    mkdir -p /pb/public/assets/vendor; \
    wget -q -O /pb/public/assets/vendor/htmx.min.js \
      "https://cdn.jsdelivr.net/npm/htmx.org@${HTMX_VERSION}/dist/htmx.min.js"; \
    test -s /pb/public/assets/vendor/htmx.min.js

COPY pb_hooks ./pb_hooks
COPY pb_migrations ./pb_migrations
COPY public ./public
# Overwrite the source placeholder with the compiled, minified stylesheet.
COPY --from=css /build/public/assets/app.css ./public/assets/app.css
COPY entrypoint.sh /entrypoint.sh

RUN chmod +x /entrypoint.sh && mkdir -p /pb/pb_data

ENV PB_DATA_DIR=/pb/pb_data
EXPOSE 8090

# Probe readiness with GET http://<host>:8090/api/health
ENTRYPOINT ["/entrypoint.sh"]
