name: Build sandbox image

# Builds the Nucleic sandbox image and pushes it to GHCR, where the macOS app pulls it at runtime
# (ContainerEngine, when the container service is enabled). Bump IMAGE_TAG in lockstep with
# `ProjectSandbox.defaultImage` (Sources/NucleicCore/Project.swift) whenever the Dockerfile changes.
#
# The `nucleic-sandbox` GHCR package may stay PRIVATE: the app authenticates the pull with the
# user's GitHub token (needs `read:packages`) — see ContainerEngine.registryAuth, configurable in
# Settings → Sandbox or via NUCLEIC_REGISTRY_USER/NUCLEIC_REGISTRY_TOKEN. Make it public only if you
# prefer anonymous pulls.

on:
  push:
    branches: [main, dev]
    paths:
      - containers/nucleic-sandbox/**
      - .github/workflows/sandbox-image.yml
  workflow_dispatch:
    inputs:
      tag:
        description: "Image tag to push (must match ProjectSandbox.defaultImage)"
        required: false
        default: v5

env:
  # Sandbox runs are arm64 (Apple silicon hosts). Keep in sync with ProjectSandbox.defaultImage.
  # v4 adds control-bridge.js (required by the default-on vsock control plane) + the Codex/Grok CLIs.
  # v5 adds openssh-client (ssh-keygen) so the agent can sign commits with gpg.format=ssh.
  IMAGE_TAG: v5

jobs:
  build-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4

      - name: Resolve image reference
        id: ref
        run: |
          owner="$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')"
          tag="${{ github.event.inputs.tag || env.IMAGE_TAG }}"
          echo "image=ghcr.io/${owner}/nucleic-sandbox" >> "$GITHUB_OUTPUT"
          echo "tag=${tag}" >> "$GITHUB_OUTPUT"

      - uses: docker/setup-qemu-action@v3      # enables linux/arm64 builds on x86 runners
      - uses: docker/setup-buildx-action@v3

      - name: Log in to GHCR
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push (linux/arm64)
        uses: docker/build-push-action@v6
        with:
          context: containers/nucleic-sandbox
          file: containers/nucleic-sandbox/Dockerfile
          platforms: linux/arm64
          push: true
          tags: |
            ${{ steps.ref.outputs.image }}:${{ steps.ref.outputs.tag }}
            ${{ steps.ref.outputs.image }}:latest
          provenance: false   # plain OCI image index the containerization ImageStore pulls cleanly
