stages:
  - 'build:images'
  - 'push:images'
  - 'push:manifests'

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

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

.cmds:
  - &cmd_install_build_packages 'apk add --no-cache coreutils git m4 make zstd'
  - &cmd_install_push_packages  'apk add --no-cache coreutils git make zstd'
  - &cmd_docker_login_registry  'docker login -u "${CI_REGISTRY_USER:?}" -p "${CI_REGISTRY_PASSWORD:?}" "${CI_REGISTRY:?}"'

.regexes:
  - &regex_version '/^v[0-9]+$/'

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

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

build:images:amd64:
  extends: '.build:images:cross'
  variables: {ARCH: 'amd64'}

build:images:arm64v8:
  extends: '.build:images:cross'
  variables: {ARCH: 'arm64v8'}

.push:images:cross:
  stage: 'push:images'
  only: [*regex_version]
  before_script:
    - *cmd_install_push_packages
    - *cmd_docker_login_registry
  script:
    - 'make "load-${ARCH:?}-image" "push-${ARCH:?}-image"'

push:images:amd64:
  extends: '.push:images:cross'
  dependencies: ['build:images:amd64']
  variables: {ARCH: 'amd64'}

push:images:arm64v8:
  extends: '.push:images:cross'
  dependencies: ['build:images:arm64v8']
  variables: {ARCH: 'arm64v8'}

push:manifests:cross:
  stage: 'push:manifests'
  dependencies: ['push:images:amd64', 'push:images:arm64v8']
  only: [*regex_version]
  variables:
    DOCKER_CLI_EXPERIMENTAL: 'enabled'
  before_script:
    - *cmd_install_push_packages
    - *cmd_docker_login_registry
  script:
    - 'make push-cross-manifest'
