name: Build docker image

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

on:
  push:
    branches:
      - v8
    tags:
      - '*'

permissions:
  contents: read

jobs:
  build-docker:
    permissions:
      packages: write
    strategy:
      matrix:
        image:
          - ubuntu-latest
          - ubuntu-24.04-arm
        include:
          - image: ubuntu-latest
            arch: amd64
          - image: ubuntu-24.04-arm
            arch: arm64
    runs-on: ${{ matrix.image }}
    steps:
      - uses: actions/checkout@v4

      # https://github.com/docker/setup-buildx-action
      - name: Set up Docker Buildx
        id: buildx
        uses: docker/setup-buildx-action@v3

      - name: Upload docker image
        env:
          EVENT_NAME: ${{ github.event_name }}
          REF: ${{ github.ref }}
          ACTOR: ${{ github.repository_owner }}
          PLATFORM: ${{ matrix.image }}
        run: |
          echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
          docker buildx build --platform linux/${{ matrix.arch }} . -f tests/dockerfiles/Dockerfile -t danog/madelineproto:next-debian-${{ matrix.arch }} --cache-from danog/madelineproto:next-debian-${{ matrix.arch }} --cache-to type=inline --push

  merge-docker:
    permissions:
      packages: write
    needs: build-docker
    runs-on: ubuntu-latest
    steps:
      - name: Set up Docker Buildx
        id: buildx
        uses: docker/setup-buildx-action@v3

      - name: Upload final docker image
        env:
          EVENT_NAME: ${{ github.event_name }}
          REF: ${{ github.ref }}
          ACTOR: ${{ github.repository_owner }}
        run: |
          echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
          docker buildx imagetools create -t danog/madelineproto:debian danog/madelineproto:next-debian-{arm,amd}64
          docker buildx imagetools create -t danog/madelineproto:next danog/madelineproto:next-debian-{arm,amd}64
          docker buildx imagetools create -t danog/madelineproto:latest danog/madelineproto:next-debian-{arm,amd}64
