FROM node:22-bookworm-slim AS openwork-builder

WORKDIR /src

RUN apt-get update \
  && apt-get install -y --no-install-recommends ca-certificates curl git unzip \
  && npm install -g bun \
  && corepack enable \
  && rm -rf /var/lib/apt/lists/*

COPY . .

RUN pnpm install --frozen-lockfile --trust-lockfile --filter openwork-server... \
  && pnpm --filter openwork-server build \
  && pnpm --filter openwork-server build:bin

FROM node:22-bookworm-slim

ARG OPENWORK_SERVER_VERSION
ARG OPENCODE_VERSION
ARG OPENCODE_DOWNLOAD_URL=

RUN apt-get update \
  && apt-get install -y --no-install-recommends ca-certificates curl tar unzip \
  && rm -rf /var/lib/apt/lists/*

COPY --from=openwork-builder /src/apps/server/dist/bin/openwork-server /usr/local/bin/openwork-server
COPY --from=openwork-builder /src/apps/server/dist/opencode-plugins /opt/openwork/opencode-plugins
COPY --from=openwork-builder /src/constants.json /usr/local/constants.json
COPY packaging/docker/microsandbox-entrypoint.sh /usr/local/bin/microsandbox-entrypoint.sh

RUN set -eux; \
  test -n "$OPENWORK_SERVER_VERSION"; \
  test -n "$OPENCODE_VERSION"; \
  arch="$(dpkg --print-architecture)"; \
  case "$arch" in \
    amd64) asset="opencode-linux-x64-baseline.tar.gz" ;; \
    arm64) asset="opencode-linux-arm64.tar.gz" ;; \
    *) echo "unsupported architecture: $arch" >&2; exit 1 ;; \
  esac; \
  url="$OPENCODE_DOWNLOAD_URL"; \
  if [ -z "$url" ]; then \
    url="https://github.com/anomalyco/opencode/releases/download/v${OPENCODE_VERSION}/${asset}"; \
  fi; \
  tmpdir="$(mktemp -d)"; \
  curl -fsSL "$url" -o "$tmpdir/$asset"; \
  tar -xzf "$tmpdir/$asset" -C "$tmpdir"; \
  binary="$(find "$tmpdir" -type f -name opencode | head -n 1)"; \
  test -n "$binary"; \
  install -m 0755 "$binary" /usr/local/bin/opencode; \
  chmod +x /usr/local/bin/microsandbox-entrypoint.sh; \
  rm -rf "$tmpdir"

RUN test -f /opt/openwork/opencode-plugins/openwork-extensions-preview.js \
  && test -f /opt/openwork/opencode-plugins/openwork-capabilities-knowledge.js \
  && test -f /opt/openwork/opencode-plugins/openwork-office-attachments.js \
  && test -f /opt/openwork/opencode-plugins/openwork-anthropic-adaptive-thinking.js \
  && test -f /opt/openwork/opencode-plugins/openwork-anthropic-tool-schema.js \
  && test "$(openwork-server --version)" = "$OPENWORK_SERVER_VERSION" \
  && opencode --version

ENV OPENWORK_EXTENSIONS_PLUGIN_DIR=/opt/openwork/opencode-plugins
ENV OPENWORK_DATA_DIR=/data/openwork-server
ENV OPENWORK_SIDECAR_DIR=/data/sidecars
ENV OPENWORK_WORKSPACE=/workspace

EXPOSE 8787

VOLUME ["/workspace", "/data"]

HEALTHCHECK --interval=10s --timeout=5s --start-period=20s --retries=12 \
  CMD /bin/sh -c 'curl -fsS "http://127.0.0.1:${OPENWORK_PORT:-8787}/health" >/dev/null || exit 1'

ENTRYPOINT ["/usr/local/bin/microsandbox-entrypoint.sh"]
