name: Docker builds

on:
  pull_request:
    branches: [master]
  push:
    branches: [master]
    tags:
      - v*

env:
  DOCKER_USERNAME: viktorstrate
  DOCKER_IMAGE: viktorstrate/photoview
  DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}

jobs:
  build:
    name: Build Docker Image
    runs-on: ubuntu-20.04

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

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

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v1
        with:
          platforms: ${{ matrix.target_platform }}

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

      - name: Docker Login
        if: success() && github.event_name != 'pull_request' && github.repository == 'photoview/photoview'
        uses: docker/login-action@v2
        with:
          username: ${{ env.DOCKER_USERNAME }}
          password: ${{ env.DOCKER_PASSWORD }}

      - name: Docker meta
        id: docker_meta
        uses: docker/metadata-action@v3
        with:
          # list of Docker images to use as base name for tags
          images: ${{ env.DOCKER_IMAGE }}
          # Docker tags based on the following events/attributes
          tags: |
            type=schedule
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=semver,pattern={{major}}
            type=sha

      - name: Build and push
        uses: docker/build-push-action@v2
        with:
          context: .
          platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6
          push: ${{ github.event_name != 'pull_request' && github.repository == 'photoview/photoview' }}
          tags: ${{ steps.docker_meta.outputs.tags }}
          labels: ${{ steps.docker_meta.outputs.labels }}
