name: docker build

on:
  push:
    branches:
      - 'main'
    tags:
      - '*'
  pull_request:
    branches:
      - 'main'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      -
        name: Checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 0
      -
        name: Set up Go
        uses: actions/setup-go@v3
        with:
          go-version: 1.18
      -
        name: Cache Go modules
        uses: actions/cache@v3
        with:
          path: |
            ~/.cache/go-build
            ~/go/pkg/mod
          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
          restore-keys: |
            ${{ runner.os }}-go-
      -
        name: Set up QEMU
        id: qemu
        uses: docker/setup-qemu-action@v2
      -
        name: Set up Docker Buildx
        id: buildx
        uses: docker/setup-buildx-action@v2
      -
        name: Check snapshot
        if: "!startsWith(github.ref, 'refs/tags/')"
        id: snapshot
        run: echo '::set-output name=ARG::--snapshot'
      -
        name: Run GoReleaser
        uses: goreleaser/goreleaser-action@v3
        with:
          distribution: goreleaser
          version: latest
          args: build --rm-dist --id docker ${{ steps.snapshot.outputs.ARG }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      -
        name: Docker meta
        id: meta
        uses: docker/metadata-action@v4
        with:
          images: xlh001/study_xxqg
          tags: |
            type=raw,value=latest
            type=ref,event=tag
      -
        name: Docker Login
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_PASSWORD }}
      -
        name: Build and push
        id: docker_build
        uses: docker/build-push-action@v3
        with:
          context: .
          push: ${{ github.event_name != 'pull_request' }}
          platforms: linux/amd64,linux/arm64
          tags: ${{ steps.meta.outputs.tags }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          shm-size: 2g
          ulimit: core=0:0
