name: docker-build-e2e-node

on:
  workflow_dispatch:
  push:
    branches:
      - main
      - v0.38.x
      - v1.x
      - v2.x
    tags:
      - "v[0-9]+.[0-9]+.[0-9]+"
      - "v[0-9]+.[0-9]+.[0-9]+-alpha.[0-9]+"
      - "v[0-9]+.[0-9]+.[0-9]+-beta.[0-9]+"
      - "v[0-9]+.[0-9]+.[0-9]+-rc[0-9]+"

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

env:
  DOCKER_ORG: cometbft
  DOCKER_IMAGE: e2e-node

jobs:
  vars:
    runs-on: ubuntu-latest
    outputs:
      repo: ${{ steps.set.outputs.repo }}
      tags: ${{ steps.set.outputs.tags }}
    steps:
      - id: set
        run: |
          REPO="${DOCKER_ORG}/${DOCKER_IMAGE}"
          VERSION="${GITHUB_REF_NAME}"

          TAGS="${REPO}:${VERSION}"
          if [ "$VERSION" = "main" ]; then
            TAGS="${TAGS:+$TAGS,}$REPO:latest"
          fi

          echo "repo=${REPO}" >> $GITHUB_OUTPUT
          echo "tags=${TAGS}" >> $GITHUB_OUTPUT

  build-images:
    needs: vars
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-24.04
            arch: amd64
          - os: ubuntu-24.04-arm
            arch: arm64
    runs-on: ${{ matrix.os }}
    outputs:
      digest-amd64: ${{ steps.digest.outputs.digest-amd64 }}
      digest-arm64: ${{ steps.digest.outputs.digest-arm64 }}
    steps:
      - id: tags
        run: |
          TAGS=$(echo "${{ needs.vars.outputs.tags }}" | sed "s/[^,]*/&-${{ matrix.arch }}/g")
          echo "tags=${TAGS}" >> $GITHUB_OUTPUT

      - uses: actions/checkout@v4
      - uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      - uses: docker/setup-buildx-action@v3
      - uses: docker/build-push-action@v6
        id: build
        with:
          platforms: linux/${{ matrix.arch }}
          context: .
          file: ./test/e2e/docker/Dockerfile
          push: true
          tags: ${{ steps.tags.outputs.tags }}

      - id: digest
        run: echo "digest-${{ matrix.arch }}=${{ steps.build.outputs.digest }}" >> $GITHUB_OUTPUT

  merge-images:
    runs-on: ubuntu-latest
    needs:
      - vars
      - build-images
    steps:
      - uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      - run: |
          TAGS="${{ needs.vars.outputs.tags }}"
          docker buildx imagetools create \
            $(printf -- '--tag %s ' ${TAGS//,/ }) \
            ${{ needs.vars.outputs.repo }}@${{ needs.build-images.outputs.digest-amd64 }} \
            ${{ needs.vars.outputs.repo }}@${{ needs.build-images.outputs.digest-arm64 }}
