# Some refs :
# - Starting : https://docs.docker.com/ci-cd/github-actions/
# - More details here : https://github.com/marketplace/actions/build-and-push-docker-images#update-dockerhub-repo-description
# - Variables (contexts) : https://docs.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions#github-context

name: Docker Hub

on:
  push:
    branches:
      - master
    tags:
      - 'v*.*.*'
  pull_request:
    branches:
      - 'master'

jobs:

  build-publish:
    name: Build, Publish
    environment: prod
    runs-on: ubuntu-latest
    steps:

    - name: Checkout
      uses: actions/checkout@v3.1.0

    - name: Docker meta
      id: docker_meta
      uses: docker/metadata-action@v3
      with:
        # list of Docker images to use as base name for tags
        images: nicolabs/musiccast-repairkit
        # See https://github.com/docker/metadata-action#tags-input
        tags: |
          type=schedule
          type=ref,event=branch
          type=ref,event=tag
          type=ref,event=pr
          type=sha
          type=semver,pattern={{version}}
          type=semver,pattern={{major}}.{{minor}}
          type=semver,pattern={{major}}

    - name: Set up QEMU for multiarch
      uses: docker/setup-qemu-action@v1

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

    - name: Login to Docker Hub
      uses: docker/login-action@v1.9.0
      with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_ACCESS_TOKEN }}

    - name: Build and push image
      id: docker_build_alpine
      uses: docker/build-push-action@v2.4.0
      with:
          context: ./
          builder: ${{ steps.buildx.outputs.name }}
          platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64/v8,linux/ppc64le,linux/s390x
          push: true
          tags: ${{ steps.docker_meta.outputs.tags }}
          labels: ${{ steps.docker_meta.outputs.labels }}

    - name: Image digest
      run: echo ${{ steps.docker_build_alpine.outputs.digest }}

  post:

    name: Update repo
    needs:
      - build-publish
    environment: prod
    runs-on: ubuntu-latest
    steps:

    - name: Checkout
      uses: actions/checkout@v3.1.0

    # https://github.com/peter-evans/dockerhub-description
    - name: Update repo description
      uses: peter-evans/dockerhub-description@v2.4.2
      with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_PASSWORD }}
          repository: nicolabs/musiccast-repairkit
