name: CI
on:
  push:
    branches: [ main, master ]
    tags:
      - v*
  pull_request:
    branches: [ main, master ]
  workflow_dispatch:

jobs:
  build:
    permissions:
      contents: write
      packages: write
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - name: Set up Go
        uses: actions/setup-go@v6
        with:
          go-version-file: 'go.mod'

      # local build
      - name: Compile the binary
        run: |
          make bin/goldpinger
          ./bin/goldpinger -h

      # simple Docker build
      - name: Build the Docker image
        run: |
          make build
          docker run `make version` --help

      - name: Login to DockerHub
        uses: docker/login-action@v3
        if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
        with:
          username: ${{ secrets.DOCKERHUB_USER }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      # multi-arch build
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v5
        with:
          bake-target: docker-metadata-action
          images: |
            ${{ github.repository_owner }}/goldpinger
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=semver,pattern={{version}}
          labels: |
            org.opencontainers.image.title=${{ github.repository }}
            org.opencontainers.image.description=Goldpinger makes calls between its instances to monitor your networking. It runs as a DaemonSet on Kubernetes and produces Prometheus metrics that can be scraped, visualised and alerted on.
            org.opencontainers.image.vendor=${{ github.repository_owner }}

      - name: Build regular image
        uses: docker/bake-action@v6
        with:
          targets: ci
          push: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') }}
          files: |
            ./docker-bake.hcl
            cwd://${{ steps.meta.outputs.bake-file }}

      # https://github.com/docker/buildx/issues/2105
      - name: Create manifest
        if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
        run: |
          set -xe
          for image in $images; do
            docker buildx imagetools create -t "${image}" "${image}-linux" "${image}-windows-ltsc2019" "${image}-windows-ltsc2022"
          done
        env:
          images: "${{ join( steps.meta.outputs.tags, ' ') }}"
