# Image derived from OpenCode with git and init script
# Usage: podman build -t arche-workspace .

ARG OPENCODE_VERSION

FROM docker.io/golang:1.22-alpine AS workspace-agent
WORKDIR /src
COPY workspace-agent/go.mod ./
COPY workspace-agent/main.go ./
RUN CGO_ENABLED=0 go build -o /workspace-agent

FROM ghcr.io/anomalyco/opencode:${OPENCODE_VERSION}

# Install git (required for KB sync)
USER root
RUN apk add --no-cache ca-certificates git nodejs npm

# Install global OpenCode custom tools configuration.
WORKDIR /opt/arche/opencode-config
COPY opencode-config/package.json /opt/arche/opencode-config/package.json
RUN npm install --omit=dev
RUN mkdir -p /opt/arche/opencode-config/shared /opt/arche/opencode-config/tools
COPY opencode-config/shared/*.js /opt/arche/opencode-config/shared/
COPY opencode-config/tools/*.js /opt/arche/opencode-config/tools/

# Create non-root user for running the workspace
RUN addgroup -g 1000 workspace && \
    adduser -u 1000 -G workspace -h /home/workspace -s /bin/sh -D workspace && \
    mkdir -p /workspace /kb /user-data && \
    chown -R workspace:workspace /workspace /kb /user-data

# Workspace agent (HTTP API for git/file ops)
COPY --from=workspace-agent /workspace-agent /usr/local/bin/workspace-agent

# Workspace initialization script
COPY init-workspace.sh /usr/local/bin/init-workspace.sh
RUN chmod +x /usr/local/bin/init-workspace.sh

# Entrypoint wrapper that initializes workspace before starting OpenCode
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh

# Keep root user for compatibility with Podman named volumes created as root.
# OpenCode still binds to an internal network and uses HTTP basic auth.
USER root
WORKDIR /workspace

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