version: '3.8'

# Based on combination of https://forgejo.org/docs/latest/admin/actions/ and
# https://code.forgejo.org/forgejo/runner/src/branch/main/examples/docker-compose/compose-forgejo-and-runner.yml
#
# Also configures a custom seccomp profile in runner config because the slash
# storage engine uses io_uring which the default profile does no allow, and
# this makes code tests fail during the build.

services:
  docker-in-docker:
    image: docker:dind
    hostname: docker # Must set hostname as TLS certificates are only valid for docker or localhost
    privileged: 'true'
    environment:
      DOCKER_TLS_CERTDIR: /certs
      DOCKER_HOST: docker-in-docker
    volumes:
      - /opt/forgejo-runner/docker_certs:/certs

  runner-register:
    image: 'code.forgejo.org/forgejo/runner:3.5.0'
    depends_on:
      docker-in-docker:
        condition: service_started
    # User without root privileges, but with access to `./data`.
    user: 1001:1001
    volumes:
      - /opt/forgejo-runner/data:/data
    command: >-
      bash -ec '
      while : ; do
        if [ -f .runner ]; then echo "runner already registered, exiting"; exit; fi
        forgejo-runner register --no-interactive --name <%= @networking['fqdn'] %> --instance https://platform.sunet.se --token <%= @runner_token %> --labels docker:docker://node:20-bookworm,ubuntu-22.04:docker://catthehacker/ubuntu:act-22.04 && break;
        sleep 1 ;
      done ;
      forgejo-runner generate-config > config.yml ;
      sed -i -e "s|network: .*|network: host|" config.yml ;
      sed -i -e "s|^  envs:$$|  envs:\n    DOCKER_HOST: tcp://docker:2376\n    DOCKER_TLS_VERIFY: 1\n    DOCKER_CERT_PATH: /certs/client|" config.yml ;
      sed -i -e "s|^  options:|  options: -v /certs/client:/certs/client --security-opt seccomp=/data/seccomp.json|" config.yml ;
      sed -i -e "s|  valid_volumes: \[\]$$|  valid_volumes:\n    - /certs/client|" config.yml ;
      '

  runner-daemon:
    image: code.forgejo.org/forgejo/runner:3.5.0
    user: 1001:1001
    links:
      - docker-in-docker
    depends_on:
      runner-register:
        condition: service_completed_successfully
    environment:
      DOCKER_HOST: tcp://docker:2376
      DOCKER_CERT_PATH: /certs/client
      DOCKER_TLS_VERIFY: "1"
    volumes:
      - /opt/forgejo-runner/data:/data
      - /opt/forgejo-runner/docker_certs:/certs
    command:
      - 'forgejo-runner'
      - '--config'
      - 'config.yml'
      - 'daemon'