services:
  # Docker-in-Docker backend so CI jobs run in isolated containers,
  # not against the host Docker daemon.
  docker-in-docker:
    image: docker:dind
    container_name: forgejo-runner-dind
    privileged: true
    environment:
      DOCKER_TLS_CERTDIR: /certs
    volumes:
      - runner-certs:/certs/client
      - forgejo-runner-dind:/var/lib/docker
    networks:
      forgejo-runner:
        # DinD's TLS cert is issued for the SAN "docker"; alias so the
        # runner can verify the cert when connecting over TLS.
        aliases:
          - docker
    restart: unless-stopped

  forgejo-runner:
    image: code.forgejo.org/forgejo/runner:${RUNNER_VERSION:-6}
    container_name: forgejo-runner
    environment:
      DOCKER_HOST: tcp://docker:2376
      DOCKER_CERT_PATH: /certs/client
      DOCKER_TLS_VERIFY: "1"
      FORGEJO_INSTANCE_URL: ${FORGEJO_INSTANCE_URL}
      FORGEJO_RUNNER_TOKEN: ${FORGEJO_RUNNER_TOKEN}
      FORGEJO_RUNNER_NAME: ${FORGEJO_RUNNER_NAME:-forgejo-runner}
    entrypoint: ["/bin/sh", "-c"]
    command:
      - |
        set -e
        if [ ! -f /data/.runner ]; then
          echo "Registering runner with ${FORGEJO_INSTANCE_URL} ..."
          forgejo-runner register --no-interactive \
            --instance "${FORGEJO_INSTANCE_URL}" \
            --token "${FORGEJO_RUNNER_TOKEN}" \
            --name "${FORGEJO_RUNNER_NAME}" \
            --labels "docker:docker://node:20-bookworm,ubuntu-latest:docker://node:20-bookworm"
        fi
        exec forgejo-runner daemon
    working_dir: /data
    volumes:
      - forgejo-runner-data:/data
      - runner-certs:/certs/client:ro
    networks:
      - forgejo-runner
      - traefik
    depends_on:
      - docker-in-docker
    restart: unless-stopped

volumes:
  forgejo-runner-data:
    name: forgejo-runner-data
  forgejo-runner-dind:
    name: forgejo-runner-dind
  runner-certs:
    name: forgejo-runner-certs

networks:
  forgejo-runner:
    name: forgejo-runner
  traefik:
    name: traefik
    external: true
