name: Docker CI

on:
  push:
    tags: 
     - 'v*'

jobs:
  docker-build:
    strategy:
      matrix:
        arch: [amd64, arm64]
    runs-on: ubuntu-latest
    steps:
      - name: Checkout project
        uses: actions/checkout@v2

      - name: Login to DockerHub
        uses: docker/login-action@v1 
        with:
          username: wantguns
          password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}

      - name: Building the ${{ matrix.arch }} image
        run: |
          docker build . \
            -t wantguns/bin:${{ matrix.arch }} \
            --build-arg ARCH=${{ matrix.arch }}
          mkdir -p artifacts/images
          docker save wantguns/bin:${{ matrix.arch }} > artifacts/images/${{ matrix.arch }}.tar

      - name: Pushing the ${{ matrix.arch }} image
        run: |
          docker push wantguns/bin:${{ matrix.arch }}

      - name: Temporarily saving the image
        uses: actions/upload-artifact@v2
        with:
          name: docker-artifacts
          path: artifacts/images
          retention-days: 1 


  docker-push:
    needs: docker-build
    runs-on: ubuntu-latest
    steps:
      - name: Login to DockerHub
        uses: docker/login-action@v1 
        with:
          username: wantguns
          password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}

      - name: Retrieve saved images
        uses: actions/download-artifact@v2
        with:
          name: docker-artifacts
          path: artifacts/images

      - name: Docker load images
        run: |
          pushd artifacts/images
          docker load < amd64.tar
          docker load < arm64.tar

      - name: Creating a multi-arch manifest
        run: |
          docker manifest create \
            wantguns/bin:latest \
            --amend wantguns/bin:amd64 \
            --amend wantguns/bin:arm64
          
          docker manifest annotate wantguns/bin:latest \
            wantguns/bin:arm64 --arch arm64

      - name: Push the manifest
        run: |
          docker manifest push wantguns/bin:latest