# https://github.com/docker/build-push-action#usage

name: Docker
on:
  push:
    branches:
      - dev
    tags:
      - '*'

jobs:
  publish:
    name: Publish
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0

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

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v1
        with:
          buildkitd-flags: "--debug"

      - name: Cache Docker layers
        uses: actions/cache@v2
        with:
          path: /tmp/.buildx-cache
          key: ${{ runner.os }}-buildx-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-buildx-

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

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v1 
        with:
          registry: ghcr.io
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GHCR_TOKEN }}

      - name: Build dev branch and push
        if: github.ref == 'refs/heads/dev'
        uses: docker/build-push-action@v2
        with:
          context: .
          platforms: linux/amd64,linux/arm/v7,linux/arm64
          push: true
          tags: 'nadoo/glider:dev,ghcr.io/nadoo/glider:dev'
          cache-from: type=local,src=/tmp/.buildx-cache
          cache-to: type=local,mode=max,dest=/tmp/.buildx-cache

      - name: Get all docker tags
        if: startsWith(github.ref, 'refs/tags/')
        uses: actions/github-script@v3
        id: tags
        with:
          script: |
            const ref = `${context.payload.ref.replace(/\/?refs\/tags\//, '')}`
            const tags = [
              'nadoo/glider:latest',
              `nadoo/glider:${ref}`,
              'ghcr.io/nadoo/glider:latest',
              `ghcr.io/nadoo/glider:${ref}`
            ]
            return tags.join(',')
          result-encoding: string

      - name: Build release and push
        if: startsWith(github.ref, 'refs/tags/')
        uses: docker/build-push-action@v2
        with:
          context: .
          platforms: linux/amd64,linux/arm/v7,linux/arm64
          push: true
          tags: ${{steps.tags.outputs.result}}
          cache-from: type=local,src=/tmp/.buildx-cache
          cache-to: type=local,mode=max,dest=/tmp/.buildx-cache
