ARG BASE_IMAGE=ghcr.io/openclaw/openclaw:latest
FROM $BASE_IMAGE

USER root

RUN apt-get update && apt-get install -y --no-install-recommends \
        tini \
        podman \
        fuse-overlayfs \
        crun \
        uidmap \
        slirp4netns \
        ca-certificates \
        # Chromium/Playwright runtime dependencies
        libnss3 libnss3-tools libnspr4 libatk1.0-0 libatk-bridge2.0-0 \
        libcups2 libdrm2 libxkbcommon0 libatspi2.0-0 libxcomposite1 \
        libxdamage1 libxfixes3 libxrandr2 libgbm1 libpango-1.0-0 \
        libcairo2 libasound2 fonts-liberation xdg-utils \
    && rm -rf /var/lib/apt/lists/*

# Allow rootless podman for the node user (uid 1000). Recent openclaw
# images already ship a node entry in /etc/subuid and /etc/subgid;
# appending a second, overlapping range makes newuidmap reject the
# mapping, so nested `podman run` inside the cage fails. Only add an
# entry when one is missing.
RUN if ! grep -qE '^node:' /etc/subuid; then echo "node:100000:65536" >> /etc/subuid; fi \
 && if ! grep -qE '^node:' /etc/subgid; then echo "node:100000:65536" >> /etc/subgid; fi

# Create user-level containers config so rootless podman uses the
# bind-mounted /var/lib/containers volume instead of ~/.local/share
RUN mkdir -p /home/node/.config/containers \
 && printf '[storage]\ndriver = "overlay"\ngraphroot = "/var/lib/containers/storage"\nrunroot = "/run/containers/storage"\n\n[storage.options.overlay]\nmount_program = "/usr/bin/fuse-overlayfs"\n' \
    > /home/node/.config/containers/storage.conf \
 && chown -R node:node /home/node/.config

# Install matrix extension dependencies for older base images that didn't
# hoist them. openclaw 2026.4+ stages runtime deps into /app/node_modules
# AND uses workspace:* devDependency refs that break plain `npm install`;
# the canary (matrix-js-sdk presence in /app/node_modules) distinguishes
# the two layouts.
RUN if [ -d /app/extensions/matrix ] && [ -f /app/extensions/matrix/package.json ] \
        && [ ! -d /app/node_modules/matrix-js-sdk ]; then \
        cd /app/extensions/matrix && npm install --omit=dev; \
    fi

# openclaw 2026.4+ bundles extensions with self-references like
#   import { X } from "openclaw/plugin-sdk/..."
# but the bundled extension dir has its own package.json (name
# "@openclaw/matrix"), so Node's self-reference doesn't resolve to the
# openclaw root. Link /app (name "openclaw") under node_modules so the
# import walks up and resolves via /app/package.json's exports map.
# Safe on older bases: they don't have the bundled extension tree, the
# symlink just goes unused.
RUN mkdir -p /app/node_modules \
 && ln -sfn /app /app/node_modules/openclaw

COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh

ENTRYPOINT ["tini", "--"]

USER node
