name: Publish Docker images

on:
  push:
    branches:
      - master
  release:
    types: [published]

jobs:
  build-platforms:
    name: Build Platforms
    runs-on: ubuntu-latest
    strategy:
      matrix:
        platform: [linux/amd64, linux/arm64]
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Determine version
        id: version
        run: |
          if [ "${{ github.event_name }}" = "release" ]; then
            echo "version=${{ github.event.release.tag_name }}" >> $GITHUB_OUTPUT
          else
            VERSION=$(grep '^version:' shard.yml | cut -d ' ' -f 2)
            echo "version=$VERSION" >> $GITHUB_OUTPUT
          fi

      - name: Build and push platform image
        uses: docker/build-push-action@v5
        env:
          CRYSTAL_WORKERS: ${{ matrix.platform == 'linux/amd64' && 4 || 2 }}
        with:
          context: .
          platforms: ${{ matrix.platform }}
          push: true
          tags: |
            sjdonado/bit:${{ steps.version.outputs.version }}-${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
          build-args: |
            TARGETARCH=${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

  create-manifest:
    name: Create Manifest
    runs-on: ubuntu-latest
    needs: build-platforms
    permissions:
      packages: write
    steps:
      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Determine version
        id: version
        run: |
          if [ "${{ github.event_name }}" = "release" ]; then
            echo "version=${{ github.event.release.tag_name }}" >> $GITHUB_OUTPUT
          else
            VERSION=$(grep '^version:' shard.yml | cut -d ' ' -f 2)
            echo "version=$VERSION" >> $GITHUB_OUTPUT
          fi

      - name: Create manifest
        run: |
          docker buildx imagetools create \
            -t sjdonado/bit:${{ steps.version.outputs.version }} \
            sjdonado/bit:${{ steps.version.outputs.version }}-{amd64,arm64}
