stages:
  - 'build'
  - 'push'

variables:
  DOCKER_HOST: 'tcp://dockerd:2376'
  DOCKER_TLS_SAN: 'DNS:dockerd'
  DOCKER_TLS_CERTDIR: '/certs'
  DOCKER_DRIVER: 'overlay2'

default:
  image: 'docker.io/docker:latest'
  services:
    - name: 'docker.io/docker:dind'
      alias: 'dockerd'

.anchors:
  - &cmd_install_packages 'apk add --no-cache coreutils git m4 make zstd'
  - &cmd_docker_login_registry 'docker login -u "${CI_REGISTRY_USER:?}" -p "${CI_REGISTRY_PASSWORD:?}" "${CI_REGISTRY:?}"'
  - &matrix_arch ['amd64', 'arm64v8']
  - &regex_version '/^v[0-9]+$/'

build:native:
  stage: 'build'
  except: [*regex_version]
  before_script:
    - *cmd_install_packages
  script:
    - 'make IMAGE_BUILD_OPTS="--pull" build-native-image save-native-image'
  artifacts:
    expire_in: '1 day'
    paths:
      - './dist/'

build:cross:
  stage: 'build'
  only: [*regex_version]
  parallel:
    matrix:
      - ARCH: *matrix_arch
  before_script:
    - *cmd_install_packages
  script:
    - 'make binfmt-register'
    - 'make IMAGE_BUILD_OPTS="--pull" "build-${ARCH:?}-image" "save-${ARCH:?}-image"'
  artifacts:
    expire_in: '1 week'
    paths:
      - './dist/'

push:cross:
  stage: 'push'
  needs: ['build:cross']
  only: [*regex_version]
  parallel:
    matrix:
      - ARCH: *matrix_arch
  before_script:
    - *cmd_install_packages
    - *cmd_docker_login_registry
  script:
    - 'make "load-${ARCH:?}-image" "push-${ARCH:?}-image"'

push:manifest:
  stage: 'push'
  needs: ['push:cross']
  only: [*regex_version]
  variables:
    DOCKER_CLI_EXPERIMENTAL: 'enabled'
  before_script:
    - *cmd_install_packages
    - *cmd_docker_login_registry
  script:
    - 'make push-cross-manifest'
