version: 2.1
jobs:
  dockerhubuploadrelease:
    docker:
      - image: docker:git
    steps:
      - checkout
      - docker_prepare
      - run: docker login --username $DOCKER_HUB_USERNAME --password $DOCKER_HUB_PASSWORD
      # for release builds, we want to get the amd64 image out asap, so first
      # we do an amd64-only build, before following up with a multiarch build.
      - docker_build:
          tag: -t matrixdotorg/synapse:${CIRCLE_TAG}
          platforms: linux/amd64
      - docker_build:
          tag: -t matrixdotorg/synapse:${CIRCLE_TAG}
          platforms: linux/amd64,linux/arm64

  dockerhubuploadlatest:
    docker:
      - image: docker:git
    steps:
      - checkout
      - docker_prepare
      - run: docker login --username $DOCKER_HUB_USERNAME --password $DOCKER_HUB_PASSWORD
      # for `latest`, we don't want the arm images to disappear, so don't update the tag
      # until all of the platforms are built.
      - docker_build:
          tag: -t matrixdotorg/synapse:latest
          platforms: linux/amd64,linux/arm64

workflows:
  build:
    jobs:
      - dockerhubuploadrelease:
          filters:
            tags:
              only: /v[0-9].[0-9]+.[0-9]+.*/
            branches:
              ignore: /.*/
      - dockerhubuploadlatest:
          filters:
            branches:
              only: [ master, main ]

commands:
  docker_prepare:
    description: Sets up a remote docker server, downloads the buildx cli plugin, and enables multiarch images
    parameters:
      buildx_version:
        type: string
        default: "v0.4.1"
    steps:
      - setup_remote_docker:
          # 19.03.13 was the most recent available on circleci at the time of
          # writing.
          version: 19.03.13
      - run: apk add --no-cache curl
      - run: mkdir -vp ~/.docker/cli-plugins/ ~/dockercache
      - run: curl --silent -L "https://github.com/docker/buildx/releases/download/<< parameters.buildx_version >>/buildx-<< parameters.buildx_version >>.linux-amd64" > ~/.docker/cli-plugins/docker-buildx
      - run: chmod a+x ~/.docker/cli-plugins/docker-buildx
      # install qemu links in /proc/sys/fs/binfmt_misc on the docker instance running the circleci job
      - run: docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
      # create a context named `builder` for the builds
      - run: docker context create builder
      # create a buildx builder using the new context, and set it as the default
      - run: docker buildx create builder --use

  docker_build:
    description: Builds and pushed images to dockerhub using buildx
    parameters:
      platforms:
        type: string
        default: linux/amd64
      tag:
        type: string
    steps:
      - run: docker buildx build -f docker/Dockerfile --push --platform << parameters.platforms >> --label gitsha1=${CIRCLE_SHA1} << parameters.tag >> --progress=plain .
